solve an ode in python

To solve ordinary differential equations (ODEs) in Python, we can use the solve_ivp function from the scipy.integrate module.

Assuming we have a first-order ODE in the form:

main.py
dy/dt = f(t, y)
16 chars
2 lines

where t is the independent variable and y is the dependent variable, we can define the function f in Python and pass it to solve_ivp.

Here's an example code snippet:

main.py
import numpy as np
from scipy.integrate import solve_ivp

# Define the function f(t, y)
def f(t, y):
    dydt = # define the right-hand side of the ODE here
    return dydt

# Define the initial condition
y0 = # initial value of y

# Define the time span for the solution
tspan = # list or tuple containing the start and end times

# Call solve_ivp to solve the ODE
sol = solve_ivp(f, tspan, y0)

# Extract the solution
t = sol.t
y = sol.y[0] # y is returned as an array with shape (n,); extract the first element to get a 1D array
532 chars
21 lines

In this code, we first define the function f that represents the right-hand side of our ODE. We then define the initial condition y0 and the time span tspan for the solution. Finally, we pass f, tspan, and y0 to solve_ivp and extract the solution t and y from the resulting Solution object.

Note that solve_ivp can also handle higher-order ODEs by treating them as systems of first-order ODEs.

gistlibby LogSnag