1.题目
2.代码
import sympy as sy
def fx_Value(x0, fx):
result = fx.subs(x, x0)
return result
def Newton(x0, fx, e=1e-6):
# fx是原函数
# x0是初值
# e是误差
times = 0
while True:
x_buff = x0
x0 = x0 - fx_Value(x0, fx) / fx_Value(x0, sy.diff(fx))
times += 1
if abs(x0 - x_buff) < e:
break
elif times > 10000:
break
print("迭代次数过大,仍不收敛")
return x0
x = sy.symbols("x")
fx = (x**3)/3 - x # 公式
print(fx)
x0 = -0.5
e = 1e-3
x_r = Newton(x0, fx ,e)
print(x_r)
(2)
<1>
x = sy.symbols("x")
fx = (x**3)/3 - x # 公式
e = 1e-3
for i in range(100000):
x0 = i/100000
print(x0)
x_pos = Newton(x0, fx, e)
x_neg = Newton(-x0, fx, e)
if abs(x_pos) > 1e-6 and abs(x_neg) > 1e-6:
break
print(x0)
<2>
x = sy.symbols("x")
fx = (x**3)/3 - x # 公式
e = 1e-3
x0 = [-2.6,-0.85,0.1,0.9,2.5]
for i in range(5):
x_r, times = Newton(x0[i], fx, e)
if abs(x_r) > 5:
print(x0[i], "的迭代结果未收敛")
else:
print(x0[i],"的迭代结果为",x_r,",迭代次数为",times)
3.结果