sandeeps sandeeps - 3 months ago 11
Python Question

Difference in long int division in python 3

I came across a bizarre situation while doing some large number division in python.

int(1012337203685477580 / 2) = 506168601842738816


and

int(1012337203685477580 >> 1) = 506168601842738790


Why is there a difference between the two approaches? int() appears to be at the least int64 because int(2^63 - 1) and 2^63 - 1 are the same values.

Answer

In Python 3, / is true division, so you will get a floating point result, and all the accuracy problems that entails. Use // for integer division instead:

>>> 1012337203685477580 / 2
5.061686018427388e+17
>>> 1012337203685477580 // 2
506168601842738790
>>> 1012337203685477580 >> 1
506168601842738790