求matlab编程 用二分法和牛顿迭代法求根号a
1个回答

对于求平方根,变成方程模式为f(x)=x^2-a,即求此方程的实根;

下面编写了两个function函数,可以直接调用.

二分法:

function x=sqrt_bisect(a)

f=@(x)x^2-a;

if a0

xb=x;

elseif f(xa)*f(x)>0

xa=x;

else

break

end

end

end

x;

牛顿迭代法:

function x=sqrt_newton(a)

f=@(x)x^2-a;

df=diff(sym('x^2-a'));

if a1e-6

x0=x1;

x1=x0-f(x0)/subs(df,x0);

end

end

x=x1;

调用格式为:

sqrt_bisect(3)

ans =

1.7321

或者

sqrt_newton(2)

ans =

1.4142