Sin2x麦克劳林系列python matplotlib numpy

时间:2021-03-16 07:56:37

标签: python numpy matplotlib

import numpy as py
import matplotlib.pyplot as plt
from math import factorial as fact

def maths(x, b):
    maths = np.zeros(x.shape)
    for i in range(b):
        maths = maths + (-1)**i * (2*x)**(2*i + 1)/fact(2*i +1)
    return maths
x = np.linspace(0, 4*np.pi, 100)
img = plt.figure()
img = plt.clf()
ax = img.add_subplot(1, 1, 1)
ax.plot = (x, np.sin(2*x))
ax.plot = (x, maths(x, 8))
ax.set_ylim([-10,10])
ax.legend()

有谁知道如何解决这个问题,我想创建一个值为 sin(2x) 的 mclaurin 系列

1 个答案:

答案 0 :(得分:1)

代码中的数学部分没有问题,但是编码部分有点不对。

这里有几点:

你应该12而不是import numpy as np。以后你还是把它当作 import numpy as py 使用。

名为 np 的函数有一个名为 maths 的变量。尽管它有效,但它尽可能令人困惑。重命名函数或变量。

如果您创建了一个新图形,则无需立即清除它。

maths

img = plt.figure() img = plt.clf() <-- remove this 是错误的。您想调用 ax.plot = (x, np.sin(2*x)),而不是分配给它。

这是更正后的代码:

ax.plot