Arithmetic/Complex: Difference between revisions

Content added Content deleted
(added factor example)
Line 983: Line 983:
return Math.sqrt( Math.pow(this.r,2) , Math.pow(this.i,2) )
return Math.sqrt( Math.pow(this.r,2) , Math.pow(this.i,2) )
}</lang>
}</lang>


=={{header|Lua}}==


--defines addition, subtraction, negation, multiplication, division, conjugation, norms, and a conversion to strings.
complex = setmetatable({
__add = function(u, v) return complex(u.real + v.real, u.imag + v.imag) end,
__sub = function(u, v) return complex(u.real - v.real, u.imag - v.imag) end,
__mul = function(u, v) return complex(u.real * v.real - u.imag * v.imag, u.real * v.imag + u.imag * v.real) end,
__div = function(u, v) return u * complex(v.real / v.norm, -v.imag / v.norm) end,
__unm = function(u) return complex(-u.real, -u.imag) end,
__index = function(u, index)
local operations = {
norm = function(u) return u.real ^ 2 + u.imag ^ 2 end,
conj = function(u) return complex(u.real, -u.imag) end,
string = function(u) return u.real .. " + " .. u.imag .. "i" end
}
return operations[index] and operations[index](u)
end,
__newindex = function() error() end
}, {
__call = function(realpart, imagpart) return setmetatable({real = realpart, imag = imagpart}, complex) end
} )

local i, j = complex(2, 3), complex(1, 1)

print(i.string .. " + " .. j.string .. " = " .. (i+j).string)
print(i.string .. " - " .. j.string .. " = " .. (i-j).string)
print(i.string .. " * " .. j.string .. " = " .. (i*j).string)
print(i.string .. " / " .. j.string .. " = " .. (i/j).string)
print("|" .. i.string .. "| = " .. math.sqrt(i.norm))
print(i.string .. "* = " .. i.conj.string)


=={{header|Maple}}==
=={{header|Maple}}==