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.
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);
If you have any doubts about the implementation of Trapezoidal method in C programming, let us know about it in the comment section. Find more about it on Wikipedia.
Is it necessary to use sqrt() function in another separate method in this trapezium theorem in c programming?
No, it is not required. You can include it within the main() method. But, then the complexity of the main method woukd increase and it will be difficult to understand this c program.
This trapezium theorem is just so simple and easily understandable. Thanks.