# L-28 MCS 260 Wed 16 Mar 2016 : anytimepi.py

"""
An anytime algorithm is an algorithm that given
some more resources will improve the accuracy of
the computed estimate.
Recall the Monte Carlo method to estimate Pi.
The user can monitor the progress of the
computations via handling of cntrl+c interrupt.
"""

from math import pi
from random import uniform as u

print('approximating pi = %.14f' % pi)
print('hold ctrl and c to check...')
(COUNT, TOTAL) = (0, 0)
while True:
    try:
        while True:
            TOTAL += 1
            (X, Y) = (u(0, 1), u(0, 1))
            if X**2 + Y**2 <= 1:
                COUNT += 1
    except KeyboardInterrupt:
        APPROX = (4.0*COUNT)/TOTAL
        print('#samples : %d, estimate : %.14f' % (TOTAL, APPROX))
        ANS = input('continue ? (y/n) ')
        if ANS != 'y':
            break
