Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.