antiloquax
antiloquax

Reputation: 47

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

Upvotes: 2

Views: 10296

Answers (2)

Gerry
Gerry

Reputation: 1323

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

Upvotes: 0

Damian Schenkelman
Damian Schenkelman

Reputation: 3535

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.

Upvotes: 4

Related Questions