Complex Number Library for LoveJIT

Showcase your libraries, tools and other projects that help your fellow love users.
Post Reply
User avatar
xXxMoNkEyMaNxXx
Party member
Posts: 206
Joined: Thu Jan 10, 2013 6:16 am
Location: Canada

Complex Number Library for LoveJIT

Post by xXxMoNkEyMaNxXx » Sun Feb 10, 2013 3:27 am

I made a complex number library for LuaJIT, and it happened to cause no errors in LoveJIT, so I'm sharing it here. I'm thinking about making a complex grapher soon.

Using complex numbers with this is very easy.
Defining a complex number:

Code: Select all

local complexnum=1+2i
Yes, that's it! LuaJIT comes with the syntax for complex numbers, but absolutely no metatables are attached.
So, in the LuaJIT command line:

print(1i)
>0+1i

print(1+1i)
> error, attempt to add 'number' and 'complex'

Enter my Complex Number Library!
Complex.lua
e^(i*pi)+1=0
(6.62 KiB) Downloaded 111 times
Simply drop the script in, require it, and use the functions contained in the cmath table. They work exactly the same as the the regular math table, but can handle complex arguments. They will return complex values at appropriate times such as cmath.sqrt(-1) cmath.asin(1.5), etc. They still manage to work just the same for regular numbers though!

Code: Select all

require'Complex'
print(cmath.sin(2))
print(math.sin(2))
print(cmath.sin(2+7i))
print(math.sin(2+7i))
> 0.90929742682568-0i <--0i means no imaginary component
> 0.90929742682568
> 498.58326915132-228.18002012795i
> Error: number expected, got cdata

Functions and constants available in cmath:
Constants
-e=2.718281828459
-i=sqrt(-1)
-pi

Complex creation and extraction functions
-complex(re,im) creates a complex number from real and imaginary components.
-re(z) real part of z
-im(z) imaginary part of z
-arg(z) argument of z

-abs(z) absolute value of z
-sqrt(z) = z^0.5
-pow(x,y) = x^y
-exp(z) = e^z
-ln(z) = e^? = z
-log(x,y) = ln(y)/ln(x)

Trig functions
-sin
-cos
-tan

-sinh
-cosh
-tanh

-asin
-acos
-atan
-atan2

-asinh
-acosh
-atanh

Miscellaneous functions
-polar(z) returns r,phi = cmath.abs(z),cmath.arg(z)
-rect(r,phi) returns a complex number from polar = r*e^(i*phi)
-diff(z) = re(z)^2-im(z)^2
-zeta(z[,accuracy=1e4]) riemann zeta function
-lintegrate(f,H,[L=0,n=sensible for H])
-cx(string) creates a complex number from a string (e.g. "1.1-i" -> 1.1+-1i)
-cx(re,im) = complex(re,im)


Explore a bit! Try these:
-If i is sqrt(-1),what's sqrt(-i)?
-What's i^i?
-Can it calculate Euler's identity?

chicken_n_cheese
Prole
Posts: 1
Joined: Sat Jan 06, 2018 5:04 am

Re: Complex Number Library for LoveJIT

Post by chicken_n_cheese » Wed Feb 14, 2018 10:40 pm

This is very cool. Would you mind saying that you release this to the public domain, or under an MIT license, so there's no copyright concern.

Post Reply

Who is online

Users browsing this forum: No registered users and 4 guests