Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python floating point number comparison

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. enter image description here

Please help me here. Thanks!

like image 776
Zhiya Avatar asked Sep 29 '14 02:09

Zhiya


2 Answers

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.

like image 145
Amadan Avatar answered Nov 16 '22 23:11

Amadan


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.

like image 36
Eric O Lebigot Avatar answered Nov 17 '22 01:11

Eric O Lebigot