## Numerical integral of 1-D functions
# Equispaced grid points
t1 <- seq(0, 1, l = 201)
t2 <- seq(pi / 4, 3 * pi / 2, l = 201)
fx1 <- 2 * (t1^3) - t1^2 + 5 * t1 - 2 # True integral is equal to 2/3
fx2 <- sin(sqrt(t2)) # True integral is equal to 3.673555
int_fx1_trap <- integral1D(fx = fx1, t = t1, int_rule = "trapezoid",
equispaced = TRUE)
int_fx1_Simp <- integral1D(fx = fx1, t = t1, int_rule = "Simpson",
equispaced = TRUE)
int_fx2_trap <- integral1D(fx = fx2, t = t2, int_rule = "trapezoid",
equispaced = TRUE)
int_fx2_Simp <- integral1D(fx = fx2, t = t2, int_rule = "Simpson",
equispaced = TRUE)
# Check if the true integrals is approximated properly
abs(int_fx1_trap - 2/3) / (2/3)
abs(int_fx1_Simp - 2/3) / (2/3)
abs(int_fx2_trap - 3.673555) / 3.673555
abs(int_fx2_Simp - 3.673555) / 3.673555
# Non equispaced grid points
t <- c(seq(0, 0.3, l = 50), seq(0.31, 0.6, l = 150),
seq(0.61, 1, l = 100))
fx <- 2 * (t^3) - t^2 + 5 * t - 2
int_fx_trap <- integral1D(fx = fx, t = t, int_rule = "trapezoid",
equispaced = FALSE)
int_fx_Simp <- integral1D(fx = fx, t = t, int_rule = "Simpson",
equispaced = FALSE)
# Check if the true integral is approximated properly
abs(int_fx_trap - 2/3) / (2/3)
abs(int_fx_Simp - 2/3) / (2/3)
## Numerical integral of 2-dimensional functions
# Equispaced grid points
s <- seq(0, 2, l = 101)
t <- seq(1, 5, l = 151)
fxy <- outer(s^2, t^3) # True integral is equal to 416
int_fxy_trap <- integral2D(fxy = fxy, s = s, t = t, int_rule = "trapezoid",
equispaced_x = TRUE, equispaced_y = TRUE)
int_fxy_Simp <- integral2D(fxy = fxy, s = s, t = t, int_rule = "Simpson",
equispaced_x = TRUE, equispaced_y = TRUE)
# Check if the true integral is approximated properly
abs(int_fxy_trap - 416) / 416
abs(int_fxy_Simp - 416) / 416
# Non equispaced grid points
s <- c(seq(0, 0.3, l = 150), seq(0.31, 1.6, l = 100),
seq(1.61, 2, l = 250))
t <- c(seq(1, 2.6, l = 170), seq(2.61, 4, l = 100),
seq(4.01, 5, l = 140))
fxy <- outer(s^2, t^3)
int_fxy_trap <- integral2D(fxy = fxy, s = s, t = t, int_rule = "trapezoid",
equispaced_x = FALSE, equispaced_y = FALSE)
# Check if the true integral is approximated properly
abs(int_fxy_trap - 416) / 416
Run the code above in your browser using DataLab