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

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.

I Did Use This And It Worked Well