> 其他 >
求matlab编程 用二分法和牛顿迭代法求根号a
人气:401 ℃ 时间:2020-05-19 13:32:32
解答
对于求平方根,变成方程模式为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
推荐
猜你喜欢
© 2024 79432.Com All Rights Reserved.
电脑版|手机版