Hacker News new | ask | show | jobs
by im3w1l 2125 days ago
So I tried a thing in python3.

    >>> max(float('nan'), 0)
    nan
    >>> max(0, float('nan'))
    0
Numpy works though

    >>> np.maximum(float('nan'), 0)
    nan
    >>> np.maximum(0, float('nan'))
    nan
Edit: Fixed numpy example.
2 comments

The functions minNum and maxNum ([IEEE 754-2008, 5.3.1, p19]) take two arguments and return the min and max, respectively. They have the special, distinguished property that “if exactly one argument is NaN, they return the other. If both are NaN they return NaN.”

Source: http://tom7.org/nand/nand.pdf

Edit: As of 2019, the formerly required minNum, maxNum, minNumMag, and maxNumMag in IEEE 754-2008 are now deleted due to their non-associativity. [https://en.wikipedia.org/wiki/IEEE_754#2019]

And for this particular use case, numpy has .clip(), that takes:

    np.clip(ndarray, lower_bound, upper_bound)
And handles NaNs correctly.