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:

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

This entry was posted in Uncategorized. Bookmark the permalink.

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

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>