How to Solve a System of ODEs in Python?

Estimated read time 2 min read

To solve a system of ODEs (ordinary differential equations) in Python, you can use the scipy.integrate module. Here’s an example of how to solve a system of ODEs in Python:

import numpy as np
from scipy.integrate import odeint

# Define the system of ODEs
def system(y, t):
    x, y = y
    dxdt = x * (3 - x - 2*y)
    dydt = y * (2 - x - y)
    return [dxdt, dydt]

# Define the initial conditions
y0 = [1, 1]

# Define the time points at which to solve the ODEs
t = np.linspace(0, 10, 101)

# Solve the ODEs
sol = odeint(system, y0, t)

# Print the solution

In this example, we first import the numpy and scipy.integrate modules using import numpy as np and from scipy.integrate import odeint.

We define the system of ODEs using a function called system. This function takes in two arguments: the state y and the time t. The state y is a list containing the values of x and y, and the function returns a list containing the values of dx/dt and dy/dt.

We define the initial conditions for x and y using y0 = [1, 1].

We define the time points at which to solve the ODEs using t = np.linspace(0, 10, 101). This creates an array of 101 equally spaced time points between 0 and 10.

We solve the ODEs using odeint(system, y0, t). This function takes in the system of ODEs, the initial conditions, and the time points at which to solve the ODEs, and returns a solution as an array.

Finally, we print the solution using print(sol).

Note: You’ll need to modify the code to define your own system of ODEs and initial conditions.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply