1. Introduction

In this short tutorial, we'll learn how to calculate logarithms in Java. We'll cover both common and natural logarithms as well as logarithms with a custom base.

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:

{\displaystyle \log _{b}(x)=y\quad }exactly if{\displaystyle \quad b^{y}=x.}

3. Calculating Common Logarithms

Logarithms of base 10 are called 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

Logarithms of the base e are called 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

To calculate a logarithm with custom base in Java, we use the following identity:

{\displaystyle \log _{b}x={\frac {\log _{10}x}{\log _{10}b}}={\frac {\log _{e}x}{\log _{e}b}}.\,}

@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

In this tutorial, we've learned how to calculate logarithms in Java.

As always, the source code is available over on GitHub.