1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
local M = {}
local complex_mt = {
__tostring = function(self)
if self.im == 0 then
return tostring(self.re)
elseif self.re == 0 then
return (math.abs(self.im) == 1 and (self.im < 0 and "-" or "") or tostring(self.im)) .. "i"
elseif self.im > 0 then
return tostring(self.re) .. "+" .. (math.abs(self.im) == 1 and "" or tostring(self.im)) .. "i"
elseif self.im == 1 then
return tostring(self.re) .. "+i"
elseif self.im == -1 then
return tostring(self.re) .. "-i"
else
return tostring(self.re) .. tostring(self.im) .. "i"
end
end,
__add = function(z1, z2)
if type(z2) == "number" then z2 = M.complex(z2) end
return M.complex(z1.re + z2.re, z1.im + z2.im)
end,
__sub = function(z1, z2)
if type(z2) == "number" then z2 = M.complex(z2) end
return M.complex(z1.re - z2.re, z1.im - z2.im)
end,
__mul = function(z1, z2)
if type(z2) == "number" then z2 = M.complex(z2) end
return M.complex(z1.re * z2.re - z1.im * z2.im,
z1.re * z2.im + z1.im * z2.re)
end,
}
-- makes a new complex number.
M.complex = function(re, im)
local res = {re = re or 0, im = im or 0, type = "complex"}
setmetatable(res, complex_mt)
return res
end
M.sqrt = function(n)
if type(n) == "number" and n < 0 then
return M.complex(0, math.sqrt(-n))
else
return math.sqrt(n)
end
end
M.i = M.complex(0, 1)
return M
|