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 log*k* 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));

}

}

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

}

}

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.

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