牛顿单点线割迭代法求解非线性方程

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 = []
    x_r.append(x)
    x = x - fun(x) / dfun(x)
    k = k + 1
    while err > eps:
        x_r.append(x)
        x = x - fun(x)*(x-x_r[0])/(fun(x)-fun(x_r[0]))
        err = fun(x)
        k = k + 1
    print('牛顿单点线割法的迭代次数为{:d}次'.format(k))
    print('x的迭代过程:')
    num = 0
    for i in x_r:
        print('{:.7f}'.format(i), end='  ')
        num = num+1
        if num%5 == 0:
            print(' ')
    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()

牛顿单点线割迭代法求解非线性方程_第1张图片
在这里插入图片描述

你可能感兴趣的:(非线性方程的求解)