0
0
SciPydata~5 mins

ODE solver methods (RK45, BDF) in SciPy

Choose your learning style9 modes available
Introduction

We use ODE solvers to find solutions to equations that describe how things change over time. RK45 and BDF are two common methods to do this accurately and efficiently.

Modeling how a population grows or shrinks over time.
Simulating the cooling of a hot object until it reaches room temperature.
Predicting the motion of a pendulum swinging back and forth.
Understanding chemical reactions that change concentrations over time.
Syntax
SciPy
from scipy.integrate import solve_ivp

solve_ivp(fun, t_span, y0, method='RK45', t_eval=None, dense_output=False, **options)

fun is the function defining the ODE system.

t_span is the time interval as (start, end).

Examples
Solves the ODE from time 0 to 10 using the RK45 method.
SciPy
solve_ivp(fun, (0, 10), [1], method='RK45')
Solves the ODE from time 0 to 10 using the BDF method, good for stiff problems.
SciPy
solve_ivp(fun, (0, 10), [1], method='BDF')
Returns solution values at specific times using RK45.
SciPy
solve_ivp(fun, (0, 5), [2], method='RK45', t_eval=[0,1,2,3,4,5])
Sample Program

This program solves a simple decay ODE using both RK45 and BDF methods. It prints the final value and shows a plot comparing both solutions.

SciPy
from scipy.integrate import solve_ivp
import numpy as np
import matplotlib.pyplot as plt

# Define the ODE: dy/dt = -2y (exponential decay)
def decay(t, y):
    return -2 * y

# Time interval and initial value
t_span = (0, 5)
y0 = [1]

# Solve using RK45 method
sol_rk45 = solve_ivp(decay, t_span, y0, method='RK45', t_eval=np.linspace(0, 5, 100))

# Solve using BDF method
sol_bdf = solve_ivp(decay, t_span, y0, method='BDF', t_eval=np.linspace(0, 5, 100))

# Print final values
print(f"RK45 final value: {sol_rk45.y[0, -1]:.5f}")
print(f"BDF final value: {sol_bdf.y[0, -1]:.5f}")

# Plot results
plt.plot(sol_rk45.t, sol_rk45.y[0], label='RK45')
plt.plot(sol_bdf.t, sol_bdf.y[0], label='BDF', linestyle='--')
plt.xlabel('Time')
plt.ylabel('y')
plt.title('Solving dy/dt = -2y with RK45 and BDF')
plt.legend()
plt.show()
OutputSuccess
Important Notes

RK45 is a fast and accurate method for most problems that are not stiff.

BDF is better for stiff problems where solutions change very quickly or slowly.

You can choose the method based on your problem's behavior for better results.

Summary

ODE solvers help find how things change over time using math.

RK45 is good for general problems; BDF works well for stiff problems.

Use solve_ivp from scipy to apply these methods easily.