WORKING OUT LOGARITHMS It's no surprise that Java can handle logarithms, but there's a surprising gap in the API. Armed with the following information, a small barrier is removed when working with numbers in Java. Sun's J2SE provides a single log method, double java.lang.Math.log(double), that is easy to use. The following code: double x = Math.log(5); is equivalent to the mathematical equation: x = ln 5 or x = loge5 where e is the Napierian or natural number. What if you want a logarithm with a different base? There is no method available to determine the base-10 log of a number or the base-2 log. However, both are frequently used in logarithms. The solution is to cast your mind back to school mathematics and the logarithmic equation: logx(y) = loge(x) / loge(y) Implement this as a simple piece of Java: package com.generationjava.math; public class Logarithm { static public double log(double value, double base) { return Math.log(value) / Math.log(base); } } Finding the base-10 logarithm of 100 becomes as simple as: double log = Logarithm.log(100, 10); // log is 2.0 The base-2 logarithm of 512 is: double log = Logarithm.log(512, 2); // log is 9.0 The following two simple methods are also useful: static public double log2(double value) { return log(value, 2.0); } static public double log10(double value) { return log(value, 10.0); } ---------------------------------------