Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python script to compute definite integral by simpson rule.
#! /usr/local/bin/python3.6
"""
Definite integral by by simpson rule
"""
import math
import sys
import traceback
class DefiniteIntegralSimpson:
M = 100 # Number of division
def __init__(self):
self.f = lambda x: math.sqrt(4 - x * x)
def compute(self, a, b):
"""
Computation of infinite intagral
"""
try:
h = (b - a) / (2 * self.M)
x, f_o, f_e = a, 0, 0
for k in range(1, 2 * self.M - 1):
x += h
if k % 2 == 1:
f_o += self.f(x)
else:
f_e += self.f(x)
s = self.f(a) + self.f(b)
s += 4 * (f_o + self.f(b - h)) + 2 * f_e
s *= h / 3.0
print(" / {:f}".format(b))
print(" | f(x)dx = {:f} ".format(s))
print(" / {:f}".format(a))
except Exception as e:
raise
if __name__ == '__main__':
if len(sys.argv) < 3:
print("USAGE: ./definite_integral_simpson.py A B")
sys.exit(0)
a, b = list(map(float, sys.argv[1:3]))
if a == 0 and b == 0:
sys.exit(0)
try:
obj = DefiniteIntegralSimpson()
obj.compute(a, b)
except Exception as e:
traceback.print_exc()
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment