cmlabs.integrate.rectangle

cmlabs.integrate.rectangle(xvals, yvals, method='left')[source]

Composite rectangle method for numerical integration.

\[\begin{split}\begin{gather} \int_{a}^{b} f(x) \, dx \approx \sum_{i=0}^{n-1} f(x_i) \cdot (x_{i+1} - x_i) \\ \int_{a}^{b} f(x) \, dx \approx \sum_{i=1}^{n} f(x_i) \cdot (x_i - x_{i-1}) \end{gather}\end{split}\]
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)\).

  • method (str, optional, default: 'left') –

    The method to use for the rectangle rule. Options are:

    • ’left’

    • ’right’

Returns:

The approximate value of the integral.

Return type:

float

Notes

The rectangle rule approximates the area under the curve by dividing it into rectangles. The height of each rectangle is determined by the function value at the left or right endpoint of the interval, depending on the chosen method.

These methods are first-order accurate. The error is approximately:

\[\begin{split}\begin{gather} |R_n(f)| \leq \frac{M(b-a)}{2} h, \\ \max_{x \in [a, b]} |f'(x)| \leq M \end{gather}\end{split}\]

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 rectangle
>>> # xvals = np.array([0, 1, 2, 3])
>>> # yvals = np.array([0, 1, 4, 9])
>>> rectangle(xvals, yvals, method='left')
5.0