summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorheav <hheav3@gmail.com>2022-10-27 02:22:50 +0000
committerheav <hheav3@gmail.com>2022-10-27 02:22:50 +0000
commitd9c2275a79bd090098e416861ec14d0294ae8c39 (patch)
treef76b9d8b22b22b1b94f549d7f04eea6c9aaeba09
parentf0f5b15fbe827572e335ca825d627f05325ee6e9 (diff)
tentative complex numbers
-rw-r--r--czzc/math.lua51
1 files changed, 51 insertions, 0 deletions
diff --git a/czzc/math.lua b/czzc/math.lua
new file mode 100644
index 0000000..cad47ee
--- /dev/null
+++ b/czzc/math.lua
@@ -0,0 +1,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