用C++实现黄金分割法的程序

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
double f(double x);
double GoldenSection( double a, double x1, double x2, double b);
int main()
{
SYSTEMTIME sys1,sys2;
GetLocalTime(&sys1);//获得当前系统时间
double a=0,b=2;//初始边界,可以自己修改
{
double y1 = f(x1), y2 = f(x2);
if( fabs(b -a) < 0.01)//精度0.01,可以自己修改精度
return (y1 < y2) ? x1 : x2;
if( y1 < y2 )
return GoldenSection( a, a+0.312*(x2 - a), a+0.618*(x2 - a), x2);
}
cout<<"用时"<<(sys2.wMilliseconds)-(sys1.wMilliseconds)<<"毫秒!"<<endl;//输出用去的时间
return 0;
}
double f(double x)//函数表达式
{
return x*x-3*x-4;//这里是需要求解的函数,可以自己修改
}
double GoldenSection( double a, double x1, double x2, double b)//运用递归求解
if( y1 > y2 )
return GoldenSecΒιβλιοθήκη Baiduion( x1, x1 + 0.312*(b - x1), x1 + 0.618*(b - x1),b);
if( y1 == y2 )//特殊情况,一般不会发生,所以放后面
return GoldenSection( x1,x1+0.312*(x2-x1), x1+0.618*(x2-x1), x2);
double x1 = 0.312 * (b-a), x2=0.618 * (b-a);
double x = GoldenSection(a,x1,x2,b);
double y = f(x);
cout<<"解为:"<<x<<",最小值是:"<<y<<endl;//输出解和函数值
GetLocalTime(&sys2);
说明:该程序是实现使用黄金分割法求解函数的极值点,本程序采用的方法是递归
程序中默认所求的函数是 ,边界是[0,2],精度是0.01,这些都可以自行在程序里修改
#include<iostream>
#include<cmath>
#include<fstream>
#include<windows.h>
using namespace std;
相关文档
最新文档