分别用牛顿法和割线法求解方程 x^3-6x^2+9x-2=0在区间[3,4]上的近似根.要求满足精度|x*-xk|

1个回答

  • %

    clc; clear all;

    global fnq dfnq

    fnq = @(x) x^3 - 6*x^2 + 9*x - 2;

    dfnq = @(x) 3*x^2 - 12*x + 9;

    tol = (1/2)*10^-4;x0 = 3.5;gmax = 1e3;x01 = 3;x02 = 4;[k,xk,yk,piancha]=newtonqx(x0,tol,gmax);

    fprintf('n牛顿法:%.5fn',xk);

    [k,xk,yk,piancha]=gexian(x01,x02,tol,gmax);

    fprintf('n割线法:%.5fn',xk);% 牛顿法

    function [k,xk,yk,piancha]=newtonqx(x0,tol,gmax)

    global fnq dfnqx(1)=x0;for i=1:gmax

    x(i+1)=x(i)-fnq(x(i))/(dfnq(x(i)+eps));

    piancha=abs(x(i+1)-x(i));i=i+1;

    xk=x(i);yk=fnq(x(i));

    [(i-1) xk yk piancha];

    if(pianchagmaxdisp('超过最大迭代次数')k=i-1;xk=x(i);yk=fnq(x(i));

    [i-1 xk yk piancha];return;end% 割线法function [k,xk,yk,piancha]=gexian(x01,x02,tol,gmax)

    global fnq dfnq

    x(1)=x01;x(2)=x02;

    for i=2:gmax

    u(i)=fnq(x(i))*(x(i)-x(i-1));

    v(i)=fnq(x(i))-fnq(x(i-1));

    x(i+1)=x(i)-u(i)/(v(i));

    piancha=abs(x(i+1)-x(i));i=i+1;xk=x(i);yk=fnq(x(i));

    if(piancha