
# trapezoid.py
''' 
  Integral of f(x) from x = a to b computed 
  using the trapezoid rule with n points.
'''

import math

def f(x): 
  return math.sin(x)


def trapezoid(f, a, b, n=500):
  print("Range:", a, "to", b, "with", n, "points")
  h =(b - a)/n
  tot = 0.5 *(f(a) + f(b))
  for i in range(1,n):
    x = a + i*h
    tot += f(x)
  return tot*h


if __name__ == "__main__":
  print("Integrate f(x) = sin(x)")
  print(trapezoid(f, 0, math.pi, 20))  # = 2
  print(trapezoid(f, 0, math.pi, 50))
  print(trapezoid(f, 0, math.pi, 1000))
  
