Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active February 26, 2018 01:41
Show Gist options
  • Save komasaru/f546261c4e015459242cb175e7835c34 to your computer and use it in GitHub Desktop.
Save komasaru/f546261c4e015459242cb175e7835c34 to your computer and use it in GitHub Desktop.
Python script to compute definite integral by trapezoidal rule.
#! /usr/local/bin/python3.6
"""
Definite integral by by trapizoidal rule
"""
import math
import sys
import traceback
class DefiniteIntegralTrapezoid:
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) / self.M
x, s = a, 0
for k in range(1, self.M):
x += h
s += self.f(x)
s = h * ((self.f(a) + self.f(b)) / 2 + s)
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_trapezoid.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 = DefiniteIntegralTrapezoid()
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