2

I just find this a bit strange tbh. Environment is Python v3 and while it looks fine to me for the expression

import numpy as np
np.nan==np.nan

to return False when used in a tuple:

(np.nan,)==(np.nan,)

it returns True

Aenaon
  • 3,169
  • 4
  • 32
  • 60
  • 1
    Because. Tuple equality is processed different from nan-equality? beside that - you might want to use `np.isnan(np.nan)` - which would lead to True - so maybe Tuple uses the correct NaN detection ... just a guess though – Patrick Artner Nov 17 '19 at 11:09
  • Well, I dont think it is a duplicate. Thats about tuples not lists – Aenaon Nov 17 '19 at 11:22
  • While both membership test and tuple equality checked identity, that doesn't make those questions the same. – Yann Vernier Nov 17 '19 at 11:32

1 Answers1

2

As mentioned in the numpy documentation:

np.nan == np.nan # is always False! Use special numpy functions instead.

I assume that upon comparing tuples, values are being checked one after another, but check behind the scene is different than explicit comparison, especially for == check.

For instance, check occurs by comparing id(elem) values, which must be the same for two different numpy.nan, therefore it returns true. Also, most likely, on the non cpython implementations the result may be false to, due to internal optimizations for storing values of variables.

Additionaly, you may checkout magic implementation of numpy.nan which may give you more glue of what is going on behind the scene on comparison action.

Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82
  • Correct, per [value comparisons](https://docs.python.org/3/reference/expressions.html#value-comparisons) "The built-in containers typically assume identical objects are equal to themselves." Therefore, the `nan`-specific inequality was never tested. Also, `array.array('f', [math.nan])` compares unequal to itself. – Yann Vernier Nov 17 '19 at 11:28