The Algorithms logo
The Algorithms
AboutDonate

The Rectangular Method

C

The rectangle method (also called the midpoint rule) is the simplest method in Mathematics used to compute an approximation of a definite integral.

Let's check this method for the next function: $$f(x) = ({e^x / 2})*(cos(x)-sin(x))$$ with $\varepsilon = 0.001$

import math 
import numpy as np

def integration(a,b,n):
    h = (b-a)/n
    r = f(a) + f(b)
    i = 1
    while i < n:
        x = a + i*h
        r = r + 4 * f(x)
        i = i + 1
        x = a + i * h
        r = r +2*f(x)
        i = i + 1
    r = r * h / 3
    print("Result: ", r) 

def rectangles(a,b,n):
    
    z = (b-a)/n
    i = a
    s1=0
    s2=0
    while i<b:
        
        s1=s1+f(i)*z
        i=i+z
    i=a 
    while i<b:
        i=i+z
        s2=s2+f(i)*z

    print('Result of formula of the left rectangles: ',s1)
    print('Result of formula of the left rectangles: ',s2)

Some input data

def f(x):
    return  (math.e**x / 2)*(math.cos(x)-math.sin(x))

n = 4  
a = 2.
b = 3.
Si = []

integration(a,b,n)
rectangles(a,b,n)
Result:  -10.297317477276613
Result of formula of the left rectangles:  -7.576924395545134
Result of formula of the left rectangles:  -9.192576890365931