0.618法(golden ratio search)

 最优化方法课程里面的,照书上的方法编了一个程序。

 

#include < iostream >
#include
< cmath >
using   namespace  std;
const   double  delta = 0.00001 ;
// the function
double  func( double  x)
{
                   
return exp(x)+exp(-x);
}

int  main()
{
    
//the interval [a,b]
    double a=-1,b=1;
    
double s=a+0.382*(b-a);
    
double t=a+0.618*(b-a);
    
double f1=func(s);
    
double f2=func(t);
    
int k=0;
    
while(true){
        k
++;
        printf(
"f(a=%6.2lf, s=%6.2lf, t=%6.2lf, b=%6.2lf) = (%6.4lf, %6.4lf, %6.4lf, %6.4lf) ",a,s,t,b,func(a),func(s),func(t),func(b));
        
if(f1>f2){
            
if(b-s<=delta){
                printf(
"******************************************************* ");
                printf(
"after %d iterators ",k);
                printf(
"when x= %.2lf, f(x)= %.2lf ",t,func(t));
                
break;
            }

            
else{
                a
=s;s=t;
                f1
=func(t);
                t
=a+0.618*(b-a);
                f2
=func(t);
            }

        }

        
else{
            
if(t-a<=delta){
                printf(
"******************************************************* ");
                printf(
"after %d iterators ",k);
                printf(
"when x= %.2lf, f(x)= %.2lf ",s,func(s));
                
break;
            }

            
else{
                b
=t;t=s;
                f2
=func(s);
                s
=a+0.382*(b-a);
                f1
=func(s);
            }

        }

    }

    
return 0;
}

你可能感兴趣的:(search,iostream,优化)