How to calculate log2 of any number?

10 09 2008


Few days back, my client give me one 4 inch long and 2 inch wide math equation to implement. Well, the equation contains log2 and while coding, my Visual Assist was not auto filling the log2 function. It just underlines the function by redline. When i checked the MSDN, I was shocked that log2 is not available as the part of standard library. So how to get the log2 of a number?


Log2 is pretty simple, nah? Its implementation as follows,

#include <math.h>
...
// Calculates log2 of number.
double Log2( double n )
{
    // log(n)/log(2) is log2.
    return log( n ) / log( 2 );
}


Its silly function, But I still blame standard library for not including it. Because I’m lazy. 😉


Targeted Audience – Beginners.

Advertisements

Actions

Information

One response

30 05 2009
Stu Kennedy

the calculation line in the function should read

return log( n ) / log( 2.0 );

because log(2) is ambiguous; the C++ compiler doesn’t realise it’s a double!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s




%d bloggers like this: