0
1

python3のroundは銀行丸め(にハマったのでメモ)

Posted at

pythonのroundは銀行丸めpythonのroundは銀行丸め
pythonのroundは銀行丸めpythonのroundは銀行丸め
pythonのroundは銀行丸めpythonのroundは銀行丸め

pythonのroundは銀行丸めなんだったら!!
ヨシッ覚えた(たぶん半年後ぐらいにまたハマる)
半日無駄にしたからな、次から同じミスはしない。

pythonとrubyで同じコード書いたはずなに何故か同じ結果にならず調べたら四捨五入するroundの挙動が違っていました。
分かりやすくするために小規模テスト。

test.py
test = 0.5000000
for ii in range(10) :
        temp = test + ii
        print(round(temp),"{:.30f}".format(temp) )

この実行結果は下記のようにX.5の時に偶数側に丸められます
銀行丸めとかなんか金額の平均計算したり合計したりするときに誤差が少なくなる丸めかたたらしいです

0 0.500000000000000000000000000000
2 1.500000000000000000000000000000
2 2.500000000000000000000000000000
4 3.500000000000000000000000000000
4 4.500000000000000000000000000000
6 5.500000000000000000000000000000
6 6.500000000000000000000000000000
8 7.500000000000000000000000000000
8 8.500000000000000000000000000000
10 9.500000000000000000000000000000

対策は色々ありますが今回は簡単な関数を自力で作ってみました。
通常の四捨五入の実装(なんていうの?)

python3 mround.py
def mround(num) :
        shou = int(num // 1 )
        amari = num % 1
        if amari >= 0.5 :
                return shou + 1
        else :
                return shou
#enddef mround
test = 0.25000000

for ii in range(15) :
        temp = test + ( ii * 0.25 )
        print(mround(temp),round(temp),"{:.30f}".format(temp) )

大きいほうに切り上げられること確認!
0.5だけだとテストケース少なくね?
ということで0.25刻みでチェック
ヨシッ

0 0 0.250000000000000000000000000000
1 0 0.500000000000000000000000000000
1 1 0.750000000000000000000000000000
1 1 1.000000000000000000000000000000
1 1 1.250000000000000000000000000000
2 2 1.500000000000000000000000000000
2 2 1.750000000000000000000000000000
2 2 2.000000000000000000000000000000
2 2 2.250000000000000000000000000000
3 2 2.500000000000000000000000000000
3 3 2.750000000000000000000000000000
3 3 3.000000000000000000000000000000
3 3 3.250000000000000000000000000000
4 4 3.500000000000000000000000000000
4 4 3.750000000000000000000000000000
0
1
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
0
1