# Trapezoidal rule

(Redirected from Trapezium rule)
The function f(x) (in blue) is approximated by a linear function (in red).

In numerical analysis, the trapezoidal rule (also known as the trapezoid rule or trapezium rule) is a technique for approximating the definite integral

$\int_{a}^{b} f(x)\,dx.$

The trapezoidal rule works by approximating the region under the graph of the function $f(x)$ as a trapezoid and calculating its area. It follows that

$\int_{a}^{b} f(x)\, dx \approx (b-a) \left[\frac{f(a) + f(b)}{2} \right].$

## Applicability and alternatives

The trapezoidal rule is one of a family of formulas for numerical integration called Newton–Cotes formulas, of which the midpoint rule is similar to the trapezoid rule. Simpson's rule is another member of the same family, and in general has faster convergence than the trapezoidal rule for functions which are twice continuously differentiable, though not in all specific cases. However for various classes of rougher functions (ones with weaker smoothness conditions), the trapezoidal rule has faster convergence in general than Simpson's rule.[1]

Moreover, the trapezoidal rule tends to become extremely accurate when periodic functions are integrated over their periods, which can be analyzed in various ways.[2][3]

For non-periodic functions, however, methods with unequally spaced points such as Gaussian quadrature and Clenshaw–Curtis quadrature are generally far more accurate; Clenshaw–Curtis quadrature can be viewed as a change of variables to express arbitrary integrals in terms of periodic integrals, at which point the trapezoidal rule can be applied accurately.

## Numerical implementation

### Uniform grid

For a domain discretized into N equally spaced panels, or N+1 grid points (1, 2, ..., N+1), where the grid spacing is h=(b-a)/N, the approximation to the integral becomes

$\int_{a}^{b} f(x)\, dx \approx \frac{h}{2} \sum_{k=1}^{N} \left( f(x_{k+1}) + f(x_{k}) \right)$ ${}= \frac{b-a}{2N}(f(x_1) + 2f(x_2) + 2f(x_3) + \ldots + 2f(x_N) + f(x_{N+1})).$

### Non-uniform grid

When the grid spacing is non-uniform, one can use the formula

$\int_{a}^{b} f(x)\, dx \approx \frac{1}{2} \sum_{k=1}^{N} \left( x_{k+1} - x_{k} \right) \left( f(x_{k+1}) + f(x_{k}) \right).$

## Error analysis

The error of the composite trapezoidal rule is the difference between the value of the integral and the numerical result:

$\text{error} = \int_a^b f(x)\,dx - \frac{b-a}{N} \left[ {f(a) + f(b) \over 2} + \sum_{k=1}^{N-1} f \left( a+k \frac{b-a}{N} \right) \right]$

There exists a number ξ between a and b, such that[4]

$\text{error} = -\frac{(b-a)^3}{12N^2} f''(\xi)$

It follows that if the integrand is concave up (and thus has a positive second derivative), then the error is negative and the trapezoidal rule overestimates the true value. This can also be seen from the geometric picture: the trapezoids include all of the area under the curve and extend over it. Similarly, a concave-down function yields an underestimate because area is unaccounted for under the curve, but none is counted above. If the interval of the integral being approximated includes an inflection point, the error is harder to identify.

In general, three techniques are used in the analysis of error:[5]

An asymptotic error estimate for N → ∞ is given by

$\text{error} = -\frac{(b-a)^2}{12N^2} \big[ f'(b)-f'(a) \big] + O(N^{-3}).$

Further terms in this error estimate are given by the Euler–Maclaurin summation formula.

It is argued that the speed of convergence of the trapezoidal rule reflects and can be used as a definition of classes of smoothness of the functions.[2]

### Periodic functions

The trapezoidal rule often converges very quickly for periodic functions.[3] This can be explained intuitively as:

When the function is periodic and one integrates over one full period, there are about as many sections of the graph that are concave up as concave down, so the errors cancel.[5]

More detailed analysis can be found in.[2][3]

### "Rough" functions

For various classes of functions that are not twice-differentiable, the trapezoidal rule has sharper bounds than Simpson's rule.[1]

## Sample implementations

The trapezoidal rule is easily implemented in a spreadsheet. As an example, we show the integral of $f(x) = x^2$.

Performing integration using the trapezoid rule on the function $f(x)=x^2$

### Python

The (composite) trapezoidal rule can be implemented in Python as follows:

#!/usr/bin/env python
from __future__ import division

def trapezoidal_rule(f, a, b, n):
"""Approximates the definite integral of f from a to b by
the composite trapezoidal rule, using n subintervals"""
h = (b - a) / n
s = f(a) + f(b)
for i in xrange(1, n):
s += 2 * f(a + i * h)
return s * h / 2

print trapezoidal_rule(lambda x:x**9, 0.0, 10.0, 100000)
# displays 1000000000.75


### MATLAB and GNU Octave

The (composite) trapezoidal rule can be implemented in MATLAB as follows:

function s=trap(f,a,b,M)

%Input    - f is the integrand input as a string 'f'
%         - a and b are upper and lower limits of integration
%         - M is the number of subintervals
%Output   - s is the trapezoidal rule sum

h=(b-a)/M;
s=0;

for k=1:(M-1)
x=a+h*k;
s=s+feval(f,x);
end

s=h*(feval(f,a)+feval(f,b))/2+h*s;


An alternative implementation that uses the MATLAB's vectorization is

function s=Trapezoid(f,a,b,M)

%Input    - f is the integrand input as a string 'f', which must accept vector inputs
%         - a and b are upper and lower limits of integration
%         - M is the number of subintervals
%Output   - s is the trapezoidal rule sum

h=(b-a)/M;
x=a:h:b;
fval=feval(f,x);
s=h*sum(fval(1:end-1)+fval(2:end))/2;


### C++

In C++, one can implement the trapezoidal rule as follows.

template <class ContainerA, class ContainerB>
double trapezoid_integrate(const ContainerA &x,  const ContainerB &y) {
if (x.size() != y.size()) {
throw std::logic_error("x and y must be the same size");
}
double sum = 0.0;
for (int i = 1; i < x.size(); i++) {
sum += (x[i] - x[i-1]) * (y[i] + y[i-1]);
}
return sum * 0.5;
}


Here, x and y can be any object of a class implementing operator[] and size().