I have to say, math is not my strong suit. I was hoping to get a decent result for How to find the cube root of a negative integer such that it does not return NaN? by using the Data.Complex package but when i do like
*Main> ((-8):+0) ** (1/3)
1.0 :+ 1.732050807568877
I expected to get something like (-2.0):+0
where -2 is the real part and 0 is the imaginary part. However the result turns out with a significant imaginary part. I have checked the (**)
RealFloat
instance of the Complex
type where it states;
x ** y = case (x,y) of
(_ , (0:+0)) -> 1 :+ 0
((0:+0), (exp_re:+_)) -> case compare exp_re 0 of
GT -> 0 :+ 0
LT -> inf :+ 0
EQ -> nan :+ nan
((re:+im), (exp_re:+_))
| (isInfinite re || isInfinite im) -> case compare exp_re 0 of
GT -> inf :+ 0
LT -> 0 :+ 0
EQ -> nan :+ nan
| otherwise -> exp (log x * y)
where
inf = 1/0
nan = 0/0
So we must be normally looking at the exp (log x * y)
part where exp
and log
instances of Complex
looks like;
exp (x:+y) = expx * cos y :+ expx * sin y
where expx = exp x
log z = log (magnitude z) :+ phase z
then i moved on to the magnitude
which is defined like;
magnitude :: (RealFloat a) => Complex a -> a
magnitude (x:+y) = scaleFloat k
(sqrt (sqr (scaleFloat mk x) + sqr (scaleFloat mk y)))
where k = max (exponent x) (exponent y)
mk = - k
sqr z = z * z
where i am stuck. I would just simply do like sqrt (realPart z ^ 2 + imagPart z ^ 2)
.
What am i doing wrong..?