Fibonacci法

来源:互联网 发布:淘宝众筹回报是什么 编辑:程序博客网 时间:2024/05/03 00:19

 

#include<iostream>
#include
<stdio.h>
#include
<cmath>
using namespace std;
//the accuracy
const double delta=1e-4;
const int MAX=200;
double fib[MAX];
//the function
double func(double x)
{
    
return exp(x)+exp(-x);
}

void calcuFib()
{
    fib[
0]=fib[1]=1;
    
for(int i=2;i<MAX;i++)
        fib[i]
=fib[i-1]+fib[i-2];
}

int main()
{
    
//the interval [a,b]
    double a=-1,b=1;
    calcuFib();
    
int n=0;
    
for(;n<MAX;n++)
    
{
        
if(fib[n]>=(b-a)/delta) {
            
break;
        }

    }

    
double s=a+fib[n-2]*1.0/fib[n]*(b-a);
    
double t=a+fib[n-1]*1.0/fib[n]*(b-a);
    
double f1=func(s),f2=func(t);
    
for(int k=2;k<=n;)
    
{
        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){
                cout
<<t<<endl;break;
            }

            a
=s;s=t;f1=f2;
            k
++;
            t
=a+fib[n-k]/fib[n-k+1]*(b-a);
            f2
=func(t);
        }

        
else{
            
if(t-a<=delta){
                cout
<<s<<endl;break;
            }

            b
=t;t=s;f2=f1;
            k
++;
            s
=a+fib[n-k-1]/fib[n-k+1]*(b-a);
            f1
=func(s);
        }

    }

    printf(
"******************************************************* ");
    printf(
"after %d iterators the values reach  ",n-1);
    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));
    
return 0;
}

原创粉丝点击