+ 1

Python comparisons and error

When comparing, say, an integer and a float, is the result guarunteed to be correct? For example, take the comparison 8 < 8.0. My understanding is that the integer 8 is casted to 8.0. One would expect the result to be False, but is it possible for this comparison to result in True if the values are stored in memory as, say, 8.000000...0 and 8.000000...1?

15th Jun 2017, 1:57 PM
Bethann Polinsky
Bethann Polinsky - avatar
1 Odpowiedź
+ 3
Normally, if you input two identical numbers, one as an int, and the other as a float, they will be equal. But if you try applying some arithmetic calculations to them, or convert one into the other, some differences may appear. This is because floats in Python are represented in base two (binary) fractions, rather than decimals. Since not every number can be represented in a x/2 fraction the same way as in a x/10 fraction, those differences appear. They are usually too small to notice, but a boolean comparing such a number with an int will return false. An example of that is the popular question in the challenges, when you are asked whether 9**19 is equal to int(9.0**19) (it is not). For more info on this, please refer to the following page: https://docs.python.org/3/tutorial/floatingpoint.html
18th Jun 2017, 7:27 AM
Agnius Bartninkas
Agnius Bartninkas - avatar