# L-15 MCS 507 Mon 25 Sep 2023 : integral4pi.py

"""
This script applies the composite trapezoidal rule
to the integral of sqrt(1-x^2) for x from 0 to 1,
to obtain an approximation for pi.
This inefficient computational expensive method
gives us an example to optimize with cython.
"""

from math import sqrt # do not import in circle !!!

def circle(xvl):
    """
    Returns the y corresponding to xvl
    on the upper half of the unit circle.
    """
    return sqrt(1-xvl**2)

def integral4pi(nbvals):
    """
    Approximates Pi with the trapezoidal
    rule with nbvals subintervals of [0,1].
    """
    step = 1.0/nbvals
    result = (circle(0)+circle(1))/2
    for i in range(nbvals):
        result += circle(i*step)
    return 4*result*step

def main():
    """
    Does the timing of integral4pi.
    """
    from time import perf_counter
    start_time = perf_counter()
    approx = integral4pi(10**8)
    stop_time = perf_counter()
    print('pi =', approx)
    elapsed = stop_time - start_time
    print('elapsed time = %.3f seconds' % elapsed)

main()
