16

I was working on a project to compute the Leibniz approximation for pi with the below code:

def pi(precision):
    sign = True
    ret = 0
    for i in range(1,precision+1):
        odd = 2 * i - 1
        if sign:
            ret += 1.0 / odd
        else:
            ret -= 1.0 / odd
        sign = not sign
    return ret

However, the output value was always was 12 digits long. How can I increase the precision (e.g. more digits) of the calculation? Does Python support more precise floating points, or will I have to use some external library?

hkk
  • 2,069
  • 1
  • 23
  • 48
  • What a strange value for pi: ``>>> repr(pi(17))`` yields ``'0.8000913788523872'`` – alko Jan 12 '14 at 19:37
  • 1
    @alko Yes, this approximates one fourth of pi. see here: http://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80 – hkk Jan 12 '14 at 19:38
  • What a strange method for pi evaluation, it converges **so slow**. – alko Jan 12 '14 at 19:40

4 Answers4

8

Try using Decimal.

Read Arbitrary-precision elementary mathematical functions (Python)original for more information

grooveplex
  • 2,492
  • 4
  • 28
  • 30
albusshin
  • 3,930
  • 3
  • 29
  • 57
6

Python's float type maps to whatever your platform's C compiler calls a double (see http://en.wikipedia.org/wiki/IEEE_floating_point_number).

The Python standard library also comes with an arbitrary-precision decimal module, called decimal: http://docs.python.org/2/library/decimal.html

Max Noel
  • 8,810
  • 1
  • 27
  • 35
4

The Leibniz formula converges extremely slowly - honestly, you won't live long enough for it get 12 digits of accuracy. Click here for one way to accelerate it enormously.

Community
  • 1
  • 1
Tim Peters
  • 67,464
  • 13
  • 126
  • 132
3

With Python's float, you get 15–17 digits of precision (if you are seeing fewer, you may need to use a different format specifier when printing).

If you need more, you'll need to use a different method (one that only uses integer arithmetic), or a different way to represent floating-point numbers.

See Python floating point arbitrary precision available?

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • 2
    12 is almost sertanly is raw print result, `float.__str__` trims up to 12 digits. – alko Jan 12 '14 at 19:38