Midpoint Rule (Rectangle Method) Algorithm is used for approximating definite integral.

This method works by approximating the area under the function (in given interval) as rectangle(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 rectangles to use),
• f(x) is the function to integrate,
• m_i is the base of i-th rectangle.

## Example:

Let’s approximate this definite integral with n = 5.    As can be seen, for n = 5, we calculated that the definite integral is equal to 66/25 = 2.64, which is really close to the actual value: 8/3 = 2.(6).

## Midpoint Rule (Rectangle Method) N Comparison

nIError
566/25 = 2.642/75 = 0.02(6)
10133/50 = 2.661/150 = 0.00(6)
251666/625 = 2.66562/1875 = 0.0010(6)

## 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 to variable integral.
3. Initialize variable i to 1.
4. Add step * f(a + (i - 1) * step) to variable integral.
5. Increase i by one.
6. Check if i is smaller than or equal to n. If it is go to step 4.
7. End algorithm and return integral.```

## Sample Output:

```f(x) = x * x
-2
2
1000000

integral: 5.333333333344218```

## Pros:

• Easy to implement
• Works well with functions that are symmetrical along Y axis

## Cons:

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

Midpoint Rule (Rectangle Method) Algorithm