LoginSignup
2
1

【小ネタ】「if a != a」をそっとしておいて

Last updated at Posted at 2024-03-19

Q. ソースコードに「if a != a」という条件分岐があった。このブロックを安易に削除してはいけないのはなぜか?

回答

aがNaNかどうかを判定しているから。


NaNはIEEE 754 で定められた特殊な値であり、Pythonではmath.nannumpy.nanなどがこれに該当します。

NaNはNaNを含むすべての値との比較演算==の結果がFalseになり、!===の結果の否定であるためTrueになります。

したがって、aがNaNのとき a != aTrueになり、分岐先のプログラムが実行されるのです。

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.

PEP 485 – A Function for testing approximate equality

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

NaN - Wikipedia

とは言え、if pandas.isna(a)if numpy.isnan(a)の方が意図が分かりやすいですね。もしif a != aと遭遇したらそっとしておきましょう。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1