使用Sympy绘制微分方程的解决方案
from sympy import *
import sympy as sp
from sympy.abc import *
import numpy as np
import matplotlib.pyplot as plt
x=sp.Function('x')
t=symbols('t')
w=int(input("enter the frequency in hz"))
eq= sp. Eq(x(t).diff(t,2)+w**2*x(t)-f*sp .cos(w*t),0)
c= sp. dsolve(eq,x(t),ics={x(0):0,x(t).diff(t).subs(t,0):sp .cos(w*t)})
d= lambdify(t,c,'numpy')
n= np. arange (0,10,1)
y=d(n)
输出错误:
名称'x'未定义!
如何纠正此错误?
from sympy import *
import sympy as sp
from sympy.abc import *
import numpy as np
import matplotlib.pyplot as plt
x=sp.Function('x')
t=symbols('t')
w=int(input("enter the frequency in hz"))
eq= sp. Eq(x(t).diff(t,2)+w**2*x(t)-f*sp .cos(w*t),0)
c= sp. dsolve(eq,x(t),ics={x(0):0,x(t).diff(t).subs(t,0):sp .cos(w*t)})
d= lambdify(t,c,'numpy')
n= np. arange (0,10,1)
y=d(n)
Output Error :
name 'x' is not defined!
How to rectify this error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,如果打印出
c
,则获得eq(x(t),(f*t/880 + cos(440*t)/440)*sin(440* t))
。要绘制,您需要通过c.rhs
获得此方程的右手侧。另请注意,(再次,打印)您在
c.rhs
中仍然具有符号f
,我们应该用您的数值替换(我将手动输入替换为<<代码> W = 440 )。这样就可以使我们c.rhs.subs(f,w)
。然后,lambdify正确执行,为我们提供了一个纯粹的数值值,而不是符号值,我们可以通过
plt.plot(n,y)
来绘制这些值。总而言之,
First up, if you print out your
c
, you getEq(x(t), (f*t/880 + cos(440*t)/440)*sin(440*t))
. For plotting, you need to get the right hand side of this equation viac.rhs
.Also note that (again, printing) you still have the symbolic
f
in yourc.rhs
, which we should replace with your numerical value (I replaced the manual input withw = 440
). So that gets usc.rhs.subs(f, w)
.Then lambdify executes correctly, giving us an array of purely numerical values, rather than symbolic ones, which we can plot via
plt.plot(n, y)
.All in all,