C Program To Implement Trapezoidal Rule
Let’s understand the trapezoidal method in numerical analysis and implement trapezoidal rule in C programming language.
What is Trapezoidal Rule?
This numerical analysis method is used to approximating the definite integral. The trapezoidal numerical method works on the principle of straight line approximation.
This numerical method is also popularly known as Trapezoid Rule or Trapezium Rule.
This numerical analysis method is slower in convergence as compared to Simpson’s rule in numerical method.
Trapezium Rule Formula
This is a technique to approximate the definite integrals. It approximates the region under the graph of the function f(x) and calculates its area.
This method becomes more accurate and outputs perfect results when periodic functions are integrated over their periods.
Must Read: Gauss Seidel Method C Program
Note: This C program to solve trapezoidal rule is compiled with GNU GCC compiler on Linux Ubuntu operating system. However, this code is compatible with all other operating systems.
If you try to compile this C program for Trapezium Rule in Linux, you will get the following error:
/tmp/ccgL393M.o: In function `trapezoidal_rule':
test.c:(.text+0x13): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status
This is because the pow() method cannot be found in the library files. To overcome this error, you will have to explicitly include the math.h header file.
Compile the program using the following command:
gcc test.c -lm
C Program To Implement Trapezoidal Rule using Function
float trapezoidal_rule(float x)
int count, interval;
float lower_limit, upper_limit, result = 0, sum = 0, length;
printf("\nEnter the Intervals:\t");
printf("\nEnter Lower Limit:\t");
printf("\nEnter Upper Limit:\t");
length = (upper_limit - lower_limit) / interval;
for(count = 1; count <= interval - 1; count++)
sum = sum + trapezoidal_rule(lower_limit + count*length);
result = (trapezoidal_rule(lower_limit) + trapezoidal_rule(upper_limit) + 2*sum) * (length/2);
printf("\nTrapezoidal Rule Value:\t%f\n", result);
Must Read: Newton-Raphson Method C Program
Let’s discuss more on trapezoidal method C program in the comment section below if you have any compilation errors and any doubts about the same.
For more information on this trapezoidal method in numerical analysis, check Wikipedia.