Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] min, max and nan
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Yaron Minsky <yminsky@g...>
Subject: [Caml-list] min, max and nan
One of the oddities associated with NaNs in ocaml is what happens when
you take the min of something and nan.  Witness:

# min nan 3.;;
- : float = 3.
# min 3. nan;;
- : float = nan

Surprisingly, the result depends on the ordering.  Why it does so is
clear once you look at the implementation and ponder for a moment the
IEEE requirements on comparisons involving nan.  When using ocaml
3.07, I tried and failed to come up with a polymorphic min that
behaved reasonably in this case, that is, that returned nan when
either argument is nan.  With 3.08, this is now doable.  Here's how it
works:

# let contains_nan x = x <> x;;
val contains_nan : 'a -> bool = <fun>
# let nmin x y = 
  if contains_nan x then x 
  else if contains_nan y then y 
  else min x y;;
      val nmin : 'a -> 'a -> 'a = <fun>
# nmin 3. nan;;
- : float = nan
# nmin nan 3.;;
- : float = nan

Still, we don't quite escape from the oddities of nan.  We still get
order dependence in the case of larger data structures that include
nan's:

# nmin (1,nan) (2,nan);;
- : int * float = (1, nan)
# nmin (2,nan) (1,nan);;
- : int * float = (2, nan)

But in my mind, the current state of affairs is a big improvement.

Yaron

-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners