LoginSignup
1
2

More than 1 year has passed since last update.

pythonの浮動小数点について(備忘録)

Last updated at Posted at 2022-12-04

pythonの浮動小数点は、不正確!?

>>> 0.3
0.3
>>> 0.1 + 0.1 + 0.1
0.30000000000000004
>>> 0.3 == (0.1 + 0.1 + 0.1) 
False

合計が違うのは、コンピュータが浮動小数点を表現する処理の際に、「丸め誤差が生じるから」IEEE 754規格のCPUを採用している場合は、python以外でも同じ結果になるらしい…
⇒IEEEは、2**53以上の整数値を表現できない

>>> float(2**53) == float(2**53) + 1  
True

より正確に計算をしたい場合は、「組み込みモジュールdecimal」を使おう!

浮動小数点のまま(不正確なまま)、decimal.Decimal()に引数として渡しても意味がない!

>>> import decimal                     
>>> x = decimal.Decimal(0.1) 
>>> x              
Decimal('0.1000000000000000055511151231257827021181583404541015625')       
>>> x + x + x
Decimal('0.3000000000000000166533453694')

decimal.Decimal()に文字列として与えよう!

>>> x = decimal.Decimal('0.1') 
>>> x
Decimal('0.1')
>>> x + x + x      
Decimal('0.3')

整数には丸め誤差がないので正確に渡すことができる。

decimalの精度レベルについて

decimal.getcontext().precを使ってdecimalの有効数字を確認(デフォルトでは、28桁)

>>> import decimal 
>>> decimal.getcontext().prec
28

decimal.Decimal().precに値を与えることで、有効数字を設定する

>>> import decimal
>>> decimal.getcontext().prec = 4
>>> decimal.getcontext().prec
4
>>> decimal.Decimal(1) / 3 
Decimal('0.3333')
1
2
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
1
2