This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Floating Point Arithmetic Inconsistency (internal off-by-one)
Type: Stage: resolved
Components: Versions: Python 3.6
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: ddg, tim.peters
Priority: normal Keywords:

Created on 2018-03-08 03:25 by ddg, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (2)
msg313420 - (view) Author: Dylan Dmitri Gray (ddg) Date: 2018-03-08 03:25
```
>>> for i in (1,2,3,1.0,2.0,3.0): print(i, i+9007199254740991)
...
1 9007199254740992
2 9007199254740993
3 9007199254740994
1.0 9007199254740992.0
2.0 9007199254740992.0   # <-- !!!
3.0 9007199254740994.0

```

Notably 9007199254740991 = 2**53 -1

Probably an internal off by one?
msg313421 - (view) Author: Tim Peters (tim.peters) * (Python committer) Date: 2018-03-08 03:47
What did you expect?  The precision of Python ints is limited only by the amount of memory you have, but Python floats are IEEE-754 double precision numbers, and have only 53 bits of precision.

2**53 + 1 simply can't be represented exactly as a float:  it requires 54 significant bits.  It must be rounded back to 53 significant bits.  Because the exact value of 2**53 + 1 is exactly half-way between the adjacent representable floats 2**53 and 2**53+2, the IEEE "round to nearest/even" rule requires rounding to the closest representable value whose 53rd (the least) significant bit is 0, which is 2**53.

Note that the 53rd bit of 9007199254740994.0 (2**53 + 2) is odd (1):

>>> (9007199254740994.0).hex()
'0x1.0000000000001p+53'
                 ^

That's why the nearest/even rule _must_ pick 2**53 instead.

You'll see the same behavior in every other language (C, C++, Java, ...) supporting IEEE-754 double precision too.

Since this really has nothing to do with Python, and is working as intended, I'll close this.
History
Date User Action Args
2022-04-11 14:58:58adminsetgithub: 77203
2018-03-08 03:47:26tim.peterssetstatus: open -> closed

nosy: + tim.peters
messages: + msg313421

resolution: not a bug
stage: resolved
2018-03-08 03:25:22ddgcreate