2 % (c) The AQUA Project, Glasgow University, 1994-1997
5 \section[Complex]{Module @Complex@}
11 realPart, imagPart, conjugate, mkPolar,
12 cis, polar, magnitude, phase
20 %*********************************************************
22 \subsection{The @Complex@ type}
24 %*********************************************************
27 data (RealFloat a) => Complex a = !a :+ !a deriving (Eq,Read,Show)
31 %*********************************************************
33 \subsection{Functions over @Complex@}
35 %*********************************************************
38 realPart, imagPart :: (RealFloat a) => Complex a -> a
42 conjugate :: (RealFloat a) => Complex a -> Complex a
43 conjugate (x:+y) = x :+ (-y)
45 mkPolar :: (RealFloat a) => a -> a -> Complex a
46 mkPolar r theta = r * cos theta :+ r * sin theta
48 cis :: (RealFloat a) => a -> Complex a
49 cis theta = cos theta :+ sin theta
51 polar :: (RealFloat a) => Complex a -> (a,a)
52 polar z = (magnitude z, phase z)
54 magnitude, phase :: (RealFloat a) => Complex a -> a
55 magnitude (x:+y) = scaleFloat k
56 (sqrt ((scaleFloat mk x)^2 + (scaleFloat mk y)^2))
57 where k = max (exponent x) (exponent y)
60 phase (x:+y) = atan2 y x
64 %*********************************************************
66 \subsection{Instances of @Complex@}
68 %*********************************************************
71 instance (RealFloat a) => Prelude.Num (Complex a) where
72 (x:+y) + (x':+y') = (x+x') :+ (y+y')
73 (x:+y) - (x':+y') = (x-x') :+ (y-y')
74 (x:+y) * (x':+y') = (x*x'-y*y') :+ (x*y'+y*x')
75 negate (x:+y) = negate x :+ negate y
76 abs z = magnitude z :+ 0
78 signum z@(x:+y) = x/r :+ y/r where r = magnitude z
79 fromInteger n = fromInteger n :+ 0
81 instance (RealFloat a) => Fractional (Complex a) where
82 (x:+y) / (x':+y') = (x*x''+y*y'') / d :+ (y*x''-x*y'') / d
83 where x'' = scaleFloat k x'
85 k = - max (exponent x') (exponent y')
88 fromRational a = fromRational a :+ 0
90 instance (Prelude.RealFloat a) => Floating (Complex a) where
92 exp (x:+y) = expx * cos y :+ expx * sin y
94 log z = log (magnitude z) :+ phase z
97 sqrt z@(x:+y) = u :+ (if y < 0 then -v else v)
98 where (u,v) = if x < 0 then (v',u') else (u',v')
100 u' = sqrt ((magnitude z + abs x) / 2)
102 sin (x:+y) = sin x * cosh y :+ cos x * sinh y
103 cos (x:+y) = cos x * cosh y :+ (- sin x * sinh y)
104 tan (x:+y) = (sinx*coshy:+cosx*sinhy)/(cosx*coshy:+(-sinx*sinhy))
110 sinh (x:+y) = cos y * sinh x :+ sin y * cosh x
111 cosh (x:+y) = cos y * cosh x :+ sin y * sinh x
112 tanh (x:+y) = (cosy*sinhx:+siny*coshx)/(cosy*coshx:+siny*sinhx)
118 asin z@(x:+y) = y':+(-x')
119 where (x':+y') = log ((-y:+x) + sqrt (1 - z*z))
120 acos z@(x:+y) = y'':+(-x'')
121 where (x'':+y'') = log (z + ((-y'):+x'))
122 (x':+y') = sqrt (1 - z*z)
123 atan z@(x:+y) = y':+(-x')
124 where (x':+y') = log (((1-y):+x) / sqrt (1+z*z))
126 asinh z = log (z + sqrt (1+z*z))
127 acosh z = log (z + (z+1) * sqrt ((z-1)/(z+1)))
128 atanh z = log ((1+z) / sqrt (1-z*z))