【MATLAB】一维搜索之抛物线法

clc;clear;

syms x a0a1 a2

f = 1/4*x^4-4/3*x^3+5/2*x^2-2*x;

xx =[1,0,3];

while(1)

    ff = subs(f,xx);  %分别求出f0,f1,f2的值

    if abs(ff(1)-ff(2))<1e-8 %调节精度&判断条件

        break;

    end

    b1 = (ff(2)-ff(1))/(xx(2)-xx(1));

    b2 = (ff(3)-ff(2))/(xx(3)-xx(2));

    a2 = (b2-b1)/(xx(3)-xx(1));

    x0 =-(b1-a2*(xx(2)+xx(1)))*(xx(3)-xx(1))/(2*b2-2*b1); %求出x_的值

    xx(4) = x0;

    ff(4) = subs(f,x0);

    minf = zeros(1,3);

    minum = zeros(1,3);

    minum(1) = find(ff == min(ff));

    minum(2) = find(ff ==min(ff(ff>ff(minum(1)))));

    minum(3) = find(ff ==min(ff(ff>ff(minum(2)))));

    xxx(1) = xx(minum(1)); %找出f值最小的x

    xxx(2) = xx(xx == max(xx(xx

    xxx(3) = xx(xx == min(xx(xx>xxx(1))));

    xxx(4) = NaN;

    xx = xxx;

end

fprintf('用抛物线法求得的近似解为%9.15f\n',double(xx(1)))

程序输出结果:

用抛物线法求得的近似解为1.999854390723428

你可能感兴趣的:(matlab)