Documentation


golden.h

Go to the documentation of this file.
00001 #ifndef NR_GOLDEN_H
00002 #define NR_GOLDEN_H
00003 
00004 #include <math.h>
00005 
00006 namespace nr {
00007 
00015 template< class Real, class Func >
00016 Real golden (
00017     Real ax, Real bx, Real cx, 
00018     Func (*f),
00019     Real tol,
00020     Real *xmin)
00021 {
00022     const Real R = 0.61803399;
00023     const Real C = (1.0-R);
00024     #define SHFT2(a,b,c) (a)=(b);(b)=(c);
00025     #define SHFT3(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);
00026     Real f1,f2,x0,x1,x2,x3;
00027 
00028     x0=ax;
00029     x3=cx;
00030     if (fabs(cx-bx) > fabs(bx-ax)) {
00031         x1=bx;
00032         x2=bx+C*(cx-bx);
00033     } else {
00034         x2=bx;
00035         x1=bx-C*(bx-ax);
00036     }
00037     f1=(*f)(x1);
00038     f2=(*f)(x2);
00039     while (fabs(x3-x0) > tol*(fabs(x1)+fabs(x2))) {
00040         if (f2 < f1) {
00041             SHFT3(x0,x1,x2,R*x1+C*x3)
00042             SHFT2(f1,f2,(*f)(x2))
00043         } else {
00044             SHFT3(x3,x2,x1,R*x2+C*x0)
00045             SHFT2(f2,f1,(*f)(x1))
00046         }
00047     }
00048     if (f1 < f2) {
00049         *xmin=x1;
00050         return f1;
00051     } else {
00052         *xmin=x2;
00053         return f2;
00054     }
00055     #undef SHFT2
00056     #undef SHFT3
00057 }
00058 
00059 
00060 
00061 } // end namespace nr
00062 #endif
00063 

Generated on Thu Dec 23 13:52:25 2004 by doxygen 1.3.6