The built-in min and max functions select a value using the usual comparison operators. Every comparison involving NaN evaluates to false, so when one of the arguments is NaN, neither value ever appears smaller or larger than the other. The function then falls back on keeping the first argument, which means the result depends on the order the values were passed rather than on the values themselves.
For example, the same two values can be passed in both orders:
import math
print(min(1.0, math.nan)) # 1.0
print(min(math.nan, 1.0)) # nan
print(max(1.0, math.nan)) # 1.0
print(max(math.nan, 1.0)) # nan
Passing the real number first returns the real number, while passing NaN first returns NaN. Both min and max behave this way, and nothing in the result indicates that a comparison was skipped.
Since Python 3.15, the math module provides fmin and fmax, which treat NaN as missing data.
import math
print(math.fmin(1.0, math.nan)) # 1.0
print(math.fmin(math.nan, 1.0)) # 1.0
print(math.fmax(1.0, math.nan)) # 1.0
print(math.fmax(math.nan, 1.0)) # 1.0
Every call now returns 1.0. The NaN argument is disregarded rather than propagated, so the result reflects the real value regardless of the order in which the two were passed.
Leave a Comment
Cancel reply