一维搜索算法----斐波那契法

标签:
杂谈 |
分类: Math |
测试结果:
http://s8/middle/60f8483a073cede2366f7&690
程序代码:
#include <iostream>
#include <math.h>
////visualsan@yahoo.cn 2010.5.8
typedef double(*Func)(double);
int Fn( int n )
{
if ( n == 0 || n ==1 )
{
return
1;
}
else
return Fn(
n-1 ) + Fn( n - 2 ) ;
}
double Fibonacci( double start, double end, Func f, double eps=1e-3)
{
double F0, F1, F2 ;
int n ;
F0 = 1;
F1 = 1;
F2 = F1 + F0;
n = 2;
while ( F2 <= (end - start )/eps
)
{
n++ ;
F2 = Fn( n ) ;
}
F1 = Fn( n -1 ) ;
double t1, t2, f1, f2, a, b;
a = start ;
b = end ;
if ( a > b )//
保证a<b
{
double temp = a;
a = b;
b = temp;
}
t1 = b - ( b - a ) * F1 / F2 ;
t2 = a + b - t1 ;
f1 = f( t1 ) ;
f2 = f( t2 ) ;
while ( t2 -
t1 >= eps
)
{
if ( f2 < f1 )
{
a = t1 ;
t1 = b - ( b - a ) * F1 / F2 ;
t2 = a + b - t1 ;
f1 = f( t1 ) ;
f2 = f( t2 ) ;
}
else
{
b = t2 ;
t1 = b - ( b - a ) * F1 / F2 ;
t2 = a + b - t1 ;
f1 = f( t1 ) ;
f2 = f( t2 ) ;
}
}
return ( t1 + t2 ) / 2.0 ;
}
////////测试函数
double Test1( double x) { return (x-1)*(x-1); }
double Test2( double x) { return exp( sin(x) ); }
/////////////////////驱动函数
void main()
{
using namespace std;
double y;
cout<<"----一维搜索法---斐波那契法测试---\n"
"------visualsan@yahoo.cn----------\n"
"-------------------2010.5.8-NUAA--\n";
cout<<"--sin(x)--x=[0,2pi]\n";
y = Fibonacci( 0.0, 6.28, sin );
cout<< " y="
<< y <<
"\n\n";
cout<<"--(x-1)*(x-1)--x=[-10,10]\n";
y = Fibonacci( -10.0, 10.0, Test1);
cout<< " y="
<< y <<
"\n\n";
cout<<"--exp( sin(x)
)--x=[-2,2]\n";
y = Fibonacci( -10.0, 10.0, Test2 );
cout<< " y="
<< y <<
"\n\n";
}
http://s8/middle/60f8483a073cede2366f7&690
程序代码:
#include <iostream>
#include <math.h>
////visualsan@yahoo.cn 2010.5.8
typedef double(*Func)(double);
int Fn( int n )
{
}
double Fibonacci( double start, double end, Func f, double eps=1e-3)
////////测试函数
double Test1( double x) { return (x-1)*(x-1); }
double Test2( double x) { return exp( sin(x) ); }
/////////////////////驱动函数
void main()
{
}
前一篇:一维搜索法---黄金分割法
后一篇:用遗传算法解几道题目