Trapezoidal Rule is used for approximating definite integral.

This method works by approximating the area under the function (in given interval) as trapezoid(s).

As can be seen, the bigger the *n *(more intervals) is, the better the integral is approximated.

## Formula:

Where:

*a*is the beggining of the interval,*b*is the end of the interval,*n*is the number of steps (number of trapezoids to use),*f(x)*is the function to integrate,*m*is the height of*i*-th trapezoid.

## Example:

Let’s approximate this definite integral with *n = 5*.

As can be seen, for *n = 5*, we calculated that the deinite integral is equal to 68/25 = 2.72, which is fairly close to the actual value: 8/3 = 2.(6).

## Trapezoidal Rule N Comparison

n | I | Error |
---|---|---|

5 | 68/25 = 2.72 | 4/75 = 0.05(3) |

10 | 67/25 = 2.68 | 1/75 = 0.01(3) |

25 | 1668/625 = 2.6688 | 4/1875= 0.0021(3) |

## Algorithm:

IN: Function f, which is continous function, interval [a,b] and number of iterations to perform - n. OUT: Defined Integral approximation of given function in given interval. 1. Calculate step = (b - a) / n. It will be used as the step size of each iteration. 2. Assign 0.5 * (f(a) + f(b)) to variable integral. 3. Initialize variable i to 0. 4. Add f(a + step * i) to variable integral. 5. Increase i by one. 6. Check if i is smaller than n. If it is go to step 4. 7. Multiply integral by step. 8. End algorithm and return integral.

## Sample Output:

f(x) = x * x -2 2 1000000 integral: 5.33334933334409

## Pros:

- Easy to implement

## Cons:

- Requires great number of iterations to be accurate, especially for big intervals (huge value of b – a)

Java Implementation R Implementation C# Implementation Python Implementation C++ Implementation