Proper rounding of floating-point values

Previous Topic Next Topic
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view

Proper rounding of floating-point values

Troels Henriksen
Much to my surprise, there does not seem to be a function in base (let
alone the Prelude) that rounds floating point numbers correctly in the
presence of NaNs and infinities.  For example:

  > round (0/0 :: Double) :: Int
  > round (0/0 :: Double) :: Integer
  > round (1/0 :: Double) :: Int
  > round (1/0 :: Double) :: Integer

This is because the 'round' function must return an instance of
Integral, which Double is not.  In the presence of NaNs and infinities,
this does not fly.  In my own code, I ended up just using the FFI to
call out to C, which is simple enough:

  foreign import ccall "round" c_round :: Double -> Double
  foreign import ccall "roundf" c_roundf :: Float -> Float

However, it does disturb me a bit that I cannot find a standard way to
do this fairly common operation.

(GHC's implementation does seem to avoid many other common pitfalls[0],
probably because it does use C's round() under the covers.)


\  Troels
/\ Henriksen
Haskell-Cafe mailing list
To (un)subscribe, modify options or view archives go to:
Only members subscribed via the mailman list are allowed to post.