Computes the definite integral of a function using either the trapezoidal rule or Simpson's rule for numerical approximation.

integrate(f, a, b, n = 10000, method = "simpson")

Arguments

f

A function to be integrated (must be vectorized)

a

Lower bound of integration (numeric)

b

Upper bound of integration (numeric, must be > a)

n

Number of subdivisions (default = 10000, must be ≥ 2)

method

Integration method: "trapezoidal" or "simpson" (default)

Value

The approximated value of the integral (numeric)

Examples

# Integrate x^2 from 0 to 1 (exact answer = 1/3)
integrate(function(x) x^2, 0, 1)
#> [1] 0.3333333

# Compare methods
integrate(sin, 0, pi, method = "trapezoidal")
#> [1] 2
integrate(sin, 0, pi, method = "simpson")
#> [1] 2

# Vectorized function example
integrate(dnorm, -1.96, 1.96) # Approx 0.95
#> [1] 0.9500042