Jump to content

Arithmetic/Complex: Difference between revisions

Line 984:
}</lang>
 
 
=={{header|Lua}}==
 
<lang lua>
 
--defines addition, subtraction, negation, multiplication, division, conjugation, norms, and a conversion to stringsstrgs.
complex = setmetatable({
__add = function(u, v) return complex(u.real + v.real, u.imag + v.imag) end,
Line 999 ⟶ 998:
norm = function(u) return u.real ^ 2 + u.imag ^ 2 end,
conj = function(u) return complex(u.real, -u.imag) end,
stringstrg = function(u) return u.real .. " + " .. u.imag .. "i" end
}
return operations[index] and operations[index](u)
Line 1,005 ⟶ 1,004:
__newindex = function() error() end
}, {
__call = function(z, realpart, imagpart) return setmetatable({real = realpart, imag = imagpart}, complex) end
} )
 
local i, j = complex(2, 3), complex(1, 1)
 
print(i.stringstrg .. " + " .. j.stringstrg .. " = " .. (i+j).stringstrg)
print(i.stringstrg .. " - " .. j.stringstrg .. " = " .. (i-j).stringstrg)
print(i.stringstrg .. " * " .. j.stringstrg .. " = " .. (i*j).stringstrg)
print(i.stringstrg .. " / " .. j.stringstrg .. " = " .. (i/j).stringstrg)
print("|" .. i.stringstrg .. "| = " .. math.sqrt(i.norm))
print(i.stringstrg .. "* = " .. i.conj.stringstrg)
</lang>
 
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.