Jump to content
  • Advertisement
Sign in to follow this  
ukdeveloper

Unity Problem with log functions

This topic is 4824 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

Hi, I'm using some code I found on this thread about using SDL_TTF with OpenGL. Part of the code was a maths function, which I can't make work. You'll find the original in that thread I linkified. Here is said function as I have it, in a header file I made:
int nextpowerof2(int x)
{

	double logbase2 = log(x) / log(2); // This line is the culprit
	return round(pow(2,ceil(logbase2)));

}
But the compiler (VS2005 Express Beta 2) kicks up a fuss with the following error, twice on the same line as referenced in the above snippet: error C2668: 'log' : ambiguous call to overloaded function 1> c:\program files\microsoft visual studio 8\vc\include\math.h(553): could be 'long double log(long double)' 1> c:\program files\microsoft visual studio 8\vc\include\math.h(505): or 'float log(float)' 1> c:\program files\microsoft visual studio 8\vc\include\math.h(114): or 'double log(double)' 1> while trying to match the argument list '(int)' The errors are being flagged in cmath and not my own header file. No amount of hacking and working around can stop that - I usually just end up with new errors. If I typecast log(x) to be (double)log(x) there's no change, but if I do:
double log(x)
I'm told double was unexpected (error C2062). I can't make it work, can anybody help me out? Thanks, ukdeveloper.

Share this post


Link to post
Share on other sites
Advertisement
Guest Anonymous Poster
log((double)x)

Share this post


Link to post
Share on other sites
If you are going to do it that way, try using the function frexp instead. Something like this:
    int nextpowerof2(int x)
{
int n;
frexp( (double)x, &n );
return n+1;
}
Or, it may be faster and more accurate to do it this way:
    int nextpowerof2( int x )
{
int n = 1;
while ( n < x )
{
n *= 2;
}
return n;
}

Share this post


Link to post
Share on other sites
The compiler doesn't know whether you want to promote 2 (an int) to a float or a double.
A MUCH MUCH more efficient way of doing what you require is:
!!!Warning: code below assumes 32-bit int's!!!
int nextpowerof2(int x)
{
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return ++x;
}
[smile]

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

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

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!