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 strings.
--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,
string = function(u) return u.real .. " + " .. u.imag .. "i" 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.string .. " + " .. j.string .. " = " .. (i+j).string)
print(i.strg .. " + " .. j.strg .. " = " .. (i+j).strg)
print(i.string .. " - " .. j.string .. " = " .. (i-j).string)
print(i.strg .. " - " .. j.strg .. " = " .. (i-j).strg)
print(i.string .. " * " .. j.string .. " = " .. (i*j).string)
print(i.strg .. " * " .. j.strg .. " = " .. (i*j).strg)
print(i.string .. " / " .. j.string .. " = " .. (i/j).string)
print(i.strg .. " / " .. j.strg .. " = " .. (i/j).strg)
print("|" .. i.string .. "| = " .. math.sqrt(i.norm))
print("|" .. i.strg .. "| = " .. math.sqrt(i.norm))
print(i.string .. "* = " .. i.conj.string)
print(i.strg .. "* = " .. i.conj.strg)
</lang>
</lang>