Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

trapz

Trapezoid Rule Numerical Integration


Description

Computes the integral of Y with respect to X using trapezoid rule integration.

Usage

trapz(x, y)

Arguments

x

Sorted vector of x-axis values.

y

Vector of y-axis values.

Details

The function has only two lines:

idx = 2:length(x)
    return (as.double( (x[idx] - x[idx-1]) %*% (y[idx] + y[idx-1])) / 2)

Value

Integral of Y with respect to X or area under the Y curve.

Note

Trapezoid rule is not the most accurate way of calculating integrals (it is exact for linear functions), for example Simpson's rule (exact for linear and quadratic functions) is more accurate.

Author(s)

Jarek Tuszynski (SAIC) jaroslaw.w.tuszynski@saic.com

References

D. Kincaid & W. Chaney (1991), Numerical Analysis, p.445

See Also

Examples

# integral of sine function in [0, pi] range suppose to be exactly 2.
  # lets calculate it using 10 samples:
  x = (1:10)*pi/10
  trapz(x, sin(x))
  # now lets calculate it using 1000 samples:
  x = (1:1000)*pi/1000
  trapz(x, sin(x))

caTools

Tools: Moving Window Statistics, GIF, Base64, ROC AUC, etc

v1.18.2
GPL-3
Authors
Jarek Tuszynski <jaroslaw.w.tuszynski@saic.com>
Initial release
2021-03-26

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.