Chao Xu
Chao Xu

Reputation: 41

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

Why is this the case?

Upvotes: 4

Views: 2091

Answers (4)

lurker
lurker

Reputation: 58284

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.

Upvotes: 1

user1855673
user1855673

Reputation: 51

I am not sure about Python, but in C++ integer/integer = integer, and therefore in case of -1/2 is -0.5 which is rounded automatically to integer and therefore you get the 0 answer.

In case of Python, maybe the system used the floor function to convert the result into an integer.

Upvotes: -1

Mike Graham
Mike Graham

Reputation: 76753

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.

Upvotes: 8

SethMMorton
SethMMorton

Reputation: 48775

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.

Upvotes: 1

Related Questions