问题
In my understanding, sys.float_info.max
is the largest possible float value. However, it seems that comparing such large values fail.
import math
import sys
m = sys.float_info.max # type 'float'
m == m # True
m < m # False
m > m # False
m == m-1.0 # True
m < m-1.0 # False
m > m-1.0 # False
m == m-1e100 # True
m < m-1e100 # False
m > m-1e100 # False
m == m-1e300 # False
m > m-1e300 # True
m < m-1e300 # False
I assume that's because of the limited precision? If so, in what numerical range can i operate safely?
The above code was run with Python 3.5.2.
回答1:
On a typical machine running Python, there are 53 bits of precision available for a Python float. If you try to go further, Python will eliminate the smallest part so the number can be properly represented.
So the value 1 is absorbed or cancelled to be able to represent the high value you're trying to compute.
The limit is obtained by subtracting (or adding) the value multiplied by float epsilon.
On my machine:
maxfloat == 1.7976931348623157e+308
epsilon == 2.220446049250313e-16
sample test code
import math
import sys
m = sys.float_info.max # type 'float'
eps = sys.float_info.epsilon
print(m == m-(m*(eps/10))) # True
print(m == m-(m*eps)) # False
m*eps
is the smallest value you have to subtract to make comparison fail. It's always relative to the m
value.
回答2:
Maybe if you try printing those numbers, you will better understand what they are:
>>> sys.float_info.max
1.7976931348623157e+308
>>> sys.float_info.max - 1.0
1.7976931348623157e+308
>>> sys.float_info.max - 1e100
1.7976931348623157e+308
>>> sys.float_info.max - 1e300
1.7976931248623157e+308
Note that the printout does not nearly describe all the problems one can encounter with floating point number precision, but in this case, the "problems" are trivial. You can see that only the last number is different.
来源:https://stackoverflow.com/questions/53030217/why-do-comparisions-between-very-large-float-values-fail-in-python