matlab二分法求方程的根

来源:学生作业帮助网 编辑:作业帮 时间:2024/11/06 03:47:25

matlab二分法求方程的根
matlab二分法求方程的根

matlab二分法求方程的根
举个简单例子:
问题1:求f(x)=1-x-sinx=0在【0,1】的根 误差不超过0.5*10^(-4)
clc;clear
a=0;b=1;
fa=1-a-sin(a);
fb=1-b-sin(b);
c=(a+b)/2;
fc=1-c-sin(c);
if fa*fb>0,break,end
while abs(fc)>0.5*10^(-4)
c=(a+b)/2;
fc=1-c-sin(c);
if fb*fc>0
b=c;
fb=fc;
else
a=c;
fa=fc;
end
end
format long
fx=fc,x=c
结果:
fx =
-2.414986223420179e-005
x =
0.510986328125000
问题2:用二分法求方程x^3-3*x-1=0的根
先建立二分法的fun.m文件,代码如下:
function fun(a,b,e)
%f是自定义的函数
%a为隔根区间左端点,b为隔根区间右端点,e为绝对误差限
if nargin==2
e=1.0e-6;
elseif nargin=b
input('隔根区间输入错误!');
return;
end
a1=a;
b1=b;
c1=(a1+b1)/2;
n=0; %迭代计数器,初值为0
while (b-a)/(2^(n)) >= 1/2*e
c1
if f(c1)==0
c1
elseif f(a1)*f(c1)>0
a1=c1;
c1=(a1+b1)/2;
n=n+1;
elseif f(b1)*f(c1)>0
b1=c1;
c1=(a1+b1)/2;
n=n+1;
end
end
n
再建立所要求函数的f.m文件:
function y=f(x)
y=x^3-3*x-1;
运行:fun(-100,100,10^(-4))
-100 100 为根所在该区间,10^(-4)表示精度要求.
结果:c1 =
0
c1 =
50
c1 =
25
c1 =
25/2
c1 =
25/4
c1 =
25/8
c1 =
25/16
c1 =
75/32
c1 =
125/64
c1 =
225/128
c1 =
475/256
c1 =
975/512
c1 =
1925/1024
c1 =
988/529
c1 =
2494/1331
c1 =
640/341
c1 =
1189/633
c1 =
171/91
c1 =
1357/722
c1 =
109/58
c1 =
1013/539
c1 =
701/373
n =
22
最后结果为 701/373