cmlabs.integrate.trapezoid
- cmlabs.integrate.trapezoid(xvals, yvals)[source]
Composite trapezoid method for numerical integration.
\[\begin{gather} \int_{a}^{b} f(x) \, dx \approx \sum_{i=0}^{n-1} \frac{f(x_i) + f(x_{i+1})}{2} (x_{i+1} - x_i) \end{gather}\]- Parameters:
xvals (array_like, 1-D) – The sorted x-coordinates of the data points.
yvals (array_like, 1-D) – The y-coordinates of the data points, i.e., \(f(x)\).
- Returns:
The approximate value of the integral.
- Return type:
float
Notes
The trapezoid rule approximates the area under the curve by dividing it into trapezoids. The height of each trapezoid is determined by the function value at the endpoints of the interval.
This method is second-order accurate. The error is approximately:
\[|R_n(f)| \leq \frac{M(b-a)}{12} h^2, \quad \max_{x \in [a, b]} |f''(x)| \leq M\]where \(h\) is the width of the rectangles and depends on the number of intervals \(n\).
Examples
>>> # import numpy as np >>> # from cmlabs.integrate import trapezoid >>> # xvals = np.array([0, 1, 2, 3]) >>> # yvals = np.array([0, 1, 4, 9]) >>> trapezoid(xvals, yvals) 9.5