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: '/' is the division operator. '//' is the floor division operator.
In Python 3. x, slash operator ("/") does true division for all types including integers, and therefore, e.g. 3/2==1.5. The result is of a floating-point type even if both inputs are integers: 4 / 2 yields 2.0.
The division function in Python has two variations: Float division: gives a decimal answer. Integer division: gives the answer in whole numbers (the division result is rounded to the nearest whole number).
In Python, there are two kinds of division: integer division and float division. Integer division returns the floor of the division. That is, the values after the decimal point are discarded. It is written as '//' in Python 3.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With