Search code examples
pythonplotsympyodedsolve

Sympy dsolve with plots


I am solving an ODE with Sympy. The equation is

ODE

To solve it, I used this little code, which returns this result.

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


x = symbols('x')
y = Function('y')


f = y(x)
print(f)

edo = Eq(f.diff()+3*x**2*f, 6*x**2)
print(edo)

edoSolve = dsolve(edo, f)
print(edoSolve)

C1*exp(-x**3) + 2

My question is, how can I plot the result with x being a range from 0 to 10?


Solution

  • Firstly it's problematic to combine these two lines:

    from sympy import *
    from numpy import *
    

    These two libraries define many functions with the same names and mixing those together will lead to problems. For clarity it is better to do something like:

    import sympy as sym
    import numpy as np
    

    You can only plot a sympy expression if you give numbers for all of the symbols apart from the one that you want to plot against (i.e. x in this example). That means that you need to have a concrete value for the integration constant C1. You can get that by giving an initial conditions (ics) argument to dsolve. Also since dsolve returns an equation you need to choose a side of the equation as the expression that you want to plot. Having done that the sym.plot function will do precisely what you ask for:

    In [10]: import sympy as sym
    
    In [11]: sol = sym.dsolve(edo, f, ics={f.subs(x, 0): 1})
    
    In [12]: sol
    Out[12]: 
                  3
                -x 
    y(x) = 2 - ℯ   
    
    In [13]: sym.plot(sol.rhs, (x, 0, 10))
    Out[13]: <sympy.plotting.plot.Plot at 0x7f346de1caf0>
    

    plot of the solution