LoginSignup
1
0

More than 3 years have passed since last update.

[Python]浮動小数点数(float)の表現誤差を直すメソッド

Last updated at Posted at 2019-06-24

こんな風に、floatだと微妙に値がずれる事があります。

print(0.3)
# => 0.3

print(0.1 * 3)
# => 0.30000000000000004 

そこで、表現誤差を取り除くメソッドを作ってみました。
(小数点以下15桁になるように四捨五入しています。)

from decimal import Decimal, ROUND_HALF_UP

def remove_representation_error_in_float(x):
    x = Decimal(str(x)).quantize(Decimal('0.000000000000001'), rounding=ROUND_HALF_UP)
    x = float(str(x))
    return x

参考:Pythonで小数・整数を四捨五入するroundとDecimal.quantize | note.nkmk.me

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