Why is sys.maxint < (sys.maxint - 100 + 0.01) in Python?
3 Answers
This is probably due to loss of precision for very large floating point values. (the adding of 0.01 converts the right-hand-side to float).
Edit: I have tried to come up with an exact explanation of what happens here, but to no avail. So I posted a question about it.
7 Comments
int(sys.maxint - 100 + 0.01) on 64-bit: 9223372036854775808L (instead of ...807L)loose 11 bits of precision, are those 11 bits set to zero or some random bit string?On a system with 64-bit longs, sys.maxint is:
// decimal hexadecimal 9223372036854775807 0x7fffffffffffffff So sys.maxint - 100 is:
9223372036854775707 0x7fffffffffffff9b Adding 0.01 forces this value to be rounded to double-precision floating point before the addition. The two closest values that are representable in double-precision are:
9223372036854774784 0x7ffffffffffffc00 9223372036854775808 0x8000000000000000 Because sys.maxint - 100 is closer to the second (larger) value, it rounds up. Adding 0.01 gives:
9223372036854775808.01 0x8000000000000000.028f5c28f5c... which is not representable in double-precision, so it is rounded again, to:
9223372036854775808 0x8000000000000000 So the value of sys.maxint - 100 + 0.01 is actually larger than the value of sys.maxint. However, in many modern languages, comparison between an integer and a float forces the integer value to be converted to floating point before the comparison takes place; if this were the case in python, sys.maxint would be rounded up to the same value, and they would compare equal. It seems that this is not the case in Python. I'm not familiar with the details of python numerics, but this is an interesting curiosity of the language.
2 Comments
assert float(sys.maxint) > (sys.maxint - 100 + 0.01)== relation is used to determine container membership.at least on my machine it is not
In [7]: import sys In [8]: sys.maxint < (sys.maxint - 100 + 0.01) Out[8]: False