2019-07-10 20:09:24 +00:00
|
|
|
"""
|
2018-10-19 12:48:28 +00:00
|
|
|
Numerical integration or quadrature for a smooth function f with known values at x_i
|
|
|
|
|
2019-07-10 20:09:24 +00:00
|
|
|
This method is the classical approch of suming 'Equally Spaced Abscissas'
|
2018-10-19 12:48:28 +00:00
|
|
|
|
2019-07-10 20:09:24 +00:00
|
|
|
method 2:
|
2018-10-19 12:48:28 +00:00
|
|
|
"Simpson Rule"
|
|
|
|
|
2019-07-10 20:09:24 +00:00
|
|
|
"""
|
2019-10-05 05:14:13 +00:00
|
|
|
|
|
|
|
|
2018-10-19 12:48:28 +00:00
|
|
|
def method_2(boundary, steps):
|
2019-10-05 05:14:13 +00:00
|
|
|
# "Simpson Rule"
|
|
|
|
# int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn)
|
2019-07-10 20:09:24 +00:00
|
|
|
h = (boundary[1] - boundary[0]) / steps
|
|
|
|
a = boundary[0]
|
|
|
|
b = boundary[1]
|
2019-10-05 05:14:13 +00:00
|
|
|
x_i = make_points(a, b, h)
|
2019-07-10 20:09:24 +00:00
|
|
|
y = 0.0
|
2019-10-05 05:14:13 +00:00
|
|
|
y += (h / 3.0) * f(a)
|
2019-07-10 20:09:24 +00:00
|
|
|
cnt = 2
|
|
|
|
for i in x_i:
|
2019-10-05 05:14:13 +00:00
|
|
|
y += (h / 3) * (4 - 2 * (cnt % 2)) * f(i)
|
2019-07-10 20:09:24 +00:00
|
|
|
cnt += 1
|
2019-10-05 05:14:13 +00:00
|
|
|
y += (h / 3.0) * f(b)
|
2019-07-10 20:09:24 +00:00
|
|
|
return y
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
|
|
|
def make_points(a, b, h):
|
2019-07-10 20:09:24 +00:00
|
|
|
x = a + h
|
2019-10-05 05:14:13 +00:00
|
|
|
while x < (b - h):
|
2019-07-10 20:09:24 +00:00
|
|
|
yield x
|
|
|
|
x = x + h
|
2018-10-19 12:48:28 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
|
|
|
def f(x): # enter your function here
|
|
|
|
y = (x - 0) * (x - 0)
|
2019-07-10 20:09:24 +00:00
|
|
|
return y
|
2018-10-19 12:48:28 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2018-10-19 12:48:28 +00:00
|
|
|
def main():
|
2019-10-05 05:14:13 +00:00
|
|
|
a = 0.0 # Lower bound of integration
|
|
|
|
b = 1.0 # Upper bound of integration
|
|
|
|
steps = 10.0 # define number of steps or resolution
|
|
|
|
boundary = [a, b] # define boundary of integration
|
2019-07-10 20:09:24 +00:00
|
|
|
y = method_2(boundary, steps)
|
2019-10-05 05:14:13 +00:00
|
|
|
print("y = {0}".format(y))
|
|
|
|
|
2018-10-19 12:48:28 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
if __name__ == "__main__":
|
|
|
|
main()
|