题目
二分法
# x^3+2x^2+10x-20
def func(x):
return x*x*x+2*x*x+10*x-20;
a=-1
b=2
fa=func(a)
fb=func(b)
eps=10e-4
iter=0
while a<=b:
iter+=1
x0=(a+b)/2
fx0=func(x0)
if abs(fx0)<eps:
print(x0,'是用二分法求解方程的根')
print('迭代次数为',iter)
break
if fa*fx0<0:
b=x0
fb=fx0
elif fb*fx0<0:
a=x0
fa=fx0
python截图:
不动点迭代法
def phi(x):
return 20/(x**2 + 2*x +10)
eps = 10e-4
N=5000
x0=1
iter=0
x1=phi(x0)
while abs(x1-x0)>eps and iter<N:
iter+=1
x0=x1
x1=phi(x0)
if iter==N:
print('迭代次数超出了上限')
print(x1,iter)
python截图
牛顿法
# x^3+2x^2+10x-20
def f(x):
return x**3+2*x*x+10*x-20
def df(x):
return 3*x*x+4*x+10
def phi(x):
return x-f(x)/df(x)
eps = 10e-4
N=5000
x0=1
iter=0
x1=phi(x0)
while abs(x1-x0)>eps and iter<N:
iter+=1
x0=x1
x1=phi(x0)
if iter==N:
print('迭代次数超出了上限')
break
print(x1,iter)
python截图
方法结果总结
方法 | 二分法 | 不动点法 | 牛顿法 |
---|---|---|---|
近似解 | 1.36883544921875 | 1.923189476944814 | 1.3688081886175318 |
迭代次数 | 14 | 5000 | 2 |