# Base-2 and Base-N logarithm calculation in Java

I was surprised today to see that the Math package does not provide a method that the calculation of an arbitrary base logarithm, even though it provides a log10() method for base-10 logarithms.

One can easily calculate the logarithm of any base using the following simple equation: Where logk is the function that returns the base-k logarithm of a number, and it can be any real number.

In terms of Java it can be written like this:

public class Logarithm
{
public static double logb( double a, double b )
{
return Math.log(a) / Math.log(b);
}

public static double log2( double a )
{
return logb(a,2);
}

public static void main( String[] args )
{
System.out.println(log2(100));
}
}

This entry was posted in Uncategorized. Bookmark the permalink.

### 5 Responses to Base-2 and Base-N logarithm calculation in Java

1. Troy says:

But when I use this to find log(10)1000 = 3, I get 2.99999999 rather than 3. I would like to use this method without errors like this. Here is the code I used:

public class logarithm {

public static double logb( double a, double b )
{
return Math.log(a) / Math.log(b);
}

public static double log2( double a )
{
return logb(a,2);
}

public static void main( String[] args )
{
System.out.println(logb(1000,10));
}

}

2. Lii says:

This is nice. It could also be a good idea to save the result of Math.log(2) as constant to avoid recalculating it each time log2 is called.

3. John says:

but this function returns NaN , sometimes. For example log2(0,3).

• Rishaan says:

John
You said: ‘log2(0,3)’
I’m going to assume you meant logb(0,3) as in log (base 0) of 3
That is undefined as you can’t have a log of base 0.

But if you meant log2(0), as in log (base 2) of 0
Then that is also undefined as log of 0 is undefined.

4. ratatat says:

I Did Use This And It Worked Well