Faster pow( 2, n )

Started by
7 comments, last by wild_pointer 20 years, 7 months ago
What''s the fastest way to compute 2n? [My site|SGI STL|Bjarne FAQ|C++ FAQ Lite|MSDN|Jargon]
Ripped off from various people
[size=2]
Advertisement
1 << n

You should never let your fears become the boundaries of your dreams.
You should never let your fears become the boundaries of your dreams.
nifty. thanks.


[My site|SGI STL|Bjarne FAQ|C++ FAQ Lite|MSDN|Jargon]
Ripped off from various people
[size=2]
IPL ... nothing is Faster...
J.A.N.K.E.Y.: Journeying Artificial Nocturnal Killing and Exploration Youth
Thats not working for me,
1 << 5 gives me 32 when
5 * 5 gives me 25 of course
- John Moses
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
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.
[sub]My spoon is too big.[/sub]
quote:Original post by RenderTarget
1 << 5 == 2^5.
5 * 5 == 5^2.
No, 2^5 == 5^2 == 7.

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^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