2 % (c) The AQUA Project, Glasgow University, 1994-1996
5 \section[Complex]{Module @Complex@}
11 realPart, imagPart, conjugate, mkPolar,
12 cis, polar, magnitude, phase
19 %*********************************************************
21 \subsection{The @Complex@ type}
23 %*********************************************************
26 data (RealFloat a) => Complex a = !a :+ !a deriving (Eq,Read,Show)
30 %*********************************************************
32 \subsection{Functions over @Complex@}
34 %*********************************************************
37 realPart, imagPart :: (RealFloat a) => Complex a -> a
41 conjugate :: (RealFloat a) => Complex a -> Complex a
42 conjugate (x:+y) = x :+ (-y)
44 mkPolar :: (RealFloat a) => a -> a -> Complex a
45 mkPolar r theta = r * cos theta :+ r * sin theta
47 cis :: (RealFloat a) => a -> Complex a
48 cis theta = cos theta :+ sin theta
50 polar :: (RealFloat a) => Complex a -> (a,a)
51 polar z = (magnitude z, phase z)
53 magnitude, phase :: (RealFloat a) => Complex a -> a
54 magnitude (x:+y) = scaleFloat k
55 (sqrt ((scaleFloat mk x)^2 + (scaleFloat mk y)^2))
56 where k = max (exponent x) (exponent y)
59 phase (x:+y) = atan2 y x
63 %*********************************************************
65 \subsection{Instances of @Complex@}
67 %*********************************************************
70 instance (RealFloat a) => Prelude.Num (Complex a) where
71 (x:+y) + (x':+y') = (x+x') :+ (y+y')
72 (x:+y) - (x':+y') = (x-x') :+ (y-y')
73 (x:+y) * (x':+y') = (x*x'-y*y') :+ (x*y'+y*x')
74 negate (x:+y) = negate x :+ negate y
75 abs z = magnitude z :+ 0
77 signum z@(x:+y) = x/r :+ y/r where r = magnitude z
78 fromInteger n = fromInteger n :+ 0
80 instance (RealFloat a) => Fractional (Complex a) where
81 (x:+y) / (x':+y') = (x*x''+y*y'') / d :+ (y*x''-x*y'') / d
82 where x'' = scaleFloat k x'
84 k = - max (exponent x') (exponent y')
87 fromRational a = fromRational a :+ 0
89 instance (Prelude.RealFloat a) => Floating (Complex a) where
91 exp (x:+y) = expx * cos y :+ expx * sin y
93 log z = log (magnitude z) :+ phase z
96 sqrt z@(x:+y) = u :+ (if y < 0 then -v else v)
97 where (u,v) = if x < 0 then (v',u') else (u',v')
99 u' = sqrt ((magnitude z + abs x) / 2)
101 sin (x:+y) = sin x * cosh y :+ cos x * sinh y
102 cos (x:+y) = cos x * cosh y :+ (- sin x * sinh y)
103 tan (x:+y) = (sinx*coshy:+cosx*sinhy)/(cosx*coshy:+(-sinx*sinhy))
109 sinh (x:+y) = cos y * sinh x :+ sin y * cosh x
110 cosh (x:+y) = cos y * cosh x :+ sin y * sinh x
111 tanh (x:+y) = (cosy*sinhx:+siny*coshx)/(cosy*coshx:+siny*sinhx)
117 asin z@(x:+y) = y':+(-x')
118 where (x':+y') = log ((-y:+x) + sqrt (1 - z*z))
119 acos z@(x:+y) = y'':+(-x'')
120 where (x'':+y'') = log (z + ((-y'):+x'))
121 (x':+y') = sqrt (1 - z*z)
122 atan z@(x:+y) = y':+(-x')
123 where (x':+y') = log (((1-y):+x) / sqrt (1+z*z))
125 asinh z = log (z + sqrt (1+z*z))
126 acosh z = log (z + (z+1) * sqrt ((z-1)/(z+1)))
127 atanh z = log ((1+z) / sqrt (1-z*z))