Skip to content

Commit d0268c2

Browse files
authored
Merge pull request #1 from ltdouthit/Maths/Numerical_Intergration
Maths/numerical intergration
2 parents 14fef95 + 698faa9 commit d0268c2

File tree

2 files changed

+92
-0
lines changed

2 files changed

+92
-0
lines changed

Diff for: Maths/SimpsonRule.py

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
2+
'''
3+
Numerical integration or quadrature for a smooth function f with known values at x_i
4+
5+
This method is the classical approch of suming 'Equally Spaced Abscissas'
6+
7+
method 2:
8+
"Simpson Rule"
9+
10+
'''
11+
12+
def method_2(boundary, steps):
13+
# "Simpson Rule"
14+
# int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn)
15+
h = (boundary[1] - boundary[0]) / steps
16+
a = boundary[0]
17+
b = boundary[1]
18+
x_i = makePoints(a,b,h)
19+
y = 0.0
20+
y += (h/3.0)*f(a)
21+
cnt = 2
22+
for i in x_i:
23+
y += (h/3)*(4-2*(cnt%2))*f(i)
24+
cnt += 1
25+
y += (h/3.0)*f(b)
26+
return y
27+
28+
def makePoints(a,b,h):
29+
x = a + h
30+
while x < (b-h):
31+
yield x
32+
x = x + h
33+
34+
def f(x): #enter your function here
35+
y = (x-0)*(x-0)
36+
return y
37+
38+
def main():
39+
a = 0.0 #Lower bound of integration
40+
b = 1.0 #Upper bound of integration
41+
steps = 10.0 #define number of steps or resolution
42+
boundary = [a, b] #define boundary of integration
43+
y = method_2(boundary, steps)
44+
print 'y = {0}'.format(y)
45+
46+
if __name__ == '__main__':
47+
main()

Diff for: Maths/TrapezoidalRule.py

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
'''
2+
Numerical integration or quadrature for a smooth function f with known values at x_i
3+
4+
This method is the classical approch of suming 'Equally Spaced Abscissas'
5+
6+
method 1:
7+
"extended trapezoidal rule"
8+
9+
'''
10+
11+
def method_1(boundary, steps):
12+
# "extended trapezoidal rule"
13+
# int(f) = dx/2 * (f1 + 2f2 + ... + fn)
14+
h = (boundary[1] - boundary[0]) / steps
15+
a = boundary[0]
16+
b = boundary[1]
17+
x_i = makePoints(a,b,h)
18+
y = 0.0
19+
y += (h/2.0)*f(a)
20+
for i in x_i:
21+
#print(i)
22+
y += h*f(i)
23+
y += (h/2.0)*f(b)
24+
return y
25+
26+
def makePoints(a,b,h):
27+
x = a + h
28+
while x < (b-h):
29+
yield x
30+
x = x + h
31+
32+
def f(x): #enter your function here
33+
y = (x-0)*(x-0)
34+
return y
35+
36+
def main():
37+
a = 0.0 #Lower bound of integration
38+
b = 1.0 #Upper bound of integration
39+
steps = 10.0 #define number of steps or resolution
40+
boundary = [a, b] #define boundary of integration
41+
y = method_1(boundary, steps)
42+
print 'y = {0}'.format(y)
43+
44+
if __name__ == '__main__':
45+
main()

0 commit comments

Comments
 (0)