Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer division: is a//b == int(a/b) true for all integers a,b?

I know that integer division will always return the same answer as truncation of a floating point result if the numbers are both positive. Is it true if one or both of them are negative?

I was just curious to know if there was an integer division expression that would return the same results in Python 2 and Python 3 (and yes, I know about from __future__ import division).

P.S. Let's ignore floating point overflow for the moment.

like image 287
Mark Ransom Avatar asked Oct 11 '12 15:10

Mark Ransom


People also ask

What is an integer in division?

Integer division is division in which the fractional part (remainder) is discarded is called integer division and is sometimes denoted .

What is the result of integer division?

The result of integer division is always an integer. Integer division determines how many times one integer goes into another. The remainder after integer division is simply dropped, no matter how big it is.

What is integer division in Python?

Integer division ( // ) The integer division operation // is used when you want your answer to be in whole numbers. Since it is very common for the result of dividing two integers to be a decimal value, in Python3 integers, division rounds the result to the lower bound.

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

It is not true in Python 3, and you can test it for yourself:

>>> int(-1/3) == -1//3
False

Integer division and modulo of a and b giving q (quotient) and r (remainder) respectively will always return numbers that satisfy b*q + r == a and (a*b)>0 == q>0 (i.e. a*b and q have the same sign) and abs(r) < abs(q). The expression int(q) simply always rounds towards 0 if q is a floating point number.

It will always be true for Python 2 unless you do from __future__ import division, but that's because a/b == a//b if a and b are integers in Python 2.

like image 146
Omnifarious Avatar answered Sep 19 '22 00:09

Omnifarious