LoginSignup
0
0

More than 3 years have passed since last update.

float型の数値は10進数の少数と同じではない

Last updated at Posted at 2020-07-15

Python学習のアウトプット。

mathモジュールには、.isclose()関数というものがある。
float型の数値を比較する際に用いる。それぞれが近似値かどうか。

>>> import math
>>> math.isclose(0.1+0.1+0.1, 0.3)
True

大前提として、Pythonを含めた計算機ハードウェアは浮動小数点数を正確に表すことができない。2進法の分数として表現されるため、例えば、2進法の分数

0.001

0/2 + 0/4 + 1/8

という値になる。

ただし、ほとんどの少数は2進法の分数として正確に表現できないため、近似値が記憶される。

float型の正確な値を取得するには、float.as_integer_ratio()メソッドを使う。xに0.3を代入し、このメソッドを使って正確な値を有理数として表現すると……

>>> x = 0.3
>>> x.as_integer_ratio()
(5404319552844595, 18014398509481984)
>>> x == 5404319552844595 / 18014398509481984
True
>>> 5404319552844595 / 18014398509481984
0.3

なんかすごい。

今度はxに0.1を代入し、3をかけてみる。すると、

>>> x = 0.1
>>> x.as_integer_ratio()
(3602879701896397, 36028797018963968)
>>> 3602879701896397 /  36028797018963968
0.1
>>> 3602879701896397 /  36028797018963968 * 3
0.30000000000000004

こう。限りなく0.3に近いんだけど、0.1 + 0.1 + 0.1 == 0.3の条件式は成立しない。

しかし、0.300000000000000040.3の近似値と言える。そのため、上記のように、

>>> import math
>>> math.isclose(0.1+0.1+0.1, 0.3)
True

.isclose()関数はTrueを返してくれる。

参考
Pythonの公式ドキュメント: 15. 浮動小数点演算、その問題と制限

0
0
2

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
0
0