LoginSignup
2
5

More than 5 years have passed since last update.

Python > 2つのfloat値の比較 > sys.float_info.epsilonを使う

Last updated at Posted at 2017-04-13

2つのfloat値が「ほぼ同じ値か」のチェックとして、CではFLT_EPSILONを使ってきた。
それと同等のものをPythonでは sys.float_info.epsilon を使うようだ。

参考 http://stackoverflow.com/questions/9528421/value-for-epsilon-in-python

試してみた。

import sys

def check_similarity(aval, bval):
    if abs(aval - bval) < sys.float_info.epsilon:
        print("similar")
    else:
        print("different")

aval = 3.141592653589797
bval = 3.141592653589796

check_similarity(aval, bval)

bval = 3.1415926535897971
check_similarity(aval, bval)
run
different
similar

http://stackoverflow.com/questions/9528421/value-for-epsilon-in-python
に記載の注意点としては

But don't forget the pitfalls of using it as an absolute error margin for floating point comparisons. E.g. for large numbers, rounding error could exceed epsilon.

2
5
1

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
5