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: Strange behavior of comparing int and float numbers
Type: behavior Stage: resolved
Components: Versions: Python 3.8
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: Petr Pisl, mrabarnett, steven.daprano
Priority: normal Keywords:

Created on 2020-01-23 17:56 by Petr Pisl, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (3)
msg360571 - (view) Author: Petr Pisl (Petr Pisl) Date: 2020-01-23 17:56
When python compares float and int created from the same int number should be equal like 

int(1) == float(1)

but from 9007199254740993 this is not true. 

int(9007199254740993) == float(9007199254740993) is not true. The same behavior is for bigger odd numbers. The even numbers are still equal. So it looks like:

int(9007199254740989) == float(9007199254740989) # True
int(9007199254740990) == float(9007199254740990) # True
int(9007199254740991) == float(9007199254740991) # True
int(9007199254740992) == float(9007199254740992) # True
int(9007199254740993) == float(9007199254740993) # False
int(9007199254740994) == float(9007199254740994) # True
int(9007199254740995) == float(9007199254740995) # False
int(9007199254740996) == float(9007199254740996) # True
int(9007199254740997) == float(9007199254740997) # False
int(9007199254740998) == float(9007199254740998) # True
msg360576 - (view) Author: Matthew Barnett (mrabarnett) * (Python triager) Date: 2020-01-23 18:42
Python floats have 53 bits of precision, so ints larger than 2**53 will lose their lower bits (assumed to be 0) when converted.
msg360579 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2020-01-23 20:34
Further to what Matthew said, this is not just a Python oddity. It applies to just about all programming languages, including C, C++, Java, Javascript, Ruby, etc. Some of them have even less precision by default.

Floats are not the same as the real numbers you learned about in school. There is a huge amount of resources about the limitations of floating point arithmetic on Stackoverflow etc which can be found by googling. A good place to start is the Python FAQs and tutorial:

https://docs.python.org/3/faq/design.html#why-are-floating-point-calculations-so-inaccurate

https://docs.python.org/3/tutorial/floatingpoint.html#tut-fp-issues
History
Date User Action Args
2022-04-11 14:59:25adminsetgithub: 83617
2020-01-23 20:34:50steven.dapranosetnosy: + steven.daprano
messages: + msg360579
2020-01-23 18:42:59mrabarnettsetstatus: open -> closed
stage: resolved
2020-01-23 18:42:48mrabarnettsetresolution: not a bug

messages: + msg360576
nosy: + mrabarnett
2020-01-23 17:56:35Petr Pislcreate