绘制/转换来自sympy的表达式:带有matplotlib的Taylor系列

时间:2013-11-08 15:25:08

标签: python numpy matplotlib plot sympy

我试图绘制函数sin(x)/ x和它的泰勒近似。 我使用python 3和pyzo - 第一个绘图可以工作,但是我在将来自sympy模块的系列转换为可以工作的numpy表达式时遇到了问题。

import numpy as np
import matplotlib.pyplot as plt
import sympy as sp
from sympy.abc import x

x = np.linspace(-10, 10, 100)
y = np.sin(x)/x #first function
plt.plot(x, y, 'k') #this is working fine

### this is a code that removes the "0(x**something)" part of 
the series at the end 

我在http://pastebin.com/ZNQakWP7

找到了它
def series(expr, x, x0, n, removeO=False):
"""
sympy bugs avoided
"""
# expr_series = expr.series(x, x0, n)
# return expr_series.removeO() if removeO else expr_series
expansion = list()
for t in expr.lseries(x, x0):
    p = t.as_coeff_exponent(x)[1]
    if p < n:
        expansion.append(t)
    else:
        break
if not removeO:
    expansion.append(sp.O(x**n))
return sp.Add(*expansion)
### my code continued ####

y_t=series(sp.sin(x)/x,x,0,6,removeO=True)

如果我现在看y_t,我会得到这个近似值

out: x**4/120 - x**2/6 + 1

现在我尝试将其转换为numpy,以便像第一个函数一样绘制它。

f_t = lambdify(x, y_t,modules=['numpy'])
x = np.linspace(-10, 10, 100) #i do this because x has
#been a symbolic variable before

plt.plot(x, y_t, 'b') #this is where the problem occurs

我得到第一个情节也是第二条错误信息:

 File "<console>", line 1, in <module>
  File "F:\pyzo2013_0_2_2\lib\site-packages\matplotlib\pyplot.py", line 2832, in plot
    ret = ax.plot(*args, **kwargs)
  File "F:\pyzo2013_0_2_2\lib\site-packages\matplotlib\axes.py", line 3998, in plot
    for line in self._get_lines(*args, **kwargs):

我如何实现我的想法来绘制来自同情的东西? 我的另一个想法是将系列从系列转换为字符串然后以某种方式解析为一个numpy表达式。我会感谢你们的任何帮助!

1 个答案:

答案 0 :(得分:4)

我认为你的问题是:

plt.plot(x, y_t, 'b') #this is where the problem occurs

应该是这样的:

plt.plot(x, f_t(x), 'b')

f_t是lambdified系列,因此它是一个可调用函数,用于计算其参数。

我在以下示例中使用了lambdify,它适用于我:

from sympy.abc import x
from sympy import sin, series
from sympy.utilities.lambdify import lambdify

import numpy as np
import matplotlib.pyplot as plt


func = sin(x)/x
taylor = series(func, n=6).removeO()

evalfunc = lambdify(x, func, modules=['numpy'])
evaltaylor = lambdify(x, taylor, modules=['numpy'])

t = np.linspace(-5.5, 5.5, 100)
plt.plot(t, evalfunc(t), 'b', label='sin(x)/x')
plt.plot(t, evaltaylor(t), 'r', label='Taylor')
plt.legend(loc='best')
plt.show()

这是剧本生成的情节。

enter image description here