函数:,初始点,精度
主程序:
clc
clear
f=@(x) (x-3)*sqrt(x);
fplot(f)
a=-100;
b=100;
[fx,x]=huangjin(f,[a b],100) % (a,b)为搜索区间
function [result,x]=huangjin(f,x0,n)
tol=0.1;%精度
x1=x0(1);
x2=x0(2);
i=1;
while i < n
%取中间值
a=x1+0.382*(x2-x1);
b=x1+0.618*(x2-x1);
fa=f(a);
fb=f(b);
% 判断fa fb大小,缩小区间
if fa < fb
x2=b;
else
x1=a;
end
if abs(x1-x2) < tol
result=f((x1+x2)/2);
x=(x1+x2)/2;
break;
end
i=i+1;
end
end
计算结果: