solve an ode and plot it in python

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.py
import numpy as np

def odefunc(t, y):
    return np.array([y[1], -2*y[1] - 5*y[0] + np.sin(3*t)])
99 chars
5 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.py
from scipy.integrate import solve_ivp

# Define time interval
t_span = [0, 10]

# Define initial conditions
y0 = [0, 1]

# Solve ODE
sol = solve_ivp(odefunc, t_span, y0)
170 chars
11 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.py
import matplotlib.pyplot as plt

# Extract solution arrays
t = sol.t
y = sol.y[0]

# Plot solution
plt.plot(t, y)
plt.xlabel('Time')
plt.ylabel('y(t)')
plt.title('Solution of y\'\' + 2y\' + 5y = sin(3t)')
plt.show()
216 chars
13 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