0

1/2 is actually 0 as expected in both languages since it's integer division.

One would expect the result to be 0 for -1/2 too. But it's -1! In other languages like Java, Scala or C++ it's 0 as it should be. What happens in Ruby and Python and why?

Machisuji
  • 738
  • 7
  • 16

2 Answers2

4

This is to preserve the identity that (x / y) * y + (x % y) == x for all integers x and y != 0; this is what it means for x % y to be the remainder when x is divided by y.

In Java, integer division rounds towards zero, but this means the remainder operator % can give negative results, and this is inconvenient for most purposes. For example, the expression arr[i % arr.length] doesn't guarantee a valid array index when i is negative.

In Python, if y is positive then x % y always gives a non-negative result (in the range from 0 to y - 1 inclusive), so to preserve the "remainder" property, integer division has to always round down, not necessarily towards zero.

kaya3
  • 47,440
  • 4
  • 68
  • 97
  • 1
    This is only true when using integer division, which in Python is accomplished with the `//` operator. In Python 2, `/` when used with two integer operands also performs integer division, but that usage is deprecated, and in Python 3 `/` uses floating point division when given two integers. – Tom Karzes Sep 11 '20 at 00:00
  • 1
    @TomKarzes Yes, the question is about integer division. – kaya3 Sep 11 '20 at 00:00
2

When doing integer math, it basically does a floor operation, or rounds down. So:

1/2 == 0.5 # rounds down to 0

But

-1/2 == -0.5 # which rounds down to -1

If you want the result to equal 0 you can run the following:

int(-1/2)
Dharman
  • 30,962
  • 25
  • 85
  • 135
artief
  • 21
  • 1