#### Archived

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

# Faster pow( 2, n )

This topic is 5404 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

1 << n

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

##### Share on other sites
IPL ... nothing is Faster...

##### Share on other sites
Thats not working for me,
1 << 5 gives me 32 when
5 * 5 gives me 25 of course

##### Share on other sites
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 on other sites
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.

##### Share on other sites
quote:
Original post by RenderTarget
1 << 5 == 2^5.
5 * 5 == 5^2.

No, 2^5 == 5^2 == 7.

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

1. 1
2. 2
3. 3
4. 4
Rutin
18
5. 5

• 11
• 12
• 9
• 12
• 37
• ### Forum Statistics

• Total Topics
631420
• Total Posts
2999989
×