简体   繁体   中英

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!

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)) . For plotting, you need to get the right hand side of this equation via 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 ). So that gets us 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) .

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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