2014-11-29 26 views
6

Si consideri il seguente script:NaNs confronto uguali in Numpy

import numpy as np 

a = np.array([np.nan], dtype=float) 
b = np.array([np.nan], dtype=float) 
print a == b 

a = np.array([np.nan], dtype=object) 
b = np.array([np.nan], dtype=object) 
print a == b 

Sulla mia macchina Questo stampa

[False] 
[ True] 

Il primo caso è chiaro (as per IEEE-754), ma quello che sta succedendo nel secondo caso ? Perché i due NaNs sono paragonabili?

Python 2.7.3, Numpy 1.6.1 su Darwin.

+1

Nel secondo caso, tutti Nan-oggetti sono uguali. – Daniel

+2

@Daniel: Empiricamente, questo è quello che sembra accadere, ma: (1) qual è il motivo della violazione di IEEE-754? (2) questo è documentato da qualche parte? – NPE

+0

Una semplice possibilità è che questo è ciò che 'list' fa:' x = [numpy.nan]; x == x # >>> Vero'. – Veedrac

risposta

7

sulle versioni più recenti di NumPy si riceve questo avviso:

FutureWarning: numpy equal will not check object identity in the future. The comparison did not return the same result as suggested by the identity (`is`)) and will change. 

mia ipotesi è che NumPy sta usando id test come una scorciatoia, per object tipi per poi scendere a __eq__ prova, e dal momento che

>>> id(np.nan) == id(np.nan) 
True 

restituisce vero.

se si utilizza float('nan') anziché np.nan il risultato sarebbe diverso:

>>> a = np.array([np.nan], dtype=object) 
>>> b = np.array([float('nan')], dtype=object) 
>>> a == b 
array([False], dtype=bool) 
>>> id(np.nan) == id(float('nan')) 
False 
+0

Mi piace l'ipotesi, grazie. Suppongo che non sarebbe irragionevole caratterizzare il comportamento come un bug. – NPE

+0

Il tuo esempio è errato: 'id (4.5) == id (float ('4.5'))' è anche 'False'. – Daniel

Problemi correlati