Archived

This topic is now archived and is closed to further replies.

wild_pointer

Faster pow( 2, n )

Recommended Posts

That''s because bit shifting (<< and >>) only applies for powers of two. That is, after all, why it''s called bit shifting.

If you want to do powers of other numbers, you may as well just use pow(), since it just does what any other power function would do. However, there may be certain tricks you could work out if you''re really clever for some slightly faster ways for certain powers (I doubt you could come up with anything that''s faster in general than pow).

The Artist Formerly Known as CmndrM

http://chaos.webhop.org

Share this post


Link to post
Share on other sites
It isn't accurate past about 5 significant digits, but it has worked perfectly for my needs. It is for doubles (64bit floating point).
(note: Would need a minor change to work on big-endian chips like motorola).

This one is valid for all values. I have some faster/more accurate ones but they are only good for ranges like [0, 1] which makes them useless for most of my needs


// calculates 2^val
inline double fast_exp2 (const double val)
{
int e;
double ret;

if (val >= 0)
{
e = (int)val;
ret = val - (e - 1);
((*(1 + (int *) &ret)) &= ~(2047 << 20)) += (e + 1023) << 20;
}
else
{
e = (int)(val + 1023);
ret = val - (e - 1024);
((*(1 + (int *) &ret)) &= ~(2047 << 20)) += e << 20;
}
return (ret);
}


The could can be sped up if you change the rounding mode of the FPU before doing the double to int conversion

[edited by - ben allison on September 6, 2003 12:07:27 AM]

Share this post


Link to post
Share on other sites