java-logarithms
Calculating Logarithms in Java
1. Introduction
2. Logarithms
A logarithm is a mathematical formula representing the power to which we must raise a fixed number (the base) to produce a given number.
In its simplest form, it answers the question: How many times do we multiply one number to get another number?
We can define logarithm by the following equation:
exactly if
3. Calculating Common Logarithms
To calculate a common logarithm in Java we can simply use the Math.log10() method:
@Test
public void givenLog10_shouldReturnValidResults() {
assertEquals(Math.log10(100), 2);
assertEquals(Math.log10(1000), 3);
}
4. Calculating Natural Logarithms
To calculate a natural logarithm in Java we use the Math.log() method:
@Test
public void givenLog10_shouldReturnValidResults() {
assertEquals(Math.log(Math.E), 1);
assertEquals(Math.log(10), 2.30258);
}
5. Calculating Logarithms With Custom Base
@Test
public void givenCustomLog_shouldReturnValidResults() {
assertEquals(customLog(2, 256), 8);
assertEquals(customLog(10, 100), 2);
}
private static double customLog(double base, double logNumber) {
return Math.log(logNumber) / Math.log(base);
}
6. Conclusion
As always, the source code is available over on GitHub.