From d9c2275a79bd090098e416861ec14d0294ae8c39 Mon Sep 17 00:00:00 2001 From: heav Date: Thu, 27 Oct 2022 02:22:50 +0000 Subject: tentative complex numbers --- czzc/math.lua | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 czzc/math.lua 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 -- cgit v1.2.3