Version 0.1
complex.lua is a small Lua ligrary that implements complex numbers. It started as an answer on Code Review Stack Exchange.
complex = require 'complex'
— require the library,complex.IMAGINARY_CHAR = 'j'
— use electrical notation for serialisation,complex.PREFIX = true
— use i/j as a prefix for serialisation,complex.PARENTHESES = true
— serialise complex numbers in parentheses,local i = complex.i
— set i,complex (re, im)
will return the complex number with real partre
and imaginary partim
,z = complex (re, im); z1 = complex (z)
will copyz
toz1
,z.r
andz.i
are real and imaginary parts ofz
, respectively,z.conjugate ()
— complex conjugation,+
,-
,*
and/
operators work as expected; both Lua (real) numbers and complex numbers can be left or right operands:local z = 1 + complex.i
,local z = complex.i + 1
,local z = complex (1, 0) + complex.i
will setz
to the same value,- unary
-
will work as expected, ==
will work as expected,<
will give a correct result when both operands are real. In addition, it will return true only if the real parts of operands are equal and the imaginary part of the first one is less than that of the secon one, which can facilitate sorting,complex:abs ()
— the absolute value,complex:abs2 ()
— the absolute value squared,complex:arg ()
— the argument,complex.polar (abs, arg)
— return a complex number with the absolute value ofabs
and argument ofarg
,complex:exp ()
— exponent of a complex number,x ^ y
will return a complex number, if either Euler's or de Moivre's formula is applicable, i.e., if either the first operand is positive number, or the second argument is real integer,complex:roots (n)
will return alln
n
th roots of a complex number,tostring (x)
will serialise the complex number rather prettily (e.g.,5 - 5i
,-5i
or5
) subject tocomplex.IMAGINARY_CHAR
,complex.PREFIX
andcomplex.PARENTHESES
.
- Lua 5.1, 5.2, 5.3, 5.4 or LuaJIT.
complex.lua is written by Alexander Mashin in 2020 and 2024, originally as a rework of the code written by Nick. Lua is created by Roberto Ierusalimschy.