Python Hax: True Division vs Floor Division

I have been recently doing an algorithms course via Python 3 and I was doing what I thought was a simple division.

I was trying to do 231871064940156750 / 5. When I did it in Python I would get 
46374212988031352. But it would then fail tests telling me the answer should be 46374212988031350.

At first, I thought maybe it was a bit error and that the number wasn’t being stored correctly. But after reading the docs for int in Python 3, there doesn’t seem to be any limit to int vs long like there was in Python 2.

I then thought maybe converting the result from scientific notation to int was causing a rounding error somewhere along the line.

It turns out that I can fix this problem by dividing with the // operator rather than the / operator. Take a look at the code below!

# Floating Point Division
231871064940156750 / 5
# => 4.637421298803135e+16
# Turn the result into a integer
# => 46374212988031352
# Floor Division
231871064940156750 // 5
# => 46374212988031350

In Python 3, all division returns as a float, not an integer (unlike Python 2, Ruby 2 or JavaScript).

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s