Q. ソースコードに「if a != a」という条件分岐があった。このブロックを安易に削除してはいけないのはなぜか?
回答
aがNaNかどうかを判定しているから。
NaNはIEEE 754 で定められた特殊な値であり、Pythonではmath.nanやnumpy.nanなどがこれに該当します。
NaNはNaNを含むすべての値との比較演算==の結果がFalseになり、!=は==の結果の否定であるためTrueになります。
したがって、aがNaNのとき a != aはTrueになり、分岐先のプログラムが実行されるのです。
The IEEE 754 special values of NaN, inf, and -inf will be handled according to IEEE rules. Specifically, NaN is not considered close to any other value, including NaN.
Comparison between NaN and any floating-point value x (including NaN and ±∞)
Comparison NaN ≥ x NaN ≤ x NaN > x NaN < x NaN = x NaN ≠ x Result False False False False False True From these rules, comparing x with itself, x ≠ x or x = x, can be used to test whether x is NaN or non-NaN
とは言え、if pandas.isna(a)やif numpy.isnan(a)の方が意図が分かりやすいですね。もしif a != aと遭遇したらそっとしておきましょう。