Skip to content

Commit 8ef43a7

Browse files
authored
Merge pull request TheAlgorithms#251 from ltdouthit/Maths/Numerical_Intergration
Maths/numerical intergration
2 parents 14fef95 + 537909d commit 8ef43a7

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

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)