__author__ ars from matplotlib import mlab import math random def get_

 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
80
81
82
83
84
85
__author__ = 'ars'
from matplotlib import mlab
import math, random
def get_i():
return math.e ** 1 - math.e ** 0
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, 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 'Rect'
print ' '.join([
'\t',
str(n),
str(math.fabs(integrate(func, mim_lim, max_lim, n))),
str(math.fabs(integrate(func, mim_lim, max_lim, n)) + d)])
def trapezium_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 'Tr'
print ' '.join([
'\t',
str(n),
str(math.fabs(integrate(func, mim_lim, max_lim, n))),
str(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 'Sim'
print ' '.join([
'\t',
str(n),
str(math.fabs(integrate(func, mim_lim, max_lim, n))),
str(math.fabs(integrate(func, mim_lim, max_lim, n)) + d)])
def monte_karlo_method(func, n):
in_d, out_d = 0., 0.
for i in range(n):
x, y = random.uniform(0, 1), random.uniform(0, 3)
if y < func(x): in_d += 1
return math.fabs(in_d / n * 3)
from numpy import random
import matplotlib.pyplot as plt
a = sorted([monte_karlo_method(lambda x: math.e ** x, 1000) for x in range(10000)])
plt.hist(a, 1000)
plt.show()