Search code examples
pythonfloating-pointfloating-point-precision

How do I get Python to display more than 50 decimal places?


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))

Solution

  • 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.