If you’ve ever wanted to calculate the logarithm of a number using a base other than Math.E in AS3, you may have noticed the lack of a Math function to do this (ex. Math.logx()). Most likely, if you were doing this, you already knew how to calculate a logarithm with an arbitrary base using the tools you had. But, if you were like me, and knew just enough to know what you wanted, but not enough to know how to get it, this simple function might save you the time it takes to figure it out:
function logx(val:Number, base:Number=10):Number { return Math.log(val)/Math.log(base) } |
So, “2 log 8” would be logx(8,2).
To be honest, I’m mostly posting this for my own reference when I forget it again in a few months. 🙂
Feel free to correct me if there’s a better way to do this.
thanks! i’ll note it as well!
Shame on you Grant, unless you expect unknown number of bases, don’t use this function in your code. Instead, you’ll want to pre-compute the Math.log(base) part (or better yet, it’s inverse and just multiply).
For example, log in base 10 becomes:
function log10(val:Number):Number {
return Math.log(val) * 0.434294481904;
}
You could also add memoization (cached results). The intent here was to convey the approach, not an optimized solution.
Besides, sometimes you don’t have to optimize everything. In my case the code was inlined and only run a couple of times per frame, so optimization really wasn’t a concern. But agreed, the above is a good optimization for most cases.
Cheers.