简体   繁体   English

将Sympy结果绘制为微分方程的特解

[英]Plotting Sympy Result to Particular Solution of Differential Equation

So far I have managed to find the particular solution to this equation for any given mass and drag coefficient. 到目前为止,我已经设法找到任何给定质量和阻力系数的这个方程的特定解。 I have not however found a way to plot the solution or even evaluate the solution for a specific point. 然而,我没有找到一种方法来绘制解决方案,甚至评估特定点的解决方案。 I really want to find a way to plot the solution. 我真的想找到一种方法来绘制解决方案。

from sympy import *

m = float(raw_input('Mass:\n> '))
g = 9.8
k = float(raw_input('Drag Coefficient:\n> '))
f = Function('f')
f1 = g * m
t = Symbol('t')
v = Function('v')
equation = dsolve(f1 - k * v(t) - m * Derivative(v(t)), 0)
C1 = Symbol('C1')
C1_ic = solve(equation.rhs.subs({t:0}),C1)[0]
equation = equation.subs({C1:C1_ic})

For completeness, you may also use Sympy's plot , which is probably more convenient if you want a "quick and dirty" plot. 为了完整起见,您还可以使用Sympy的plot ,如果您想要“快速而肮脏”的plot ,这可能更方便。

plot(equation.rhs,(t,0,10))

在此输入图像描述

Import these libraries (seaborn just makes the plots pretty). 导入这些库(seaborn只是使图很漂亮)。

from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np

Then tack this onto the end. 然后把它解决到最后。 This will plot time, t, against velocity, v(t). 这将绘制时间t与速度v(t)的关系曲线。

# make a numpy-ready function from the sympy results
func = lambdify(t, equation.rhs,'numpy')
xvals = np.arange(0,10,.1)
yvals = func(xvals)

# make figure
fig, ax = plt.subplots(1,1,subplot_kw=dict(aspect='equal'))     
ax.plot(xvals, yvals)
ax.set_xlabel('t')
ax.set_ylabel('v(t)')
plt.show()

I get a plot like this for a mass of 2 and a drag coefficient of 2. 我得到这样的情节,质量为2,阻力系数为2。 在此输入图像描述

If I've understood correctly, you want to represent the right hand side of your solution, here's one of the multiple ways to do it: 如果我理解正确,您希望代表解决方案的右侧,这是执行此操作的多种方法之一:

from sympy import *
import numpy as np
import matplotlib.pyplot as plt

m = float(raw_input('Mass:\n> '))
g = 9.8
k = float(raw_input('Drag Coefficient:\n> '))
f = Function('f')
f1 = g * m
t = Symbol('t')
v = Function('v')
equation = dsolve(f1 - k * v(t) - m * Derivative(v(t)), 0)
C1 = Symbol('C1')
C1_ic = solve(equation.rhs.subs({t: 0}), C1)[0]
equation = equation.subs({C1: C1_ic})

t1 = np.arange(0.0, 50.0, 0.1)
y1 = [equation.subs({t: tt}).rhs for tt in t1]

plt.figure(1)
plt.plot(t1, y1)
plt.show()

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

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