Approximate an Integral Using the Trapezoidal Rule in C

CCBeginner
Practice Now

Introduction

In this lab, we will learn how to approximate an integral using the trapezoidal rule in C. The lab covers the following steps: 1) defining the function f(x) and the interval [a, b], 2) splitting the interval and applying the trapezoidal formula to calculate the approximate integral, and 3) printing the final result. This lab aims to provide a practical understanding of numerical integration techniques using the C programming language.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/BasicsGroup -.-> c/variables("`Variables`") c/ControlFlowGroup -.-> c/for_loop("`For Loop`") c/FunctionsGroup -.-> c/function_declaration("`Function Declaration`") c/FunctionsGroup -.-> c/math_functions("`Math Functions`") subgraph Lab Skills c/output -.-> lab-435132{{"`Approximate an Integral Using the Trapezoidal Rule in C`"}} c/variables -.-> lab-435132{{"`Approximate an Integral Using the Trapezoidal Rule in C`"}} c/for_loop -.-> lab-435132{{"`Approximate an Integral Using the Trapezoidal Rule in C`"}} c/function_declaration -.-> lab-435132{{"`Approximate an Integral Using the Trapezoidal Rule in C`"}} c/math_functions -.-> lab-435132{{"`Approximate an Integral Using the Trapezoidal Rule in C`"}} end

Define f(x) and Interval [a,b]

In this step, we will define the mathematical function f(x) and specify the interval [a,b] for numerical integration using the trapezoidal rule in C.

First, let's create a new C source file to implement our integral approximation:

cd ~/project
nano integral_approximation.c

Now, let's write the initial code to define our function and interval:

#include <stdio.h>
#include <math.h>

// Define the function to integrate f(x)
double f(double x) {
    // Example: f(x) = x^2
    return x * x;
}

int main() {
    // Define the interval [a, b]
    double a = 0.0;  // Lower bound
    double b = 1.0;  // Upper bound

    printf("Integral Approximation\n");
    printf("Function: f(x) = x^2\n");
    printf("Interval: [%.2f, %.2f]\n", a, b);

    return 0;
}

Let's compile and run the code to verify:

gcc -o integral_approximation integral_approximation.c -lm
./integral_approximation

Example output:

Integral Approximation
Function: f(x) = x^2
Interval: [0.00, 1.00]

In this code, we've defined:

  • A function f(x) that returns x^2
  • An interval [a, b] from 0 to 1
  • Printed the function and interval details

The function f(x) can be modified to represent any mathematical function you want to integrate.

Split Interval and Apply Trapezoidal Formula

In this step, we will modify our previous code to implement the trapezoidal rule for numerical integration by splitting the interval and calculating the approximate integral.

Open the previous source file and update the code:

cd ~/project
nano integral_approximation.c

Replace the contents with the following implementation:

#include <stdio.h>
#include <math.h>

// Define the function to integrate f(x)
double f(double x) {
    return x * x;
}

// Trapezoidal Rule Implementation
double trapezoidalRule(double a, double b, int n) {
    double h = (b - a) / n;  // Width of each trapezoid
    double sum = 0.5 * (f(a) + f(b));  // First and last points

    for (int i = 1; i < n; i++) {
        double x = a + i * h;
        sum += f(x);
    }

    return sum * h;
}

int main() {
    // Define the interval [a, b]
    double a = 0.0;  // Lower bound
    double b = 1.0;  // Upper bound
    int n = 100;     // Number of trapezoids

    double approximateIntegral = trapezoidalRule(a, b, n);

    printf("Integral Approximation\n");
    printf("Function: f(x) = x^2\n");
    printf("Interval: [%.2f, %.2f]\n", a, b);
    printf("Number of Trapezoids: %d\n", n);
    printf("Approximate Integral: %.6f\n", approximateIntegral);

    return 0;
}

Compile and run the updated code:

gcc -o integral_approximation integral_approximation.c -lm
./integral_approximation

Example output:

Integral Approximation
Function: f(x) = x^2
Interval: [0.00, 1.00]
Number of Trapezoids: 100
Approximate Integral: 0.333333

Key points in this implementation:

  • trapezoidalRule() function calculates the approximate integral
  • h represents the width of each trapezoid
  • n determines the number of trapezoids for approximation
  • Increasing n improves the approximation accuracy

Print the Approximate Integral

In this step, we will enhance our integral approximation program by adding more detailed output and comparing the numerical result with the exact integral value.

Open the previous source file and update the code:

cd ~/project
nano integral_approximation.c

Modify the code to include more comprehensive output:

#include <stdio.h>
#include <math.h>

// Define the function to integrate f(x)
double f(double x) {
    return x * x;
}

// Exact integral calculation for x^2 from 0 to 1
double exactIntegral() {
    return 1.0 / 3.0;
}

// Trapezoidal Rule Implementation
double trapezoidalRule(double a, double b, int n) {
    double h = (b - a) / n;  // Width of each trapezoid
    double sum = 0.5 * (f(a) + f(b));  // First and last points

    for (int i = 1; i < n; i++) {
        double x = a + i * h;
        sum += f(x);
    }

    return sum * h;
}

int main() {
    // Define the interval [a, b]
    double a = 0.0;  // Lower bound
    double b = 1.0;  // Upper bound
    int n = 100;     // Number of trapezoids

    double approximateIntegral = trapezoidalRule(a, b, n);
    double exact = exactIntegral();
    double error = fabs(approximateIntegral - exact);
    double percentError = (error / exact) * 100.0;

    // Formatted output with detailed information
    printf("Integral Approximation Results\n");
    printf("------------------------------\n");
    printf("Function:            f(x) = x^2\n");
    printf("Interval:            [%.2f, %.2f]\n", a, b);
    printf("Number of Trapezoids: %d\n", n);
    printf("\nNumerical Results:\n");
    printf("Approximate Integral: %.6f\n", approximateIntegral);
    printf("Exact Integral:       %.6f\n", exact);
    printf("\nError Analysis:\n");
    printf("Absolute Error:       %.6f\n", error);
    printf("Percent Error:        %.4f%%\n", percentError);

    return 0;
}

Compile and run the updated code:

gcc -o integral_approximation integral_approximation.c -lm
./integral_approximation

Example output:

Integral Approximation Results
------------------------------
Function:            f(x) = x^2
Interval:            [0.00, 1.00]
Number of Trapezoids: 100

Numerical Results:
Approximate Integral: 0.333333
Exact Integral:       0.333333

Error Analysis:
Absolute Error:       0.000000
Percent Error:        0.0000%

Key improvements in this version:

  • Added exactIntegral() function to compare numerical result
  • Calculated absolute and percentage errors
  • Provided more detailed and formatted output

Summary

In this lab, we learned how to approximate an integral using the trapezoidal rule in C. First, we defined the mathematical function f(x) and the interval [a, b] for numerical integration. Then, we implemented the trapezoidal rule by splitting the interval and applying the formula to calculate the approximate integral. Finally, we printed the result of the integral approximation.

The key steps in this lab were defining the function and interval, splitting the interval, and applying the trapezoidal formula to compute the approximate integral. By following these steps, we were able to implement a simple and effective numerical integration technique in C.

Other C Tutorials you may like