Search code examples
pythonfloating-point-precisionpi

Python: Float infinite length (Precision float)


My code:

def calc_pi(acc):
     pos = False
     sum = 4.0
     for i in range(2, acc):
          if not pos:
               sum -= 4.0/(2*i-1)
               pos = True
          else:
               sum += 4.0/(2*i-1)
               pos = False
     return float(sum)

print(calc_pi(5000))

And of course, I'm trying to calculate a pi, with more than 10 after-point-digits. But Python seems to round to 10. Is there a simple way, to prevent it from doing this? Like a million after-point-digits?

Thank you!


Solution

  • You can use the Decimal class provided by the standard library.

    From the docs:

    Unlike hardware based binary floating point, the decimal module has a user alterable precision (defaulting to 28 places) which can be as large as needed for a given problem:

      >>> from decimal import *
      >>> getcontext().prec = 6
      >>> Decimal(1) / Decimal(7)
      Decimal('0.142857')
      >>> getcontext().prec = 28
      >>> Decimal(1) / Decimal(7)
      Decimal('0.1428571428571428571428571429')