Sign in to follow this  
ukdeveloper

Unity Problem with log functions

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this