2

I have written this program to calculate pi. It gives me 50 decimal places. How can I get more precision?

# pi.py - arctan(1) * 4 = pi
from math import *
from decimal import *

err = 0.0000000000000001

def arctan(n, err):
    """Uses Gregory's formula for calculating atan."""
    temp = n
    atan = 0
    i = 3
    while (abs(atan - n) > err):
        atan = n
        n = n - (pow(temp, i)/i) + ((pow(temp, i + 2)) / (i + 2))
        i += 4
    return n

def euler(a, b, err):
    """Uses Euler's formula and fibonacci numbers."""
    euler = 0
    temp = 5
    while (abs(temp - euler) > err):
        temp = euler
        euler += arctan(1/b, err)
        a = b + a
        b = b + a
    return euler


pi = euler(1, 2, err) * 4
print(Decimal.from_float(pi))
Jeffrey Bosboom
  • 13,313
  • 16
  • 79
  • 92
antiloquax
  • 27
  • 1
  • 7
  • 2
    Why are you doing all your calculations with 64 bit binary floats and *then* wrap up the result in a arbitrary-precision decimal float? That doesn't add any accuracy at all, you know... –  Oct 05 '12 at 13:10
  • Sorry, this is the first time I have tried writing something like this. – antiloquax Oct 05 '12 at 13:16

2 Answers2

4

You must set the Decimal prec to a higher value. See this example thread. The official python site has a lot more examples.

Also, you should make all your calculations using decimal, not just the last step. Otherwise you will not get the precision you need.

Community
  • 1
  • 1
Damian Schenkelman
  • 3,505
  • 1
  • 15
  • 19
0

Or look at mpmath, which supports arbitrary precision floats.

And, there are algorithms which will generate one digit of pi at a time, indefinitely (without exceedingly high precision requirements).

Gerry
  • 1,303
  • 1
  • 10
  • 16