第四章 无约束最优化问题
一维搜索
前提:满足凸规划条件
搜索区间上有唯一的极小点
思想:序贯试验方法,即通过比较区间端点值,利用函数的单调性,缩小搜索区间长度直至小于规定的精度。
具体方法:fibonacci方法、黄金分割法
//
// Created by xylee on 2020/4/30.
//
#include <cstdio>
#include <iostream>
using namespace std;
double f[100] = {0};
double function(double x)
{
double result = x*x-6*x-2;
return result;
}
double fibonacci(double a,double b,double e)
{
double x1,x2,f1,f2;
int i = 0;
while(f[i]<((b-a)/e))
{
i++;
}
x2 = a + f[i-1]/f[i]*(b-a);
x1 = a+b - x2;
f2 = function(x2);
f1 = function(x1);
while((x2 - x1)>e)
{
if(f2 > f1){
b = x2;
x2 = x1;
x1 =a+b-x2;
f2 = f1;
f1 = function(x1);
}
else{
a =x1;
x1 = x2;
x2 = a+b-x1;
f1 = f2;
f2 = function(x2);
}
cout <<"x1="<<x1<<" x2="<<x2<<" l="<<(x2-x1)<<endl;
}
return (x1+x2)/2;
}
double golden_section(double a,double b,double e)
{
double x1,x2,f1,f2;
int i = 0;
while(f[i]<((b-a)/e))
{
i++;
}
x2 = a + 0.618*(b-a);
x1 = a + 0.382*(b-a);
f2 = function(x2);
f1 = function(x1);
while((x2 - x1)>e)
{
if(f2 > f1){
b = x2;
x2 = x1;
x1 =a+b-x2;
f2 = f1;
f1 = function(x1);
}
else{
a =x1;
x1 = x2;
x2 = a+b-x1;
f1 = f2;
f2 = function(x2);
}
cout <<"x1="<<x1<<" x2="<<x2<<" l="<<(x2-x1)<<endl;
}
return (x1+x2)/2;
}
int main() {
f[0] = f[1] =1;
for (int i = 2; i < 100; ++i) {
f[i] = f[i-1]+f[i-2];
}
double a,b,e;
cin >>a>>b>>e;
// double result = fibonacci(a,b,e);
double result = golden_section(a,b,e);
printf("x= %.4lf",result);
return 0;
}