牛頓下山法求解非線性方程
阿新 • • 發佈:2021-01-09
技術標籤:非線性方程組
from matplotlib import pyplot as plt
import numpy as np
def fun(x):
return x**3-2*x-5
def dfun(x):
return 3*x*x-2
def newton(fun,dfun,a,b,eps):
err = 1
x = b
k = 0
lada = 1
x_r = []
while err > eps:
x_r.append(x)
x = x - lada * fun( x)/dfun(x)
err = fun(x)
k = k + 1
lada = lada * 0.99
print('牛頓下山法的迭代次數為{:d}次'.format(k))
print('x的迭代過程:')
for i in x_r:
print('{:.7f}'.format(i), end=' ')
print(' ')
return x
x = newton(fun, dfun, 0, 10, 0.0000001)
print('牛頓下山迭代法的求解結果為{:.7}'.format(x))
x1 = np.linspace(-10, 10, 1000)
y1 = fun(x1)
plt.plot(x1, y1)
plt.show()