Wednesday, February 2, 2011

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:


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

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:

No comments:

Post a Comment

Chitika