简体   繁体   English

使用 SYMPY 绘制微分方程的解

[英]Plotting a Solution of differential equation Using 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)

Output Error :输出错误:

name 'x' is not defined!名称“x”未定义!

How to rectify this error?如何纠正这个错误?

First up, if you print out your c , you get Eq(x(t), (f*t/880 + cos(440*t)/440)*sin(440*t)) .首先,如果你打印出你的c ,你会得到Eq(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 via c.rhs .对于绘图,您需要通过c.rhs获得该等式的右侧。

Also note that (again, printing) you still have the symbolic f in your c.rhs , which we should replace with your numerical value (I replaced the manual input with w = 440 ).另请注意(再次打印)您的c.rhs中仍然有符号f ,我们应该用您的数值替换它(我用w = 440替换了手动输入)。 So that gets us c.rhs.subs(f, w) .这样我们就得到了c.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) .然后 lambdify 正确执行,给我们一个纯数值数组,而不是符号数组,我们可以通过plt.plot(n, y)绘制。

All in all,总而言之,

[nav] In [29]: 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=440
          ...: 
          ...: 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.rhs.subs(f, w),modules='numpy')
          ...: n= np. arange (0,10,1)
          ...: 
          ...: 
          ...: y=d(n)
          ...: plt.plot(n, y)
          ...: plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM