解\方法 | 二分法 | 不动点迭代 | 牛顿迭代 |
---|---|---|---|
近似解 | 1.3688 | 1.9332 | 1.3688 |
迭代次数 | 14 | 10000 | 3 |
matlab代码
clear all;clc
f=@(x)x^3+2*x^2+10*x-20;
a=0;
b=2;
if(f(a)*f(b)<0)
a0=a;
b0=b;
else
error('a,b处同号')
end
iter = 0;
eps=0.0001;
while((b0-a0)/2)>=eps
iter=iter+1;
c=(a0+b0)/2;
if f(c)==0
solution=c;
break
elseif f(c)*f(a0)<0
b0=c;
else
a0=c;
end
end
[c iter]
python代码
def f(x):
return x**3+2*x**2+10*x-20
a = 0
b = 2
if f(a)*f(b) < 0:
a0 = a
b0 = b
else:
print('a,b同号')
iter = 0
eps=0.0001
while((b0-a0)/2)>=eps:
iter=iter+1
c=(a0+b0)/2
if f(c)==0:
solution=c
break
elif f(c)*f(a0)<0:
b0=c
else:
a0=c
print(c,iter)
matlab代码
clear all;clc
iter = 0;
eps=0.0001;
x0=1.2;
N=10000
% phi=@(x)(-2*x^2-10*x+20)^(1/3);
% phi=@(x)((-x^3-10*x+20)*0.5)^(1/2);
phi=@(x)((-x^3-2*x^2+20)/10);
x1=phi(x0)
while abs(x0-x1)>=eps & iter<N
x0=x1
x1=phi(x0);
iter=iter+1;
end
if iter==N
warning('迭代次数达到允许上限')
end
format short g
[x1 iter]
def phi(x):
return (20-x**3-2*x**2)/10
#def phi(x):
# return ((-x**3-10*x+20)*0.5)**(0.5)
# phi=@(x)((-x^3-10*x+20)*0.5)^(1/2);
eps = 1e-4
N=10000
x0=1.2
iter=0
x1=phi(x0)
while abs(x0-x1)>=eps and iter<N:
iter+=1
x0=x1
x1=phi(x0)
if iter==N:
print('迭代次数达到允许上限')
break
print(x1,iter)
matlab代码
clear all;clc
iter = 0;
eps=0.0001;
x0=2;
df=@(x)3*x^2+4*x+10;
f=@(x)x^3+2*x^2+10*x-20;
while abs(x0-(x0-f(x0)/df(x0)))>=eps
x0=(x0-f(x0)/df(x0));
iter=iter+1;
end
[x0 iter]
python代码
def df(x):
return 3*x**2+4*x+10
def f(x):
return x**3+2*x**2+10*x-20
iter = 0
eps=0.0001
x0=2
while abs(x0-(x0-f(x0)/df(x0)))>=eps:
x0=(x0-f(x0)/df(x0))
iter=iter+1
print(x0,iter)