Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

@cocet33000

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

大きな数($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
0
Help us understand the problem. What are the problem?