from matplotlib import mlab import math def method_of_rectangles func

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
from matplotlib import mlab
import math
def method_of_rectangles(func, mim_lim, max_lim, delta):
def integrate(func, mim_lim, max_lim, n):
integral = 0.0
step = (max_lim - mim_lim) / n
for x in mlab.frange(mim_lim, max_lim, step):
integral += step * func(x + step / 2)
return integral
d, n = 1, 10
while d > delta:
d = integrate(func, mim_lim, max_lim, n) - integrate(func, mim_lim, max_lim, n * 2)
n *= 2
step = (max_lim - mim_lim) / n
print integrate(func, mim_lim, max_lim, n)
print (step ** 2) * (max_lim - mim_lim) / 24 * func(step / 2)
method_of_rectangles(lambda x: math.e ** x, 0.0, 1.0, 0.01)