目录
Fibonacci数列又称黄金分割数列、因数学家列昂纳多·斐波那契(Leonardoda Fibonacci)以兔子繁殖为例子而引入,故又称为“兔子数列”,Fibonacci迭代法可以求解函数零点、函数极值等,本文用c++语言实现Fibonacci迭代法求解函数极值。
Fibonacci数列:
迭代公式:
算法步骤:
step1.给定初始搜索区间和允许误差,辨别系数,求解迭代次数n,使
step2.计算初始值
step3.开始循环k=k+1,转step4,若k>=n-2则退出循环,转step7.
step4 判断,是转step5,否转step6;
step5.令
step6.令
step7.令
,
判断,是,极小点所在的区间为;否,极小点所在的区间为
极值点为:
例题
求解函数在区间[-1,3]上的极小点,要求求解的区间不大于原始区间长度的0.0008倍。
程序求解结果如图:
C++代码:
#include <iostream>
#include <vector>
#include <iomanip>
using namespace std;
double fx(double x)
{
double fx;
fx = pow(x, 2) - x + 2;
return fx;
}
int main()
{
double epsilon = 0.08, f_min;
vector<double>fn(2);
fn[0] = 1; fn[1] = 1;
int i;
double a_fib = -1.0, b_fib = 3.0, f_lambda = 0, f_mu = 0;
for (i = 2; fn[i - 1] < 1.0 / epsilon; i++)
{
fn.push_back(fn[i - 2] + fn[i - 1]);
}
int n_fib = i - 1;
cout <<"n取值: "<< n_fib <<endl << endl;
double lambda = a_fib + (fn[n_fib - 2] / fn[n_fib])*(b_fib - a_fib), mu = a_fib + (fn[n_fib -1] / fn[n_fib])*(b_fib - a_fib);
f_lambda = fx(lambda);
f_mu = fx(mu);
cout << "区间迭代: " << endl;
for (int i = 0; i < n_fib-2; i++)
{
if ( f_lambda<f_mu)
{
a_fib = a_fib, b_fib = mu, mu = lambda, f_mu = f_lambda;
lambda = a_fib + (fn[n_fib - i - 3] / fn[n_fib-1 - i])*(b_fib - a_fib);
f_lambda = fx(lambda);
}
else
{
a_fib = lambda, b_fib = b_fib, lambda = mu, f_lambda = f_mu;
mu = a_fib + (fn[n_fib - i - 2] / fn[n_fib -1-i])*(b_fib - a_fib);
f_mu = fx(mu);
}
cout << fixed << setw(12) << setprecision(5) << a_fib << fixed << setw(12) << setprecision(5) << lambda << fixed << setw(12) << setprecision(5) << mu << fixed << setw(12) << setprecision(5) << b_fib << endl;
}
mu = lambda + 0.001;
f_mu = fx(mu);
if (f_lambda < f_mu)
{
a_fib = a_fib, b_fib = mu,f_min=0.5*(fx(a_fib)+fx(b_fib));
}
else
{
a_fib = lambda, b_fib = b_fib, f_min = 0.5*(fx(a_fib) + fx(b_fib));
}
cout << endl << "极小值区间:" << fixed << setw(9) << setprecision(5) << a_fib << fixed << setw(12) << setprecision(5) << b_fib << endl;
cout << "极小值: " << fixed << setw(12) << setprecision(5) << f_min << endl;
}