Step-by-Step Guide to Integrating a Function Using the Trapezoidal Rule in R
- Mathew Shem
- Nov 6, 2024
- 3 min read

Goal: To calculate the integral of the function f(x)=e−x2f(x) = e^{-x^2}f(x)=e−x2 over the interval [0,1][0, 1][0,1] using the Trapezoidal Rule. We’ll also adjust the accuracy and rounding of the results as specified.
Step 1: Define the Function to Integrate
r
f <- function(x) exp(-x^2)
Here, we’re defining a function f in R, which represents f(x)=e−x2f(x) = e^{-x^2}f(x)=e−x2. The function f(x) calculates the value of e−x2e^{-x^2}e−x2 for any input xxx. This function will be used later in the code when we apply the Trapezoidal Rule.
Step 2: Understand the Trapezoidal Rule
The Trapezoidal Rule is a numerical method used to approximate the integral of a function. It works by dividing the area under the curve into trapezoids, calculating the area of each trapezoid, and summing these areas to get an approximation of the integral.
For a function f(x)f(x)f(x) over an interval [a,b][a, b][a,b], the Trapezoidal Rule with nnn subintervals gives:
Integral≈h2(f(x0)+2∑i=1n−1f(xi)+f(xn))\text{Integral} \approx \frac{h}{2} \left( f(x_0) + 2 \sum_{i=1}^{n-1} f(x_i) + f(x_n) \right)Integral≈2h(f(x0)+2i=1∑n−1f(xi)+f(xn))
where h=b−anh = \frac{b - a}{n}h=nb−a.
Step 3: Define the Trapezoidal Rule Function in R
r
trapezoidal_rule <- function(a, b, n) { h <- (b - a) / n x_values <- seq(a, b, by = h) y_values <- f(x_values) integral <- (h / 2) (2 sum(y_values) - y_values[1] - y_values[length(y_values)]) return(integral) }
This code block defines a function called trapezoidal_rule that calculates the integral of f(x) from a to b using the Trapezoidal Rule with nnn subintervals. Here’s a breakdown of each part:
Calculate the Interval Width: h <- (b - a) / n
Here, h is the width of each subinterval, calculated as the total interval length divided by the number of subintervals nnn.
Generate x-values: x_values <- seq(a, b, by = h)
x_values is a sequence of points from a to b spaced by h. These points are where the function f(x) will be evaluated.
Evaluate the Function: y_values <- f(x_values)
y_values stores the values of f(x) at each x in x_values. This gives the heights of the function at each point, which will be used to compute the area.
Calculate the Integral:
(h / 2) (2 sum(y_values) - y_values[1] - y_values[length(y_values)]) is the Trapezoidal Rule formula in R. It calculates the approximate integral by summing the trapezoid areas.
Return the Result: return(integral)
The function outputs the calculated integral.
Step 4: Set the Parameters for Integration
r
a <- 0 b <- 1
Here, a and b are the limits of integration, where a=0a = 0a=0 and b=1b = 1b=1. We want to find the integral of f(x)=e−x2f(x) = e^{-x^2}f(x)=e−x2 over this interval.
Step 5: Define the Accuracy and Rounding Specifications
r
accuracy_rounding <- list( list(target_accuracy = 4, round_to = 6, n_value = 100000), list(target_accuracy = 6, round_to = 4, n_value = 1000000), list(target_accuracy = 8, round_to = 6, n_value = 10000000) )
This part sets up a list called accuracy_rounding, which contains different accuracy and rounding requirements. Each entry in the list specifies:
target_accuracy: Desired number of decimal places for accuracy.
round_to: Number of decimal places to round the result.
n_value: Number of subintervals nnn for the Trapezoidal Rule.
These settings allow us to test the integral’s accuracy with different levels of precision.
Step 6: Perform the Integration for Each Accuracy Specification
r
for (spec in accuracy_rounding) { # Calculate integral with specified n integral <- trapezoidal_rule(a, b, spec$n_value) # Round the result as specified integral_rounded <- round(integral, spec$round_to) # Print the result with formatted text cat(sprintf("Target accuracy: %d decimal places, rounded to %d decimal places\n", spec$target_accuracy, spec$round_to)) cat(sprintf("Integration result with n = %d: %.*f\n", spec$n_value, spec$round_to, integral_rounded)) cat("--------------------------------------------------\n") }
This loop performs the integration using the parameters specified in accuracy_rounding. Here’s what each part does:
Calculate the Integral:
integral <- trapezoidal_rule(a, b, spec$n_value) calculates the integral for the given number of intervals (n_value).
Round the Result:
integral_rounded <- round(integral, spec$round_to) rounds the result to the specified decimal places.
Print Results:
The cat() and sprintf() functions display the results. Each iteration prints:
Target accuracy and rounding details.
The rounded integration result.
Each result is separated by a line for clarity.
(I would have uploaded the exact R file containing the code and the end result as shown below however, the file failed to upload, if you fail to understand the above notes please request for assistance via WhatsApp +254768944928 or Email shemmathew.biostatistician@gmail.com)
BUY ME A CUP OF COFFEE - TILL NUMBER 8967608
Commentaires