Base-2 and Base-N logarithm calculation in Java

January 9th, 2010
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:

log.png

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));
}
}

Leave a Reply