dansalmo
dansalmo

Reputation: 11686

Is this correct for cmp()?

I just came across this behavior but have not seen it explained anywhere. I would think float('-inf') should be less than 0.

>>> cmp(0, float('-inf'))
1

Upvotes: 0

Views: 80

Answers (2)

Tim Peters
Tim Peters

Reputation: 70572

It might help to know that cmp(a, b) is essentially the sign of a-b. So it's +1 if a > b, -1 if a < b, and 0 if a == b.

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121176

float('-inf') is smaller than 0.

cmp() returns a positive value when the first argument is greater than the second. Since float('-inf') is smaller than 0, that also means that 0 is greater than float('-inf') so you would expect cmp() to return 1.

From the cmp() documentation:

Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y.

and also simply verified:

>>> cmp(0, -1)
1

Upvotes: 7

Related Questions