二分法求函数零点
long double l=INT_MIN,r=INT_MAX,mid,eps=1e-6;
while(r-l>eps)
{
mid=(l+r)/2;
if(f(mid)<0) l=mid;
else r=mid;
}
cout<<l<<endl;
三分法求单谷函数最小值
long double l=INT_MIN,r=INT_MAX,lmid,rmid,eps=1e-6;
while(r-l>eps)
{
lmid=l+(r-l)/3;
rmid=r-(r-l)/3;
if(f(lmid)<f(rmid)) r=rmid;
else l=lmid;
}
cout<<f(l)<<endl;
求导二分法求单谷函数最小值
inline long double df(long double x)
{
long double dx=1e-6;
return (f(x+dx)-f(x-dx))/(dx*2);
}
signed main()
{
long double l=INT_MIN,r=INT_MAX,mid,eps=1e-6;
while(r-l>eps)
{
mid=(l+r)/2;
if(df(mid)<0) l=mid;
else r=mid;
}
cout<<f(l)<<endl;
return 0;
}
优化三分法求单谷函数最小值
long double l=INT_MIN,r=INT_MAX,lmid,rmid,eps=1e-6;
while(r-l>eps)
{
lmid=(l+r)/2-eps*0.01;
rmid=(l+r)/2+eps*0.01;
if(f(lmid)<f(rmid)) r=rmid;
else l=lmid;
}
cout<<f(l)<<endl;