File tree 1 file changed +47
-0
lines changed
1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
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 ()
You can’t perform that action at this time.
0 commit comments