Wednesday, February 10, 2010

Finding the logarithm of any base in Java

Unfortunately, the only methods in Java that compute the logarithm of a number are java.lang.Math.log and java.lang.Math.log10. The former returns the natural logarithm (base e) of the number and the latter returns the base 10 logarithm of the number.

To calculate the logarithm of any base in Java, we thus have to use the following method:

public double logOfBase(int base, int num) {
    return Math.log(num) / Math.log(base);
}

Why does it work?


Let's say we want to find the base 2 logarithm of 32 (method call would be logOfBase(2, 32)), which is 5.


Now if we divide the base e logarithm (ln) of our number (32) by the base e logarithm of our base (2), we get the answer we wanted: