Jessie Cotton Jessie Cotton - 1 year ago 75
Python Question

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

Answer Source

Import these libraries (seaborn just makes the plots pretty).

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

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

I get a plot like this for a mass of 2 and a drag coefficient of 2. enter image description here