Here's an example of how to solve an ordinary differential equation (ODE) using the scipy.integrate
module in Python, and then plot the solution using matplotlib
. Specifically, we'll solve the following ODE:
y''(t) + 2y'(t) + 5y(t) = sin(3t)
subject to the initial conditions:
y(0) = 0
y'(0) = 1
First, we define the right-hand side of our ODE as a Python function:
main.py99 chars5 lines
Note that odefunc
takes two arguments: the independent variable t
and the dependent variable y
(which is a two-element array representing y(t)
and y'(t)
).
Next, we use the scipy.integrate.solve_ivp
function to solve the ODE over a desired time interval:
main.py170 chars11 lines
Here, t_span
is the pair of start and end times for the simulation, and y0
is a list of the initial conditions. solve_ivp
returns a scipy.integrate.OdeResult
object containing the time and solution arrays.
Finally, we can use matplotlib
to plot the solution:
main.py216 chars13 lines
This should produce a plot of the solution y(t)
as a function of time.
Note that this is just a simple example, and more complex ODEs may require different solution methods or numerical techniques. Also, it's important to always check the solution for accuracy and convergence.
gistlibby LogSnag