newton - JasonWayne/personal-wiki GitHub Wiki

牛顿方法

python 示例

import time
import matplotlib.pyplot as plt


def get_x(x0, f, df, epsilon):
    xn = float(x0)
    history = [xn, f(xn)](/JasonWayne/personal-wiki/wiki/xn,-f(xn))
    while(abs(f(xn)) > epsilon):
        # time.sleep(0.5)
        xn = xn - f(xn) / df(xn)
        history.append([xn, f(xn)])
    return history

if __name__ == "__main__":
    def f(x):
        return x ** 2

    def df(x):
        return 2 * x

    history = get_x(10, f, df, 0.01)

    x = [float(x) / 100 for x in range(-1500, 1500)]
    y = [f(i) for i in x]

    plt.plot(x, y, 'r-', linewidth=3, label='original curve')

    x = [e[0] for e in history]
    y = [e[1] for e in history]
    plt.plot(x, y, 'b*', markersize=10, alpha=0.5)
    plt.show()


参考资料