Home > database >  Extreme floating point precision number 1.0-(0.1^200) in python
Extreme floating point precision number 1.0-(0.1^200) in python

Time:11-09

I was creating a threshold with extreme floating point precision. I am in need of a value something like 0.999999999... with 200 9s. Is that possible in python?

One solution I thought of was to create it using 1.-1e-200, but that just gives me the value 1.

CodePudding user response:

It is not possible with normal variables. Python uses the processor's double precision floating point numbers, which hold about 17 decimal digits.

There are add-on packages like bigfloat that can do arbitrary floating point arithmetic, but you'd need a pretty good reason to use them. Most people overestimate the need for precision in floating point math.

CodePudding user response:

The standard fractions.Fraction class provides unlimited-precision exact rational arithmetic.

>>> from fractions import Fraction
>>> x = Fraction(1) - Fraction(1, 10**200)

decimal.Decimal might also suit your needs if you're looking for high-precision rather than exact arithmetic, but you'll have to tweak the context settings to allow more than the default 28 significant digits.

>>> from decimal import Decimal, Context
>>> decimal.setcontext(Context(prec=1000))
>>> x = Decimal(1) - 1 / Decimal(10**200)
  • Related