# Educational example from Sarovi journal. Python 3; no extra dependencies.
def trapezoid(f, a, b, n):
    if n <= 0:
        raise ValueError("n must be positive")
    h = (b - a) / n
    total = (f(a) + f(b)) / 2
    total += sum(f(a + i * h) for i in range(1, n))
    return total * h

for n in [10, 100, 1000]:
    print(n, trapezoid(lambda x: x*x, 0, 2, n))

assert abs(trapezoid(lambda x: x*x, 0, 2, 1000) - 8/3) < 2e-6
