消えた「細かすぎて伝わりにくい、Pythonの本当の落とし穴10選」# Extra Stage! (2017-06-16)
で紹介されているisclose()が便利そう。
Python 3.5から mathモジュールに isclose() という関数が入ったので、気になる折には使用を検討しよう。
関連して以下を見つけた。
Using math.isclose function with values close to 0 @ stackoverflow
0に近い値を比較する場合にはabs_tolを設定するように、とのこと。
試してみた。
import math
res = math.isclose(0.2 + 0.4, 0.6)
print(res)
res = math.isclose(0.2 + 0.4 - 0.6, 0.0)
print(res)
res = math.isclose(0.2 + 0.4 - 0.6, 0.0, abs_tol=1e-9)
print(res)
run
True
False
True
検索用キーワード
(追記 2018/01/13)
- sys.float_info.epsilon