Arithmetic/Complex: Difference between revisions
Content added Content deleted
Line 984: | Line 984: | ||
}</lang> |
}</lang> |
||
=={{header|Lua}}== |
|||
<lang lua> |
<lang lua> |
||
--defines addition, subtraction, negation, multiplication, division, conjugation, norms, and a conversion to |
--defines addition, subtraction, negation, multiplication, division, conjugation, norms, and a conversion to strgs. |
||
complex = setmetatable({ |
complex = setmetatable({ |
||
__add = function(u, v) return complex(u.real + v.real, u.imag + v.imag) end, |
__add = function(u, v) return complex(u.real + v.real, u.imag + v.imag) end, |
||
Line 999: | Line 998: | ||
norm = function(u) return u.real ^ 2 + u.imag ^ 2 end, |
norm = function(u) return u.real ^ 2 + u.imag ^ 2 end, |
||
conj = function(u) return complex(u.real, -u.imag) end, |
conj = function(u) return complex(u.real, -u.imag) end, |
||
strg = function(u) return u.real .. " + " .. u.imag .. "i" end |
|||
} |
} |
||
return operations[index] and operations[index](u) |
return operations[index] and operations[index](u) |
||
Line 1,005: | Line 1,004: | ||
__newindex = function() error() end |
__newindex = function() error() end |
||
}, { |
}, { |
||
__call = function(realpart, imagpart) return setmetatable({real = realpart, imag = imagpart}, complex) end |
__call = function(z, realpart, imagpart) return setmetatable({real = realpart, imag = imagpart}, complex) end |
||
} ) |
} ) |
||
local i, j = complex(2, 3), complex(1, 1) |
local i, j = complex(2, 3), complex(1, 1) |
||
print(i. |
print(i.strg .. " + " .. j.strg .. " = " .. (i+j).strg) |
||
print(i. |
print(i.strg .. " - " .. j.strg .. " = " .. (i-j).strg) |
||
print(i. |
print(i.strg .. " * " .. j.strg .. " = " .. (i*j).strg) |
||
print(i. |
print(i.strg .. " / " .. j.strg .. " = " .. (i/j).strg) |
||
print("|" .. i. |
print("|" .. i.strg .. "| = " .. math.sqrt(i.norm)) |
||
print(i. |
print(i.strg .. "* = " .. i.conj.strg) |
||
</lang> |
</lang> |
||