00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020 #include "stdafx.h"
00021 #include "gul_types.h"
00022
00023 namespace guma {
00024
00025 using gul::rtr;
00026
00027
00028
00029
00030
00031
00032
00033
00034 template< class T >
00035 bool GoldenSectionSearch( T ax, T bx, T cx, T (*func)( T, void * ), void *fdat,
00036 T tol, int max_iterations, T *xmin, T *fmin )
00037 {
00038 T x0,x1,x2,x3,f1,f2;
00039 int iteration;
00040
00041 x0 = ax;
00042 x3 = cx;
00043
00044 if( rtr<T>::fabs(cx-bx) > rtr<T>::fabs(bx-ax) )
00045 {
00046 x1 = bx;
00047 x2 = bx + rtr<T>::golden_c()*(cx-bx);
00048 }
00049 else
00050 {
00051 x2 = bx;
00052 x1 = bx - rtr<T>::golden_c()*(bx-ax);
00053 }
00054 f1 = func( x1, fdat );
00055 f2 = func( x2, fdat );
00056
00057 for( iteration = 0; iteration < max_iterations; iteration++ )
00058 {
00059 if( f2 < f1 )
00060 {
00061 x0 = x1;
00062 x1 = x2;
00063 x2 = rtr<T>::golden_r() * x2 + rtr<T>::golden_c() * x3;
00064 f1 = f2;
00065 f2 = func( x2, fdat );
00066 }
00067 else
00068 {
00069 x3 = x2;
00070 x2 = x1;
00071 x1 = rtr<T>::golden_r() * x2 + rtr<T>::golden_c() * x0;
00072 f2 = f1;
00073 f1 = func( x1, fdat );
00074 }
00075 if( rtr<T>::fabs(x3-x0) <= tol*(rtr<T>::fabs(x1)+rtr<T>::fabs(x2)) )
00076 break;
00077 }
00078 if( f1 < f2 )
00079 {
00080 *xmin = x1;
00081 *fmin = f1;
00082 }
00083 else
00084 {
00085 *xmin = x2;
00086 *fmin = f2;
00087 }
00088 if( iteration == max_iterations ) return false;
00089 return true;
00090 }
00091 template bool GoldenSectionSearch(
00092 float ax, float bx, float cx, float (*func)( float, void * ), void *,
00093 float tol, int max_iterations, float *xmin, float *fmin );
00094 template bool GoldenSectionSearch(
00095 double ax, double bx, double cx, double (*func)( double, void * ), void *,
00096 double tol, int max_iterations, double *xmin, double *fmin );
00097
00098 }
00099
00100
00101
00102