Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Floor division with negative number

The expression 6 // 4 yields 1, where floor division produces the whole number after dividing a number.

But with a negative number, why does -6 // 4 return -2?

like image 971
Naz Islam Avatar asked May 17 '16 18:05

Naz Islam


People also ask

How do you do floor division with negative numbers?

That means that the result of such division is the floor of the result of regular division (performed with / operator). 7 / 2 = 3.5 so 7 // 2 = floor of 3.5 = 3. For negative numbers it is less intuitive: -7 / 2 = -3.5, so -7 // 2 = floor of -3.5 = -4 . Similarly -1 // 10 = floor of -0.1 = -1.

When using the floor division if the result is negative?

Floor Division with Negative Integer That is if a dividend is negative, and the divisor is a positive integer, then the quotient will be a negative integer. Hence the output will be rounded off to -4.

How does the floor function work with negative numbers?

The FLOOR. MATH function rounds a number down to the nearest integer or a multiple of specified significance, with negative numbers rounding toward or away from zero depending on the mode.

How does integer division work with negative numbers?

RULE 1: The quotient of a positive integer and a negative integer is negative. RULE 2: The quotient of two positive integers is positive. RULE 3: The quotient of two negative integers is positive. If the signs are different the answer is negative.


1 Answers

The // operator explicitly floors the result. Quoting the Binary arithmetic operations documentation:

the result is that of mathematical division with the ‘floor’ function applied to the result.

Flooring is not the same thing as rounding to 0; flooring always moves to the lower integer value. See the math.floor() function:

Return the floor of x, the largest integer less than or equal to x.

For -6 // 4, first the result of -6 / 4 is calculated, so -1.5. Flooring then moves to the lower integer value, so -2.

If you want to round towards zero instead, you'll have to do so explicitly; you could do this with the int() function on true division:

>>> int(-6 / 4)
-1

int() removes the decimal portion, so always rounds towards zero instead.

like image 194
Martijn Pieters Avatar answered Oct 25 '22 03:10

Martijn Pieters