Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

python - Strange error in python3 when doing big int calculation

I was trying to do this in Python 3.5.2:

int(204221389795918291262976/10000)

but got the unexpected result: 20422138979591827456

It's working fine in Python 2.7.12, result is: 20422138979591829126L

Any idea why Python 3 gave me the wrong result?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In python 3 you have to use integer division // explicitly or else float division will apply even between 2 integers.

That's one of the major changes between python 2 and python 3

In your example: (will work both in python 2 and python 3 so it's backwards compatible!)

204221389795918291262976//10000
20422138979591829126

(you don't even need to convert to int here, result is int since both terms are int)

BTW if you want to make this bug work with python 2 it is also possible :)

from __future__ import division

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...