[Haskell-cafe] Data.Complex.magnitude slow?

stefan kersten sk at k-hornz.de
Thu Jul 17 15:21:32 EDT 2008

On 17.07.2008, at 17:18, Henning Thielemann wrote:
>> i've attached an example program which seems to indicate that the  
>> magnitude function from Data.Complex is very slow compared to a  
>> more naive implementation (for Complex Float). on my machine  
>> (intel core2 duo, osx 10.4) the CPU time using the library  
>> function is about 6-7 times as much as when using the other  
>> function. any ideas what might be going on? any flaws in my  
>> measurement code?
> Complex.magnitude must prevent overflows, that is, if you just  
> square 1e200::Double you get an overflow, although the end result  
> may be also around 1e200. I guess, that to this end  
> Complex.magnitude will separate mantissa and exponent, but this is  
> done via Integers, I'm afraid.

very enlightening, thanks! it might be possible to (almost) get the  
best of two worlds (ported from dejagnu's libm):

c_magnitude4 :: Complex Float -> Float
c_magnitude4 (x:+y) = if x' < y'
                         then mag y' x'
                         else mag x' y'
         x'      = abs x
         y'      = abs y
         sqr x   = x * x
         mag a 0 = a
         mag a b = a * sqrt (1 + sqr (b/a))

is fast and doesn't overflow intermediate results but accuracy isn't  
so great ...


More information about the Haskell-Cafe mailing list