# NaN comparisons - Call For Anecdotes

Ian Kelly ian.g.kelly at gmail.com
Wed Jul 9 19:26:26 CEST 2014

```On Wed, Jul 9, 2014 at 10:53 AM, Steven D'Aprano
> Cast your 64-bit float into a 64-bit int. Or, if it's a C single rather
> than a double, cast the 32-bit float into a 32-bit int. Now you can
> compare them for equality without carrying about NANs, and without losing
> data. Later, when you're ready to start doing some numeric work on them,
> you cast back to floats. That's the idea I had in mind. Perhaps it

Unfortunately, it's not that simple:

>>> import math, struct
>>> def float_to_int(x):
...   return struct.unpack('L', struct.pack('d', x))[0]
...
>>> 0.0 == -0.0
True
>>> float_to_int(0.0) == float_to_int(-0.0)
False
>>> nan1 = struct.unpack('d', b'\x00'*6+b'\xf1\x7f')[0]
>>> math.isnan(nan1)
True
>>> nan2 = struct.unpack('d', b'\x00'*6+b'\xf2\x7f')[0]
>>> math.isnan(nan2)
True
>>> float_to_int(nan1) == float_to_int(nan1)
True
>>> float_to_int(nan2) == float_to_int(nan2)
True
>>> float_to_int(nan1) == float_to_int(nan2)
False

```