2 -- complex arithmetic package for lua
3 -- Luiz Henrique de Figueiredo (lhf@csg.uwaterloo.ca)
7 Complex
={type="package"}
10 return { re
=x
, im
=y
, type="complex" }
13 function Complex
.conj(x
,y
)
14 return complex(x
.re
,-x
.im
)
17 function Complex
.norm2(x
)
18 local n
=Complex
.mul(x
,Complex
.conj(x
))
22 function Complex
.abs(x
)
23 return sqrt(Complex
.norm2(x
))
26 function Complex
.add(x
,y
)
27 return complex(x
.re
+y
.re
,x
.im
+y
.im
)
30 function Complex
.sub(x
,y
)
31 return complex(x
.re
-y
.re
,x
.im
-y
.im
)
34 function Complex
.mul(x
,y
)
35 return complex(x
.re
*y
.re
-x
.im
*y
.im
,x
.re
*y
.im
+x
.im
*y
.re
)
38 function Complex
.div(x
,y
)
39 local z
=x
*Complex
.conj(y
)
40 local t
=Complex
.norm2(y
)
46 function Complex
.fallback(x
,y
,op
)
47 if type(x
)=="number" then x
=complex(x
,0) end
48 if type(y
)=="number" then y
=complex(y
,0) end
49 if type(x
)=="complex" and type(y
)=="complex" then
50 return Complex
[op
](x
,y
)
52 return Complex
.oldfallback(x
,y
)
56 function Complex
.newtype(x
)
57 local t
=Complex
.oldtype(x
)
58 if t
=="table" and x
.type then return x
.type else return t
end
61 function Complex
.print(x
)
62 if type(x
)~="complex" then
66 if x
.im
>=0 then s
="+" else s
="" end
67 Complex
.oldprint(x
.re
..s
..x
.im
.."I")
71 function Complex
.newabs(x
)
72 if type(x
)~="complex" then
73 return Complex
.oldabs(x
)
79 Complex
.oldfallback
=setfallback("arith",Complex
.fallback
)
80 Complex
.oldtype
=type type=Complex
.newtype
81 Complex
.oldprint
=print print=Complex
.print
82 Complex
.oldabs
=abs abs=Complex
.abs