Learn R Programming

comphy (version 1.0.5)

numint_reg: Numerical integration using the trapezoid or simpson's rule

Description

Computes the definite integral of \(f(x)\) between \(a\) and \(b\), using one of the three numerical integration Newton-Cotes rules, trapezoid, Simpson's 1/3 or Simpson's 3/8.

Usage

numint_reg(x, f, scheme = "sim13")

Value

A real number, corresponding to the numeric approximation of the definite integral of \(f(x)\).

Arguments

x

A vector of real numbers. Grid points corresponding to the tabulated (known) values of the function. These must be equally spaced (regular grid).

f

A vector of real numbers. Tabulated (known) values of the function, corresponding to the grid x.

scheme

A character indicating the integration rule to follow. Possible values are "trap" (trapezoid rule), "sim13" (Simpson's 1/3 rule), and "sim38" (Simpson's 3/8 rule). Default scheme is "sim13".

Details

The default method is Simpson's 1/3 rule. For this method to be applied correctly, the number of regular intervals must be even. If this is not the case, the area corresponding to the last interval will be calculated with the trapezoid rule with a warning being posted.

When using the Simpson's 3/8 rule, the number of regular intervals must be a multiple of 3. If this is not the case, the last or last two intervals will be computed with the trapezoid rule.

Examples

Run this code
# Tabulated values: f(x) = x^2
x <- seq(0,2,length.out=21) # number of intervals is even
f <- x^2

# Integral between 0 and 2
# The correct result is 2^3/3=8/3=2.6666...
nvalue <- numint_reg(x,f) # Defaul nethod simpson's 1/3
print(nvalue)

# If the number of intervals is not even,
# a warning is issued
y <- seq(0,2,length.out=22)
g <- y^2
nvalue <- numint_reg(y,g)
print(nvalue)

Run the code above in your browser using DataLab