4

I am trying to determine how precise python floats are when comparing to zero. Observe the following:

1e-323 == 0
> False
1e-324 == 0
> True

I appears the threshold is 324 decimal points, at least with the implementation I am running (python 2.7, CPython). Is this documented anywhere? Is it implementation dependent?

C_Z_
  • 7,427
  • 5
  • 44
  • 81
  • I don't think you can trust that threshold to always hold, even limited to your own environment. For instance, consider that `1e100 == 1e100 + 1`. This implies that especially large floats don't have even a single digit of precision after the decimal point. – Kevin Aug 28 '18 at 18:21
  • 1
    math.isclose() may also be helpful: https://stackoverflow.com/a/33024979/3841261 – Chad Kennedy Aug 28 '18 at 18:27

1 Answers1

9

It is implementation-specific:

numbers.Real (float)

These represent machine-level double precision floating point numbers. You are at the mercy of the underlying machine architecture (and C or Java implementation) for the accepted range and handling of overflow. Python does not support single-precision floating point numbers; the savings in processor and memory usage that are usually the reason for using these are dwarfed by the overhead of using objects in Python, so there is no reason to complicate the language with two kinds of floating point numbers.

You can, however, query this information at run time:

>>> sys.float_info
sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)
chepner
  • 497,756
  • 71
  • 530
  • 681
  • 1
    Look at the docs for `sys.float_info`. That exposes various info about the specific implementation. However, on almost all platforms it exposes the same info, because almost all platforms support IEEE 754 doubles now. – Tim Peters Aug 28 '18 at 18:20