Wednesday, June 22, 2011

Handy function for Log Base 2 and nearest power of two in C++

Since there is no direct way to find Logarithm Base 2 of a number in C++, the given function in C++, would come handy in several situations.

// Essential Header file - math.h

// Log2 Function

double Log2(double in)
{
return log(in)/ log(double(2));
}

Let us use the above function for calculating nearest power of two easily, as given below.

int NearestPowerOfTwo(int in)
{
return pow(2, ceil(Log2(in)));
}

2 comments:

  1. Couldn't you speed this up by just precomputing log(double(2)) might not seem like much but it certainly can be when computing millions/billions of times in a look in scientific computing and it's basically "free" :) . -D , texas, usa

    ReplyDelete
  2. I meant loop :) , -D, texas, usa

    ReplyDelete