<Previous Page: Numerical Differentiation|Next Page: Numerical Solutions to First-Order ODEs>
In this page, we will learn about numerical integration, evaluating integrals numerically using the C programming language.
For users of other programming languages, please refer to the following pages:
Numerical Integration with Python
Numerical Integration with Julia
Numerical Integration with Fortran
To evaluate integrals numerically, let's first review integration. Here, we consider the integration of a function
In the above discussion, we considered evaluating the integral in equation (
The approximation formula for integration in equation (
In this section, we numerically evaluate the following integral using the trapezoidal rule (Equation (
#include <stdio.h> #include <math.h> int main() { int i, n; double a, b; double x, h, f, s; n = 20; a = 0.0; b = 1.0; h = (b - a) / n; x = a; f = 4.0 / (1.0 + x * x); s = 0.5 * h * f; for (i = 1; i < n; i++) { x = a + h * i; f = 4.0 / (1.0 + x * x); s = s + h * f; } x = b; f = 4.0 / (1.0 + x * x); s = s + 0.5 * h * f; printf("Result:\n"); printf("%26.16e\n", s); return 0; }
The above C code performs numerical integration using the trapezoidal rule. Here is an explanation of the code:
f
is defined to calculate the value of the function x
.trapezoidal_rule
is defined, which takes the integration range n
as inputs and evaluates the integral using the trapezoidal rule.trapezoidal_rule
function, the width of each trapezoid is calculated as h
. The function computes the average value at the endpoints and then adds the contributions from the interior points to the sum. Finally, the sum is multiplied by h
to obtain the approximate value of the integral.main
function, the integration range n
are set, and the trapezoidal_rule
function is called to display the result.Does the result approximate n
will yield more accurate results. Try changing the value of n
to observe how the error changes.
<Previous page: Numerical Differentiation|Next page: Numerical Solutions of First-Order Ordinary Differential Equations>