What''s the fastest way to compute 2n?
[My site|SGI STL|Bjarne FAQ|C++ FAQ Lite|MSDN|Jargon]
Ripped off from various people
Faster pow( 2, n )
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
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
quote:Original post by jmoses
Thats not working for me,
1 << 5 gives me 32 when
5 * 5 gives me 25 of course
1 << 5 == 2^5.
5 * 5 == 5^2.
I like pie.
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
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]
(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^valinline 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]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement