Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] Weird behavior with nan's and min/max
[ 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@c...>
Subject: Re: [Caml-list] Weird behavior with nan's and min/max
Here's a working solution, I think.

let raw_min = min
let raw_max = max

let nan_or_equal x y =
  not (x < y) && not (x > y)

(** min and max that choose nan if its there *)
let min x y =
  if x = y then x
  else if nan_or_equal x y then nan
  else raw_min x y

let max x y =
  if x = y then x
  else if nan_or_equal x y then nan
  else raw_max x y


> min and max have pretty strange behavior when it comes to nan's.  Here's
> an example:
>
> # min 3. nan;;
> - : float = 3.
> # min  nan 3.;;
> - : float = nan
>
> When you think about it, the reason for this is clear.  comparisons
> involving nan's always return false, so if you simply implement min as
> follows:
>
>    if x < y then x else y
>
> the the result will depend on the order.
>
> Now here's the weird bit.  I decided I wanted a polymorphic comparison
> that wouldn't have this problem.  But this is a little harder than it
> seems, since it turns out that specialized float version of equality is
> different from the polymorphic version.  Here's the example:
>
> # let raw_min = min
> val raw_min : 'a -> 'a -> 'a = <fun>
> # let min x y =
>   if not (y = y) then y
>   else if not (x = x) then x
>   else raw_min x y
> ;;
>         val min : 'a -> 'a -> 'a = <fun>
> # let fmin (x:float) y =
>   if not (y = y) then y
>   else if not (x = x) then x
>   else raw_min x y
> ;;
>         val fmin : float -> float -> float = <fun>
> # fmin 3. nan;;
> - : float = nan
> # fmin nan 3.;;
> - : float = nan
> # min nan 3.;;
> - : float = nan
> # min 3. nan;;
> - : float = 3.
>
> So, does this count as a bug?  Any ideas about how to fix this behavior in
> a reasonably efficient way?
>
> 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
>

-------------------
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