#include #include #include #include #include "SCmathlib.h" using namespace std; double E_function(Vector &x); void dE_function(Vector &x, Vector &g); void lnsrch(int n, Vector &xold, double fold, Vector &g, Vector &p, Vector &x, double *f, double stpmax, int *check, double (*func)(Vector &p)); void dfpmin(Vector &p, int n, double gtol, int *iter, double *fret, double(*func)(Vector &p), void (*dfunc)(Vector &p, Vector &g)); static double sqrarg; #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 : sqrarg*sqrarg) static double maxarg1,maxarg2; #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1) > (maxarg2) ?\ (maxarg1) : (maxarg2)) // Main function begins here int main() { int n, iter; double gtol, fret; double alpha; n = 1; Vector g(n), p(n); cout << "Read in guess for alpha" << endl; cin >> alpha; // reserve space in memory for vectors containing the variational // parameters gtol = 1.0e-5; // now call dfmin and compute the minimum p(0) = alpha; dfpmin(p, n, gtol, &iter, &fret, E_function, dE_function); cout << "Value of energy minimum = " << fret << endl; cout << "Number of iterations = " << iter << endl; cout << "Value of alpha at minimum = " << p(0) << endl; return 0; } // end of main program // this function defines the Energy function double E_function(Vector &x) { double value = x(0)*x(0)*0.5+1.0/(8*x(0)*x(0)); return value; } // end of function to evaluate // this function defines the derivative of the energy void dE_function(Vector &x, Vector &g) { g(0) = x(0)-1.0/(4*x(0)*x(0)*x(0)); } // end of function to evaluate #define ITMAX 200 #define EPS 3.0e-8 #define TOLX (4*EPS) #define STPMX 100.0 void dfpmin(Vector &p, int n, double gtol, int *iter, double *fret, double(*func)(Vector &p), void (*dfunc)(Vector &p, Vector &g)) { int check,i,its,j; double den,fac,fad,fae,fp,stpmax,sum=0.0,sumdg,sumxi,temp,test; Vector dg(n), g(n), hdg(n), pnew(n), xi(n); Matrix hessian(n,n); fp=(*func)(p); (*dfunc)(p,g); for (i = 0;i < n;i++) { for (j = 0; j< n;j++) hessian(i,j)=0.0; hessian(i,i)=1.0; xi(i) = -g(i); sum += p(i)*p(i); } stpmax=STPMX*FMAX(sqrt(sum),(double)n); for (its=1;its<=ITMAX;its++) { *iter=its; lnsrch(n,p,fp,g,xi,pnew,fret,stpmax,&check,func); fp = *fret; for (i = 0; i< n;i++) { xi(i)=pnew(i)-p(i); p(i)=pnew(i); } test=0.0; for (i = 0;i< n;i++) { temp=fabs(xi(i))/FMAX(fabs(p(i)),1.0); if (temp > test) test=temp; } if (test < TOLX) { return; } for (i=0;i test) test=temp; } if (test < gtol) { return; } for (i=0;i EPS*sumdg*sumxi) { fac=1.0/fac; fad=1.0/fae; for (i=0;i stpmax) for (i=0;i test) test=temp; } alamin=TOLX/test; alam=1.0; for (;;) { for (i=0;i0.5*alam) tmplam=0.5*alam; } } alam2=alam; f2 = *f; fold2=fold; alam=FMAX(tmplam,0.1*alam); } } #undef ALF #undef TOLX