LoginSignup
1
0

More than 3 years have passed since last update.

python3の除算は型に注意 A//B != int(A/B)

Last updated at Posted at 2019-08-24

大きな数($10^9$程度)の割り算で、以下のような罠にハマったので解説します。

A//B != int(A/B)

問題点

Python3では/演算子を使用した場合、floatに変換して除算が行われます。
そのため、以下のコードを実行すると問題が生じます。

a = 123
b = 456

A = 10**9 + 123
B = 10**9 + 456

c = a*b/2
d = a*b//2

C = A*B/2
D = A*B//2

print("a*b/2       =",c)
print("int(a*b/2)  =",int(c))
print("a*b//2      =",d)

print("A*B/2       =",C)
print("int(A*B/2)  =",int(C))
print("A*B//2      =",D)

結果は以下の通り、a,bが小さいときには問題ありませんが、A,Bが大きいと結果が一致しません。

a*b/2       = 28044.0
int(a*b/2)  = 28044
a*b//2      = 28044
A*B/2       = 5.00000289500028e+17
int(A*B/2)  = 500000289500028032
A*B//2      = 500000289500028044

原因

python3ではint型は無限の桁数を持つのに対して、float型は有限です、そのため/演算子によりA*Bfloat型で実行され、大きい数字の場合には以下の様な結果となってしまうのです。お気をつけあれ。

A = 10**9 + 123
B = 10**9 + 456

c = (A*B)
d = float(A*B)

if c != d:
    print("一致しません")
    print("c", c)
    print("d", d)

結果

一致しません
c 1000000579000056088
d 1.000000579000056e+18
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