Why is -1/2 evaluated to 0 in C++, but -1 in Python?

  • C++: cout << -1/2 evaluates to 0
  • Python: -1/2 evaluates to -1.

Why is this the case?


Integer division in C++ rounds toward 0, and in Python, it rounds toward -infinity.

People dealing with these things in the abstract tend to feel that rounding toward negative infinity makes more sense (that means it's compatible with the modulo function as defined in mathematics, rather than % having a somewhat funny meaning). The tradition in programming languages is to round toward 0--this wasn't originally defined in C++ (following C's example at the time), but eventually C++ (and C) defined it this way, copying Fortran.


From the Python docs (emphasis mine):

The / (division) and // (floor division) operators yield the quotient of their arguments. The numeric arguments are first converted to a common type. Plain or long integer division yields an integer of the same type; the result is that of mathematical division with the ‘floor’ function applied to the result.

The floor function rounds to the number closest to negative infinity, hence -1.


For C++, from this reference: 5.2 — Arithmetic operators

It is easiest to think of the division operator as having two different “modes”. If both of the operands are integers, the division operator performs integer division. Integer division drops any fractions and returns an integer value.

Thus, -1/2 would yield -0.5 with the fraction dropped, yielding 0.

As SethMMorton indicated, Python's rule is floor, which yields -1. It's described in 5. Expressions.

Put in the terms that Mike Graham mentioned, floor is a round toward minus infinity. Dropping the fraction is a round toward zero.