I'm just reviewing some basics of Python and there's a tricky problem about comparing floating point numbers.
2.2 * 3.0 == 6.6
3.3 * 2.0 == 6.6
I thought these should both return a False. However, the second one gave me a True.
Please help me here. Thanks!
This might be illuminating:
>>> float.hex(2.2 * 3.0)
'0x1.a666666666667p+2'
>>> float.hex(3.3 * 2.0)
'0x1.a666666666666p+2'
>>> float.hex(6.6)
'0x1.a666666666666p+2'
Although they are all displayed in decimal as 6.6
, when you inspect the internal representation, two of them are represented in the same way, while one of them is not.
In order to complete Amadan's good answer, here is a more obvious way of seeing that 2.2*3. and 3.3*2. are not represented by the same float: in a Python shell,
>>> 2.2 * 3.
6.6000000000000005
>>> 3.3 * 2.
6.6
In fact, the Python shell displays the representation of numbers, which by definition should allow the corresponding float to be correctly built back from the representation, so you see the numerical approximation of 2.2*3 that Python does. The fact that 2.2*3. != 3.3*2. is obvious when seeing all the necessary digits, like above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With