From 7c09b694b9eeaad268e99c3161393c3412e07a34 Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Sun, 14 Dec 2014 20:04:04 +0100 Subject: [PATCH] add CCFloat.{fsign, sign_exn} --- core/CCFloat.ml | 11 +++++++++++ core/CCFloat.mli | 15 ++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/core/CCFloat.ml b/core/CCFloat.ml index 6749913a..ad8ad32b 100644 --- a/core/CCFloat.ml +++ b/core/CCFloat.ml @@ -76,6 +76,17 @@ let sign (a:float) = else if a > 0.0 then 1 else 0 +let fsign a = + if is_nan a then nan + else if a = 0. then a + else Pervasives.copysign 1. a + +exception TrapNaN of string + +let sign_exn (a:float) = + if is_nan a then raise (TrapNaN "sign") + else compare a 0. + let to_int (a:float) = Pervasives.int_of_float a let of_int (a:int) = Pervasives.float_of_int a diff --git a/core/CCFloat.mli b/core/CCFloat.mli index 02da623e..32a3317f 100644 --- a/core/CCFloat.mli +++ b/core/CCFloat.mli @@ -77,7 +77,20 @@ val random_small : t random_gen val random_range : t -> t -> t random_gen val sign : t -> int -(** [sign t] is one of [-1, 0, 1] *) +(** [sign t] is one of [-1, 0, 1], depending on how the float + compares to [0.] + @deprecated use {! fsign} or {!sign_exn} since it's more accurate *) + +val fsign : t -> float +(** [fsign x] is one of [-1., -0., +0., +1.], or [nan] if [x] is NaN. + @since NEXT_RELEASE *) + +exception TrapNaN of string +val sign_exn : t -> int +(** [sign_exn x] will return the sign of [x] as [1, 0] or [-1], or raise an + exception [TrapNaN] if [x] is a NaN. + Note that infinities have defined signs in OCaml. + @since NEXT_RELEASE *) val to_int : t -> int val of_int : int -> t