首页 > 解决方案 > Sin2x mclaurin 系列 python matplotlib numpy

问题描述

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) 的麦克劳林系列

标签: pythonnumpymatplotlib

解决方案


您的代码中的数学部分没有任何问题,但是编码部分有点偏离。

这里有几点:

你应该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,而不是分配给它。

这是更正后的代码:

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

def mclaurin(x, order):
    maths = np.zeros(x.shape)
    for i in range(order):
        maths += (-1)**i * (2*x)**(2*i + 1)/fact(2*i +1)
    return maths

x = np.linspace(0, 2*np.pi, 1000)

fig, ax = plt.subplots()
ax.plot(x, np.sin(2 * x))
ax.plot(x, mclaurin(x, 8))
ax.set(ylim=(-2, 2))

推荐阅读