我有一定的功能,例如sin(b * x),同时我得到衍生和反衍生表达式,但我需要在matplotlib中绘制这3个函数。我的问题是我无法将函数正确转换为numpy以便在matplotlib中绘图。我已经在lamby函数的sympy页面中跟踪了文档,但它不起作用。 http://docs.sympy.org/latest/modules/utilities/lambdify.html
我有这段代码:
from sympy import Symbol, diff, integrate, sin, cos, Function
from sympy.utilities.lambdify import lambdify, implemented_function
from sympy.abc import x
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons
def signal(b,x):
return sin(b*x)
def derivative(b,x):
yprime = diff(signal(b,x), x)
return yprime
def antiderivative(b,x):
anti = integrate(signal(b,x), x)
return anti
b = 5
evalfunc = lambdify((b,x), signal(b,x), modules=['numpy'])
evalderiv = lambdify((b,x), derivative(b,x), modules=['numpy'])
evalantideriv = lambdify((b,x), antiderivative(b,x), modules=['numpy'])
axis_color = 'lightgoldenrodyellow'
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
fig.subplots_adjust(left=0.25, bottom=0.25)
t = np.arange(-10, 10, 0.001)
[line] = ax.plot(t, evalfunc(b,t), linewidth=2, color='red')
[line2] = ax.plot(t, evalderiv(b,t), linewidth=2, color='blue')
[line3] = ax.plot(t, evalantideriv(b,t), linewidth=2, color='blue')
ax.set_xlim([-10, 10])
ax.set_ylim([-5, 5])
ax.grid()
plt.show()
在ax.plot中失败ValueError:序列太大;不能大于32
答案 0 :(得分:1)
您的代码不是一个很小的工作示例,但它只需要很少的更改即可。
您需要在推导之前将b
声明为真实符号。
在数值评估之前将其设置为b=5
。
请参阅:
from sympy import Symbol, diff, integrate, sin, cos, Function
from sympy.utilities.lambdify import lambdify, implemented_function
from sympy.abc import x
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons
def signal(b,x):
return sin(b*x)
def derivative(b,x):
yprime = diff(signal(b,x), x)
return yprime
def antiderivative(b,x):
anti = integrate(signal(b,x), x)
return anti
b = Symbol('b', real=True)
evalfunc = lambdify((b,x), signal(b,x), modules=['numpy'])
evalderiv = lambdify((b,x), derivative(b,x), modules=['numpy'])
evalantideriv = lambdify((b,x), antiderivative(b,x), modules=['numpy'])
axis_color = 'lightgoldenrodyellow'
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
fig.subplots_adjust(left=0.25, bottom=0.25)
t = np.arange(-10, 10, 0.001)
b = 5
[line] = ax.plot(t, evalfunc(b,t), linewidth=2, color='red')
[line2] = ax.plot(t, evalderiv(b,t), linewidth=2, color='blue')
[line3] = ax.plot(t, evalantideriv(b,t), linewidth=2, color='blue')
ax.set_xlim([-10, 10])
ax.set_ylim([-5, 5])
ax.grid()
plt.show()