Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

大きな数($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
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした