Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negative integer division surprising result

In my application I encountered the following and was surprised by the results:

8/-7=-2 (both integers).

What does this mean?

like image 350
Vivek S Avatar asked Apr 04 '11 06:04

Vivek S


People also ask

What happens when a negative integer is divided?

Rule 3: a negative number divided by a negative number equals a positive number. Two negatives make a positive, so a negative number divided by a negative number equals a positive number. For example, -8 / -2 = 4.

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.

When using the floor division operator if the result is negative then the result is rounded off to the next largest integer True or false?

Floor division always rounds away from zero for negative numbers, so -3.5 will round to -4 , but towards zero for positive numbers, so 3.5 will round to 3 .

What is the result of division and remainder for negative integers?

The rule is: Perform the operation as if both operands were positive. If the left operand is negative, then make the result negative.


2 Answers

For the actual values, i.e. 8.0/(-7.0), the result is roughly -1.143.

Your result using integer division is being rounded down toward the more negative value of -2. (This is also known as "Floor division")

This is why you will get the somewhat perplexing answers of:

>>> 8/(-7) -2 >>> 8/7 1 

Note: This is "fixed" in Python 3, where the result of 8/(-7) would be -1.143. So if you have no reason to be using Python 2, you should upgrade. ;)

In Python 3, if you still want integer division, you can use the // operator. This will give you the same answer as 8/(-7) would in Python 2.

Here's a Python Enhancement Proposal on the subject: PEP 238 -- Changing the Division Operator

like image 77
Chris Cooper Avatar answered Sep 22 '22 17:09

Chris Cooper


Python always does the "floor division" for both negative numbers division and positive numbers division.

That is

1/10 = 0 1/-10 = -1 

But sometime we need 1/-10 to be 0

I figure out it can be done by using the float division first then cast result to int, e.g.

int(float(1)/-10) = 0 

That works fine for me, no need to import the future division or upgrade to Python 3

Hope it can help you~

like image 33
ZH.Jay Avatar answered Sep 24 '22 17:09

ZH.Jay