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 = '+'
    else:
        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...

Recommended Answers

All 2 Replies

This page Click Here contains many formulas. I suggest to start with Ramanujan's formula.

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(pi_decimal(precision))
print("compare with published pi")
print("3.14159265358979323846264338327950288419716939937510582097494")

'''result ...
pi calculated to a precision of 60
3.14159265358979323846264338327950288419716939937510582097494
compare with published pi
3.14159265358979323846264338327950288419716939937510582097494
'''
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.