0

i have a polynomial f(x)= x^3-a and i need its matlab function with parameters

function [x,err]=cubic1(a,xinit,eps) where xinit: Initial approximation eps: iterations are performed until approximate error is less than this number x: Root approximations of the function, and it is an array. relerr: Approximate errors corresponding to the iterations and it is an array.

do you have any idea ?

4

2 回答 2

0
function [x,err] = cubic1(f,df_dx,x0,eps)
   err = Inf;
   x = x0;
   while abs(err) > eps
      x_old = x;
      x = x_old - f(x_old)./df_dx(x_old);
      err = x - x_old;
   end

要调用cubic1函数,

a = 1; % you can change a
f = @(x)(x.^3-a);
df_dx = @(x)(3*x.^2);
x0 = 1;
eps = 1e-7;
[x,err] = cubic1(@f,@df_dx,x0,eps);
于 2013-11-25T00:33:40.767 回答
0

关于lennon310解决方案中函数重命名的补充

文件cubic1.m

function [x,err] = cubic1(a,xinit,eps)
    f = @(x)(x.^3-a);
    df_dx = @(x)(3*x.^2);
    [x,err] = newton_root(@f,@df_dx,xinit,eps);
end

function [x,err] = newton_root(f,df_dx,x0,eps)
    err = Inf;
    x = x0;
    while abs(err) > eps
        x_old = x;
        x = x_old - f(x_old)./df_dx(x_old);
        err = x - x_old;
    end
end

对于 f(x)=x^2-a/x,使用牛顿法可以更快地收敛,

文件cubic2.m

function [x,err] = cubic2(a,xinit,eps)
    err = Inf;
    x = xinit;
    while abs(err) > eps
        x3=x.^3;
        x_new = x*(x3+3*a)/(3*x3+a);
        err = x_new - x;
        x=x_new
    end
end
于 2013-12-13T15:23:31.257 回答