Recently I've been fooling around with some fun mathmatic (dont knwo if that is even a word) stuff. I recently took on the task of trying to calcualte PI.

I have a very simple program in python that does this for me:

import math
from datetime import datetime

top = 4
bot = 1
pi = 0
op = '+'

starttime = datetime.now()
for x in range(1000000000):
    if op == '-':
        pi = pi - (top / bot)
        op = '+'
        pi = pi + (top / bot)
        op = '-'
    bot = bot + 2

timefinish = datetime.now()
print("Time it took to calculate: ", timefinish - starttime)
print("{0}   |   {1}".format(math.pi, pi))

Like I said, very simple.
My computer gave the folowing results:
Time: 0:04:35.069303
My PI value = 3.1415926525880504
Real PI value = 3.141592653589793

As we can see this is a rather lengthy task. At the moment my PI is also not too acurate. It is only accurate to 11 decimal digit. The accuracy of my PI is increased if I increase the amount of times the loop executes.
(I think I might need to go and get my IBM BLUEGENE if I want to calculate PI to 1 000 000 decimal digits.)

Do you guys know of any more efficient / accurate ways that I can calculate PI?
Feel free to post your own improved methods etc...

Edited by MasterHacker110

2 Years
Discussion Span
Last Post by sneekula

Looks like you use the Gregory–Leibniz series which converges rather slowly.
A much faster series is given in the Python manual under the decimal module recipes:

import decimal

def pi_decimal(prec):
    compute Pi to the current precision
    # increase precision for intermediate steps
    decimal.getcontext().prec = prec + 2
    D = decimal.Decimal
    # make starting assignments
    lasts, t, s, n, na, d, da = D(0), D(3), D(3), D(1), D(0), D(0), D(24)
    while s != lasts:
        lasts = s
        n, na = n+na, na+8
        d, da = d+da, da+32
        t = (t * n) / d
        s += t
    # reset to original precision
    decimal.getcontext().prec -= 2
    # unary plus applies the reset precision
    return +s

precision = 60
print("pi calculated to a precision of {}".format(precision))
print("compare with published pi")

'''result ...
pi calculated to a precision of 60
compare with published pi
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.