[Haskell-cafe] double2Float is faster than (fromRational . toRational)

Daniel Fischer daniel.is.fischer at web.de
Fri May 21 16:35:37 EDT 2010


On Friday 21 May 2010 22:06:43, Henning Thielemann wrote:
> On Fri, 21 May 2010, Daniel van den Eijkel wrote:
> > Dear Haskellers,
> >
> > I just want to share an observation. I had to convert a Double to a
> > Float value in an inner loop of an application, and I used somethin
> > like this:
> >
> > xf = (fromRational $ toRational xd) :: Float
>
> I think realToFrac is the function to use here, and this might be
> replaced by double2Float by an optimizer rule. I think double2Float is
> from a GHC package and thus one should avoid to call double2Float
> directly.

In GHC.Real:

-- | general coercion to fractional types
realToFrac :: (Real a, Fractional b) => a -> b
realToFrac = fromRational . toRational

{-# RULES
"realToFrac/Int->Int" realToFrac = id :: Int -> Int
    #-}

There are more rules elsewhere. If you compile with optimisations, GHC 
turns your realToFrac into double2Float# nicely, so it's okay to use 
realToFrac.
However, without optimisations, no rules fire, so you'll get 
(fromRational . toRational).


More information about the Haskell-Cafe mailing list