LoginSignup
9
5

More than 5 years have passed since last update.

Python 3.5 > math > isclose() > 0.0に近い値との比較での落とし穴

Last updated at Posted at 2017-07-24

消えた「細かすぎて伝わりにくい、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
9
5
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
9
5