Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 563
d0n.key Avatar asked Jul 04 '15 20:07

d0n.key


People also ask

Do Python floats have infinite precision?

Note: These examples were originally created for Python 2. X. With Python 3. x, all the integer variables are of "infinite" precision and the floats are always double precision.

How precise are Python floats?

Double precision numbers have 53 bits (16 digits) of precision and regular floats have 24 bits (8 digits) of precision. The floating point type in Python uses double precision to store the values.

Is Python float 32 or 64?

Python's floating-point numbers are usually 64-bit floating-point numbers, nearly equivalent to np.

Why do we use float (' inf ') in Python?

Representing infinity as an Integer in python But in python, as it is a dynamic language, float values can be used to represent an infinite integer. One can use float('inf') as an integer to represent it as infinity.


1 Answers

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')
like image 191
musically_ut Avatar answered Sep 29 '22 19:09

musically_ut