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

Pierre-Etienne Meunier pierreetienne.meunier at gmail.com
Fri May 21 19:11:08 EDT 2010


By the way, speaking of floating-point precision, is there a real reason why haskell forces us to write :

foreign import ccall unsafe "math.h frexp" c_frexp::CDouble->(Ptr CInt)->IO ()
foreign import ccall unsafe "math.h ldexp" c_ldexp::CDouble->CInt->IO CDouble

ulp::Double->Double
ulp x=unsafePerformIO $ do
  expon<-alloca (\e->do
                    c_frexp (realToFrac x) e
                    peek e)
  (c_ldexp 0.5 $ expon-52) >>= return.realToFrac

To allow us to change the IEEE-754 rounding mode ? Shouldn't it be rather "roundDown $ x+3*y/z" or "roundUp $ (cos x)**y" ?

Moreover, due to laziness it appears quite difficult (at least to me !) to implement these roundDown and roundUp functions with C calls to select a hardware rounding mode, then unsafePerformIO. It would be way faster than an allocation (on the stack, I agree), then C calls with a memory access (probably cached, but...) in between !

Does anyone know how this translates to LLVM (maybe in the forthcoming GHC backend) ?
If anyone has got an answer or a solution...

Cheers,
PE

El 21/05/2010, a las 17:10, Don Stewart escribió:

> dvde:
>> 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
>> 
>> The program works on windows but it did not on OSX - it was too slow.  
>> Now, after big headaches and much frustration, I replaced the code above  
>> with this line (why didn't I come up with this earlier?):
>> 
>> xf = double2Float xd
>> 
>> and now everything works just fine.
>> 
>> I am not really surprised by the speed-up (and no-one should be), but I  
>> am still surprised how often such kinds of unobvious problems occur  
>> while programming in Haskell. So I write this email just to remind me  
>> and you to look out for such pitfalls.
> 
> There's no rewrite rule for this optimization. There's a ticket though
> with some of the solutions.
> 
> -- Don
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe



More information about the Haskell-Cafe mailing list