0

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?

J Pablo A
  • 3
  • 1

2 Answers2

1

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

JohanC
  • 71,591
  • 8
  • 33
  • 66
Oscar Benjamin
  • 12,649
  • 1
  • 12
  • 14
1

If you want to show solutions for multiple values for C1 together, you could append plots:

from sympy import symbols, Function, Eq, dsolve, plot

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

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

edoSolve = dsolve(edo, f)

plot1 = plot(show=False)
for c1 in range(-5, 6):
    plotc1 = plot(edoSolve.subs('C1', c1).rhs, (x, 0, 10), show=False)
    plot1.append(plotc1[0])
plot1.show()

sympy plotting multiple solutions together

JohanC
  • 71,591
  • 8
  • 33
  • 66