我需要绘制DE方程,但是我不知道该怎么做。
首先,解决问题。
#10527113
from sympy import *
import numpy as np
import matplotlib.pyplot as plt
# Solve the DE: 3y'' + 2y' +y = 0
x = symbols('x')
y = symbols('y', cls=Function)
diffeq1 = Eq(3*y(x).diff(x,x) + 2*y(x).diff(x) + y(x), 0)
ans1 = dsolve ( diffeq1, y(x) )
print ( ans1 )
然后是绘图部分。
#plotting
#Let x : [0, 2*pi], c1 = 1 and c2 = 0
b = []
a = np.linspace( 0, 2*np.pi )
for k in a:
b.append(ans1.subs(x, k))
plt.plot(a, b, label="curve")
我在代码中输入了正确的'ans1',但无法成功绘制。
答案 0 :(得分:0)
绘图时,您在注释中说c1 = 1和c2 = 0,但没有在DE解算ans1中进行设置。我在您的代码中添加了替换内容,并选择了绘图解决方案的评估值。
from sympy import *
import numpy as np
import matplotlib.pyplot as plt
# Solve the DE: 3y'' + 2y' +y = 0
from sympy.solvers.ode import classify_sysode
x = symbols('x')
y = symbols('y', cls=Function)
diffeq1 = Eq(3*y(x).diff(x,x) + 2*y(x).diff(x) + y(x), 0)
ans1 = dsolve ( diffeq1, y(x) )
print ( ans1 )
# Eq(y(x), (C1*sin(sqrt(2)*x/3) + C2*cos(sqrt(2)*x/3))/exp(x)**(1/3))
print (ans1)
#plotting
# Let x : [0, 2*pi], c1 = 1 and c2 = 0
c1 = symbols('C1')
c2 = symbols('C2')
ans1 = ans1.subs(c1, 1) # substitute for c1
ans1 = ans1.subs(c2, 0) # substitute for c2
b = []
a = np.linspace( 0, 2*np.pi )
for k in a:
sol = ans1.subs(x, k)
b.append(sol.rhs) # select the value for plotting
plt.plot(a, b, label="curve")
plt.show()