0

If I run python on my terminal and type this, and hit enter:

-1 / 2

It returns

-1

If I do the same in XCode, compiling C++ code, and I have this:

int idx = -1 / 2;
cout << idx << endl;

It prints this:

0

Why are these rounding differently?

EDIT :forgot to mention that 'int' is an integer type (int). This is corrected.

Shaun Budhram
  • 3,690
  • 4
  • 30
  • 41

3 Answers3

3

In Python integer division has always rounded downwards, as if you used the floor function.

In C++03 the rounding direction was left to the compiler.

In C++11 and later it is required to be towards zero.


As I see it, the C++ rounding direction is more easy to understand for novices, since it gives the same kind of numerical result that you would calculate by hand. It also corresponds to how most computers implement integer division, i.e. is efficient at the level of individual operations. The Python rounding direction, on the other hand, is mathematically more elegant and more practically useful in programming.


One practical difference, illustrating the Pythonic elegance, is to compute how many cabs with capacity of 3 passengers you need for a party of 10 persons. In Python, -(-10//3). In C++, (10 + (3-1))/3.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
0

Because that's how integer division specified in those languages (downwards vs. zerowards).

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • Not sure for Python, but according to eg. http://stackoverflow.com/questions/5535206/python-negative-integer-division-surprising-result, this is more like a bug in older versions. And for C++, it depends. Eg. IEEE754 has multiple rounding variants – deviantfan Feb 28 '15 at 20:25
  • 1
    @deviantfan, C++11 specifies it as toward zero. Older versions seem to only recommend that. – chris Feb 28 '15 at 20:27
  • @deviantfan: Integer division is not a bug, nor the division operator performing integer division when both operands are integers. – Ignacio Vazquez-Abrams Feb 28 '15 at 20:27
  • @IgnacioVazquez-Abrams I don´t mean integer division in general, but that it goes down for negative results has apparently changed since Python 3 – deviantfan Feb 28 '15 at 20:28
  • @deviantfan: `3>> -1 // 2` `-1` – Ignacio Vazquez-Abrams Feb 28 '15 at 20:29
0

Python will round any division between integers downwards (i.e. the smallest of the two integers between the real decimal value). If the result is 2.6, it will round to 2, and if it's -2.6 it will round to -3.

C++ will round towards zero (whether the result is positive or negative). So if the result is 2.6 it will be rounded to 2, and if it's -2.6 it will be rounded to -2.

wyas
  • 377
  • 2
  • 14