Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

max and min with NaN in Haskell

Tags:

haskell

Why is it that the max of NaN and a number is NaN, but the min of NaN and a number is the number? This seems to be at odds with a few other languages I have tried:

In Haskell:

max (0/0) 1 -- NaN
min (0/0) 1 -- 1.0

In Python

>>> max(float("nan"),1) #nan
>>> min(float("nan"),1) #nan

In JavaScript

> Math.max(0/0,1) //NaN
> Math.min(0/0,1) //NaN
like image 339
jek Avatar asked Aug 19 '14 03:08

jek


2 Answers

The Haskell report specifies that (min x y, max x y) will return either (x, y) or (y, x). This is a nice property, but hard to reconcile with a symmetric treatment of NaN.

It's also worth mentioning that this is exactly the same asymmetry as the SSE2 instructions MINSD and MAXSD exhibit, i.e., Haskell min (for Double) can be implemented by MINSD and max by MAXSD.

like image 152
augustss Avatar answered Sep 28 '22 17:09

augustss


Not quite, min 1.0 (0/0) will return NaN, for instance.

This is because any comparison with NaN is defined to return false, and by the definiton of min and max below :

max x y 
     | x <= y    =  y
     | otherwise =  x
min x y
     | x <= y    =  x
     | otherwise =  y

min and max with NaN will return second and first argument, respectively.

like image 24
Evan Sebastian Avatar answered Sep 28 '22 17:09

Evan Sebastian