# NaN comparisons - Call For Anecdotes

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Jul 8 20:10:27 CEST 2014

```On Tue, 08 Jul 2014 19:16:53 +0300, Marko Rauhamaa wrote:

> Chris Angelico <rosuav at gmail.com>:
>
>> Why *should* all NaNs be equal to each other?
>
> I appreciate why you can't say NaN is equal to NaN. However, shouldn't
> the very comparison attempt trigger an arithmetic exception?

No. Why should it? It's not an error to check whether two things are
equal.

> After all, so does a division by zero.

Um, yes, and multiplying by zero isn't an error. In what way is x == y
related to x/0 ?

But having said that, sometimes it is useful to stop processing as soon
as you reach a NAN. For that, IEEE-754 defines two kinds of NANs, Quiet
NANs and Signalling NANs. Quiet NANs don't trigger a signal when you
perform operations on them. (By default -- I believe you can enable
signals if you wish.) Signalling NANs always trigger a signal, including
when you check them for equality:

py> from decimal import Decimal as D
py> a = D('nan')
py> b = D('snan')
py> 1 == a
False
py> 1 == b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]

But by default, NANs are quiet. The C99 standard doesn't support
signalling NANs, and Java actually prohibits them.

Aside: The influence of C and Java has crippled IEEE-754 support across
almost all languages and hardware. It's a crying shame the pernicious
influence those two languages have had.

http://grouper.ieee.org/groups/1788/email/pdfmPSi1DgZZf.pdf

Floating point is *hard*, and people who don't understand it insist on
telling those who do that "you don't need that feature" :-(

--
Steven

```