Working with scipy.integrate
The scipy.integrate module provides tools for numerical integration and for solving ordinary differential equations (ODEs).
It’s especially useful when:
- You need to compute definite integrals
- You want to integrate functions without closed-form solutions
- You’re solving systems of differential equations
Example 1: Definite Integral with quad
Use integrate.quad() to compute the definite integral of a function within a given range.
Definite Integral of sin(x) from 0 to π
# Integrand
f = lambda x: np.sin(x)
# Integrate from 0 to π
val, err = integrate.quad(f, 0, np.pi)
print("Integral value:", val)
print("Estimated error:", err)
Explanation:
quad()returns both the integral value and an estimated numerical error.- Best suited for smooth, continuous functions.
Example 2: Solving an ODE with solve_ivp
Use integrate.solve_ivp() to solve initial value problems (IVPs) for differential equations.
Solve y' = -2y, y(0) = 1
# Derivative function
def dydt(t, y):
return -2 * y
# Time span and evaluation points
t_span = (0, 3)
t_eval = np.linspace(*t_span, 100)
# Solve the ODE
sol = integrate.solve_ivp(dydt, t_span, y0=[1.0], t_eval=t_eval)
print("First 5 y values:", sol.y[0][:5])
Explanation:
solve_ivp()numerically integrates an ODE over a time interval.t_span definesthe range of integration.y0provides the initial conditions for the system.
Key Takeaways
quad()— integrates single-variable functions over a defined range.solve_ivp()— solves initial value problems for ordinary differential equations.- Use
NumPyarrays when defining functions to ensure full compatibility withSciPy’s integration tools.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.