[ create a new paste ] login | about

Link: http://codepad.org/HCmovMEd    [ raw code | output | fork ]

Python, pasted on Jan 29:
"""
pi.py
Calculates an approximation of pi given the multiples 0pi - 1000pi using
the Pigeonhole Principle. Outputs the first approximation found.

Author: Louis Li
"""

import math


def main():
    # Store the decimals we've found in a dictionary with its multiple of pi
    d = dict()

    for n in xrange(0, 1001):
        n_pi = n * math.pi

        first_three_dec = int(math.floor((n_pi * 1000) % 1000))

        if not first_three_dec in d:
            d[first_three_dec] = n
        else:
            # Calculate an approximation, having found two numbers
            # with the same first three decimal places
            m = d[first_three_dec]
            m_pi = m * math.pi

            print int(round(n_pi - m_pi))
            print "----- = ", ((n_pi - m_pi) / (n - m)), \
                "(m = %d, n = %d)" % (m, n)
            print (n - m)
            print "\nActual value, pi: ", math.pi
            break

if __name__ == '__main__':
    main()


Output:
1
2
3
4
5
355
----- =  3.14159265359 (m = 1, n = 114)
113

Actual value, pi:  3.14159265359


Create a new paste based on this one


Comments: