I have hot spots in my code where I\'m doing pow() taking up around 10-20% of my execution time.
My input to pow(x,y) is very specific, so
Ian Stephenson wrote this code which he claims outperforms pow(). He describes the idea as follows:
Pow is basically implemented using log's:
pow(a,b)=x(logx(a)*b). so we need a fast log and fast exponent - it doesn't matter what x is so we use 2. The trick is that a floating point number is already in a log style format:a=M*2ETaking the log of both sides gives:
log2(a)=log2(M)+Eor more simply:
log2(a)~=EIn other words if we take the floating point representation of a number, and extract the Exponent we've got something that's a good starting point as its log. It turns out that when we do this by massaging the bit patterns, the Mantissa ends up giving a good approximation to the error, and it works pretty well.
This should be good enough for simple lighting calculations, but if you need something better, you can then extract the Mantissa, and use that to calculate a quadratic correction factor which is pretty accurate.