python - 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) 的麦克劳林系列
解决方案
您的代码中的数学部分没有任何问题,但是编码部分有点偏离。
这里有几点:
你应该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))
推荐阅读
- python - matplotlib 标题中内联字符串中符号上方的单词
- python-3.x - 显示从linux入口点执行的python脚本的控制台?
- java - 如何在 Java 中使用 xdg-desktop-portal 文件门户
- sql-server - 未激活电子邮件的作业失败的 SQL Server 代理
- c - 为什么我用两种方法检查一个数字是否是阿姆斯壮数字会得到不同的结果?
- docker - Filebeat 不尝试连接到 backoff/Logstash 并且没有日志发送到 Logstash
- python-3.x - 尝试在序列化程序“CommentSerializer”上获取字段“文本”的值时出现 AttributeError
- javascript - CSS 和 Javascript 中的通知动画
- php - Symfony Mercure 错误 Symfony\Component\Mercure\PublisherInterface
- .net - 将 .NET 5.0 目标添加到我的 NuGet 包