from matplotlib import mlab import math random function lambda _x math

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
from matplotlib import mlab
import math, random
function = lambda _x: math.exp(_x) * _x
integ_function = lambda _x: math.exp(_x) * (_x - 1)
a = 0.0
b = 2.0
delta = 0.001
def rectangles_method(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, step):
integral += step * func(x + step / 2)
return integral
d, n = 1, 1
while math.fabs(d) > delta:
d = (integrate(func, mim_lim, max_lim, n * 2) - integrate(func, mim_lim, max_lim, n)) / 3
n *= 2
print_result('Rectang', n, math.fabs(integrate(func, mim_lim, max_lim, n)), math.fabs(integrate(func, mim_lim, max_lim, n)) + d)
def trapeze_method(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, step):
integral += step * (func(x) + func(x + step)) / 2
return integral
d, n = 1, 1
while math.fabs(d) > delta:
d = (integrate(func, mim_lim, max_lim, n * 2) - integrate(func, mim_lim, max_lim, n)) / 3
n *= 2
print_result('Trapeze', n, math.fabs(integrate(func, mim_lim, max_lim, n)), math.fabs(integrate(func, mim_lim, max_lim, n)) + d)
def simpson_method(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 + step / 2, max_lim - step / 2, step):
integral += step / 6 * (func(x - step / 2) + 4 * func(x) + func(x + step / 2))
return integral
d, n = 1, 1
while math.fabs(d) > delta:
d = (integrate(func, mim_lim, max_lim, n * 2) - integrate(func, mim_lim, max_lim, n)) / 15
n *= 2
print_result('Simpson', n, math.fabs(integrate(func, mim_lim, max_lim, n)), math.fabs(integrate(func, mim_lim, max_lim, n)) + d)
max_y_for_monte_carlo = 20
def monte_karlo_method(func, n):
in_d, out_d = 0.0, 0.0
for i in range(n):
x, y = random.uniform(a, b), random.uniform(0, max_y_for_monte_carlo)
if y < func(x): in_d += 1
return math.fabs(in_d / n * max_y_for_monte_carlo * (b-a))
def print_result(method, n, without_rich, with_rich):
print method + '\t\t' + str(n) + '\t' + str(without_rich) + '\t' + str(with_rich)
simpson_method(function, a, b, delta)
trapeze_method(function, a, b, delta)
rectangles_method(function, a, b, delta)
print 'Montecar\t' + str(monte_karlo_method(function, 100))
print 'Real result:\t' + str(integ_function(b) - integ_function(a))