lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I wrote a new pure-lua implementation of complex numbers.

"Why yet another lua library for complex numbers?," you might ask.

Well, first it was a fun thing to do!

Second, I did download a few other complex libraries for lua and tried them.  None clicked exactly with what I was looking for, so decided to have a go at rolling my own.

I created a library named cmath.lua.  It is a feature-complete, backward-compatible update to math.lua:

require 'cmath'
cmath.sqrt(-1)
i

If you are really brave, you can do this...

math = require 'cmath'

cmath.lua adds almost nothing to the API of math.lua; just four new items:

    cmath.i
    cmath.re()
    cmath.im()
    cmath.angle()

You create complex numbers using standard arithmetic expressions:

local i, e, pi = cmath.i, cmath.exp(1), cmath.pi

omega = e ^ (2 * pi * i / 1024)

The goal is that everything should work as you would expect in normal lua.  Ideally, you should not have to learn anything new to use this library!  Just load and go, and do everything like you normally would in lua.  (Where usability and easy "on-ramp" conflicted with performance, I chose to optimize for usability.)

All of the existing functions in math.lua that have a meaningful extension to complex numbers have been included:

    cmath.type
    cmath.abs
    cmath.exp
    cmath.sqrt
    cmath.log
    cmath.log10
    cmath.cos
    cmath.sin
    cmath.tan
    cmath.acos
    cmath.asin
    cmath.atan
    cmath.atan2

All other functions in math.lua (those that have no mathematically meaningful extension to complex values) return an appropriate error message when they are applied to complex values.

All of the metatable-based arithmetic overloading operations have been implemented, including those that shouldn't be applied to complex values.  In the latter case, an appropriate error message is issued.

Complex values are opaque; you really can't pry them open or look inside them or change them in any way (unless you resort "backstage" developer power tools such as the debug API.)  They are supposed to look and feel just like normal lua numbers.

I would be delighted to have you check it out:

    git clone http://github.com/gregfjohnson/cmath.git

Any thoughts or comments, bug reports, suggestions, etc. would be most welcome.

If this looks reasonable, and if there is agreement that this is useful, I would be glad to have it go up on the lua libraries wiki.  Would need a bit of community help/guidance/advice/concurrence/permission to do that.

Thanks!

Greg Johnson