本文讲解如何使用matplotlib动态演示牛顿迭代法。牛顿迭代法是一种用于寻找方程的根的迭代方法。它的思想是从一个初始点开始,通过不断迭代来逐步接近方程的根。每次迭代通过求导数值来计算出函数的局部切线,并将切线与x轴交点作为下一次迭代的初始点。
在本文中,我们使用matplotlib模块来可视化牛顿迭代法的过程。为了使演示更加生动和易于理解,我们将使用三次方程$x^3-2x^2-5=0$作为示例。
我们先来看一下完整代码:
import numpy as np
import matplotlib.pyplot as plt
# 目标方程
def f(x):
return x**3 - 2*x**2 - 5
# 目标方程的导数
def df(x):
return 3*x**2 - 4*x
# 牛顿迭代法
def newton(x0, tol=1e-6):
x = x0
while True:
x_next = x - f(x)/df(x)
if abs(x_next - x) < tol:
break
x = x_next
return x
# 动态演示牛顿迭代法
x_values = np.linspace(-2, 3, 200)
fig, ax = plt.subplots(figsize=(8,6))
plt.plot(x_values, f(x_values), label='f(x)')
plt.axhline(y=0, color='black', linestyle='--')
plt.legend()
# 定义初始点
x0 = 1.5
# 开始迭代
for i in range(10):
x = newton(x0)
ax.plot(x,