multiple nested member function?

In the below code I'm having trouble calculating the algebraic equation on the line marked with &&&. I attempt to calculate it both within the member function Energy(x) and within find_kin_en(x), but in the latter I find the result equal to zero, which is wrong and disagrees with the correct value calculated in Energy(x). I think the problem might be having multiple nested member functions, i.e. operator() calls Energy(x) which calls find_kin_en().

Anybody know if this is the problem? and what would fix it?

Thanks!
John



#include "/u7/tolsma/Numerical_Recipes/nr_c304/code/nr3.h" // these are numerical recipes libraries, not important for the problem below I believe.
#include "/u7/tolsma/Numerical_Recipes/nr_c304/code/mins.h"
#include "/u7/tolsma/Numerical_Recipes/nr_c304/code/mins_ndim.h"

struct Funcd{ // A functor that gets passed
to the numerical recipes libraries
(where the function Energy(x) is
Doub Energy (VecDoub_IO &x); minimized).
Doub find_kin_en (VecDoub_IO &nx);

Doub operator() (VecDoub_IO &x)
{
Doub retf;
retf = Energy(x);
return retf;
}
};

Doub Funcd::Energy (VecDoub_IO &x){
FILE *f1;
VecDoub xn(2);
Doub nE1u=x[0];
Doub nE1d=x[1];
Doub ekin,ekinN,edenN;
xn=x;
ekin = find_kin_en(xn);

//find_kin_en(xn) evaluates the same function
as given in the line below (i.e. the RHS of edenN)

edenN = (nE1u-3.3)*(nE1u-3.3)+(nE1d+2.2)*(nE1d+2.2) + 4.4;

// edenN should equal ekin, but they are NOT when written out. This is the problem!

f1=fopen("testeden.dat","a");
fprintf(f1,"%lf,%lf,%lf,%lf \n",nE1u,nE1d,edenN,ekinN); //compare column 3&4
fflush(f1);
fclose(f1);
return edenN;
};

Doub Funcd::find_kin_en(VecDoub_IO &xn)
{
Doub nE1u2=xn[0];
Doub nE1d2=xn[1];

ekintot=(nE1u2-3.3)*(nE1u2-3.3)+(nE1d2+2.2)*(nE1d2+2.2) + 4.4; &&&
return ekintot;
};

//It is clear that in this simple case I do not need to call the member function find_kin_en(xn) but could just as well evaluate it internally in the member function Energy(x). I'm doing it though because Energy(x) will need to call a bunch of other functions as well as find_kin_en(xn) when I get the whole code put together.

Int main(void) {

Doub xmin;
Funcd funcd;
Frprmn<Funcd> frprmn(funcd); // Frprmn is a numerical recipes functor that finds the minimum of the function funcd passed to it
VecDoub p(2);
FILE *f1,*f2;

p[0]=1.0; // initial guesses for the variable x[0] and x[1] used above.
p[1]=2.0;
p=frprmn.minimize(p);
xmin=frprmn.fret; // the minimum value of the function. when evaluated
using the included values, it should give 4.40.
return 0;
}




Last edited on
Please use code tags: [code]Your code[/code]
Read this: http://www.cplusplus.com/articles/z13hAqkS/

The problem with ekin = find_kin_en(xn); is that xn doesn't have the value of x. Why don't you just pass x?
Topic archived. No new replies allowed.