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
Setting Up
Importing the required modules:
Import NumPy and SciPy Integrate
import numpy as np from scipy import integrate
Example 1: Definite Integral with quad
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)
Here:
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
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])
Here:
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.
In the next lesson, we’ll look at Signal and Image Processing Modules in SciPy.
Quiz
0 / 1
What is the primary use of the scipy.integrate
module?
Performing symbolic integration of algebraic expressions.
Solving linear algebra problems.
Numerical integration and solving ordinary differential equations.
Generating random numbers for simulations.
학습 자료
AI 튜터
디자인
업로드
수업 노트
즐겨찾기
도움말