Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in long int division in python 3 [duplicate]

Tags:

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.

like image 326
sandeeps Avatar asked Sep 10 '16 04:09

sandeeps


People also ask

What is the difference between '/' and in Python?

Answer: '/' is the division operator. '//' is the floor division operator.

Does Python 3 do integer division?

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.

What is the difference between division and integer division Python?

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).

What happens when you do integer division in Python?

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.


1 Answers

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
like image 137
lazy dog Avatar answered Oct 14 '22 02:10

lazy dog