Jump to content
  • Advertisement

Archived

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

drago

How do I ..?

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

If you intended to correct an error in the post then please contact us.

Recommended Posts

How can I check a float if it isn''t an integer? What i want to do is check if a float is a power of 2:
bool IsPowerOf2(unsigned int nInput)
{
   float fPower = log10(nInput) / log10(2);

   // Check if fPower is an integer
   ???????????????????????????????????

}
 
or is this impossible due to round-off errors? ---------- Drago

Share this post


Link to post
Share on other sites
Advertisement
I would make the test like this:

float fPower = log10(nInput) / log10(2);
float fRound = (float)floor(fPower+0.5f);
if( (float)fabs(fPower - fRound) < 1e-5f )
{
// The number is power of two
}

You could also count the number of set bits in nInput. If there are only one bit set then you know nInput is power of two. If this is faster or not I don''t know.

- WitchLord

Share this post


Link to post
Share on other sites
My funcion would look like this.

bool ispower2(int num)
{
float exponet = log10(num) / log10(2);
int testnum;

testnum = (int)exponet;
if(exponet == testnum) {
// then its a power of two
return true;
}

return false;
}

hope that helps


Edited by - UraniumRod on 4/29/00 6:29:33 PM

Share this post


Link to post
Share on other sites
on a side note, you can do this:

return exponet == testnum;

instead of the if, else block


adamm@san.rr.com

Share this post


Link to post
Share on other sites

bool IsPowerOf2(unsigned int nInput)
{
unsigned char bitcounter = 0;
for(unsigned char i=0;(i<32) && (bitcounter<2);i++)
{
bitcounter += nInput&1;
nInput >>= 1;
}
return (bitcounter==1);
}


If you want to test if an integer is a power of 2, you don't need to work with floating point operations.

Visit our homepage: www.rarebyte.de.st

GA

Edited by - ga on 5/2/00 3:13:31 PM

Share this post


Link to post
Share on other sites
Could you explain me that code? I think I''m gonna read me a good C++ book and finish it for a change ;-)..

----------
Drago, VerSoft

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!