Working with scipy.integrate
The scipy.integrate
module provides functions for numerical integration and solving ordinary differential equations (ODEs).
It's useful when:
- You need to evaluate a definite integral
- You want to integrate functions without an exact formula
- You are solving systems of ODEs
Example 1: Definite Integral with quad
You can use the quad
function to evaluate a definite integral.
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 the integral value and an error estimate- This is useful for smooth, well-behaved functions
Example 2: Solving an ODE with solve_ivp
You can use the solve_ivp
function to solve an ODE.
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
solves initial value problems for ODEst_span
is the interval of integrationy0
is the initial condition
Key Takeaways
quad()
: Integrates single-variable functions over a given range.solve_ivp()
: Solves initial value problems for differential equations.- Use NumPy for defining functions and arrays to ensure compatibility with SciPy's integration routines.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.