2 module Complex(Complex((:+)), realPart, imagPart, conjugate, mkPolar,
3 cis, polar, magnitude, phase) where
5 infix 6 :+
7 data (RealFloat a) => Complex a = !a :+ !a deriving (Eq,Read,Show)
10 realPart, imagPart :: (RealFloat a) => Complex a -> a
11 realPart (x:+y) = x
12 imagPart (x:+y) = y
14 conjugate :: (RealFloat a) => Complex a -> Complex a
15 conjugate (x:+y) = x :+ (-y)
17 mkPolar :: (RealFloat a) => a -> a -> Complex a
18 mkPolar r theta = r * cos theta :+ r * sin theta
20 cis :: (RealFloat a) => a -> Complex a
21 cis theta = cos theta :+ sin theta
23 polar :: (RealFloat a) => Complex a -> (a,a)
24 polar z = (magnitude z, phase z)
26 magnitude :: (RealFloat a) => Complex a -> a
27 magnitude (x:+y) = scaleFloat k
28 (sqrt ((scaleFloat mk x)^2 + (scaleFloat mk y)^2))
29 where k = max (exponent x) (exponent y)
30 mk = - k
32 phase :: (RealFloat a) => Complex a -> a
33 phase (0 :+ 0) = 0
34 phase (x :+ y) = atan2 y x
37 instance (RealFloat a) => Num (Complex a) where
38 (x:+y) + (x':+y') = (x+x') :+ (y+y')
39 (x:+y) - (x':+y') = (x-x') :+ (y-y')
40 (x:+y) * (x':+y') = (x*x'-y*y') :+ (x*y'+y*x')
41 negate (x:+y) = negate x :+ negate y
42 abs z = magnitude z :+ 0
43 signum 0 = 0
44 signum z@(x:+y) = x/r :+ y/r where r = magnitude z
45 fromInteger n = fromInteger n :+ 0
47 instance (RealFloat a) => Fractional (Complex a) where
48 (x:+y) / (x':+y') = (x*x''+y*y'') / d :+ (y*x''-x*y'') / d
49 where x'' = scaleFloat k x'
50 y'' = scaleFloat k y'
51 k = - max (exponent x') (exponent y')
52 d = x'*x'' + y'*y''
54 fromRational a = fromRational a :+ 0
56 instance (RealFloat a) => Floating (Complex a) where
57 pi = pi :+ 0
58 exp (x:+y) = expx * cos y :+ expx * sin y
59 where expx = exp x
60 log z = log (magnitude z) :+ phase z
62 sqrt 0 = 0
63 sqrt z@(x:+y) = u :+ (if y < 0 then -v else v)
64 where (u,v) = if x < 0 then (v',u') else (u',v')
65 v' = abs y / (u'*2)
66 u' = sqrt ((magnitude z + abs x) / 2)
68 sin (x:+y) = sin x * cosh y :+ cos x * sinh y
69 cos (x:+y) = cos x * cosh y :+ (- sin x * sinh y)
70 tan (x:+y) = (sinx*coshy:+cosx*sinhy)/(cosx*coshy:+(-sinx*sinhy))
71 where sinx = sin x
72 cosx = cos x
73 sinhy = sinh y
74 coshy = cosh y
76 sinh (x:+y) = cos y * sinh x :+ sin y * cosh x
77 cosh (x:+y) = cos y * cosh x :+ sin y * sinh x
78 tanh (x:+y) = (cosy*sinhx:+siny*coshx)/(cosy*coshx:+siny*sinhx)
79 where siny = sin y
80 cosy = cos y
81 sinhx = sinh x
82 coshx = cosh x
84 asin z@(x:+y) = y':+(-x')
85 where (x':+y') = log (((-y):+x) + sqrt (1 - z*z))
86 acos z@(x:+y) = y'':+(-x'')
87 where (x'':+y'') = log (z + ((-y'):+x'))
88 (x':+y') = sqrt (1 - z*z)
89 atan z@(x:+y) = y':+(-x')
90 where (x':+y') = log (((1-y):+x) / sqrt (1+z*z))
92 asinh z = log (z + sqrt (1+z*z))
93 acosh z = log (z + (z+1) * sqrt ((z-1)/(z+1)))
94 atanh z = log ((1+z) / sqrt (1-z*z))