Learn R Programming

comphy (version 1.0.5)

Gquad: Numerical integration using \(n\)-point Gaussian quadrature.

Description

Computes the definite integral of \(f(x)\) between \(a\) and \(b\), using the method of Gaussian quadrature. The default number of points is

Usage

Gquad(f, a = -1, b = 1, n = 5)

Value

A list with three elements. The first is a numeric vector containing the nodes of the quadrature. The second is a numeric vector containing the corresponding weight. The third is a real number corresponding to the approximate value of the integral.

Arguments

f

A function to integrate.

a

Lower bound of integration (default -1).

b

Upper bound of integration (default 1).

n

Number of quadrature points (default 5).

Examples

Run this code
# Integral in [-1,1] of 2x-1.
# Value is -2 and n=1 is enough for exact result

# Define the function
f <- function(x) {ff <- 2*x-1; return(ff)}

# 1-point quadrature
ltmp <- Gquad(f,-1,1,n=1)

# The only zero is x1=0
print(ltmp$xt)

# The only weight is w1=2
print(ltmp$wt)

# Quadrature gives exact integral
print(ltmp$itg)

# 2-point quadrature
ltmp <- Gquad(f,-1,1,n=2)
print(ltmp) # Same result but more zeros and weights

# Default, n=5, is accurate enough
ltmp <- Gquad(exp,-1,1)
print(ltmp$itg)

# Different extremes of integration
ltmp <- Gquad(exp,1,4)
print(ltmp$itg)

Run the code above in your browser using DataLab