Calculating Logarithms in Java – 在Java中计算对数

最后修改: 2019年 8月 15日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

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.

在这个简短的教程中,我们将学习如何在Java中计算对数。我们将介绍普通对数和自然对数,以及自定义基数的对数。

2. Logarithms

2.对数

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

3.普通对数的计算

Logarithms of base 10 are called common logarithms.

以10为底的对数被称为普通对数。

To calculate a common logarithm in Java we can simply use the Math.log10() method:

要在Java中计算一个普通的对数,我们可以简单地使用Math.log10()方法。

@Test
public void givenLog10_shouldReturnValidResults() {
    assertEquals(Math.log10(100), 2);
    assertEquals(Math.log10(1000), 3);
}

4. Calculating Natural Logarithms

4.计算自然对数

Logarithms of the base e are called natural logarithms.

e为底的对数被称为自然对数。

To calculate a natural logarithm in Java we use the Math.log() method:

要在Java中计算自然对数,我们使用Math.log()方法。

@Test
public void givenLog10_shouldReturnValidResults() {
    assertEquals(Math.log(Math.E), 1);
    assertEquals(Math.log(10), 2.30258);
}

5. Calculating Logarithms With Custom Base

5.用自定义基数计算对数

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

要在Java中计算带有自定义基数的对数,我们使用下面的标识。

{\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

6.结语

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

在本教程中,我们已经学会了如何在Java中计算对数。

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

像往常一样,源代码可在GitHub上获得