【问题标题】:Using log base 10 in a formula in Java在 Java 的公式中使用 log base 10
【发布时间】:2012-11-21 13:28:11
【问题描述】:

我正在尝试编写一个 Java 程序,该程序可以获取值并将它们放入涉及 log base 10 的公式中。

如何在 Java 中计算 log10

【问题讨论】:

  • Math.log(x) / Math.log(10)
  • @Mysticial:这是一个答案,不是吗? (而不是评论。)
  • 欲了解更多信息,请查看“改变碱基”公式。

标签: java logarithm


【解决方案1】:

下面的完整示例可能会对您有所帮助

public class Log10Math {
    public static void main(String args[]) {
        // Method returns logarithm of number argument with base ten(10);
        short shortVal = 10;
        byte byteVal = 1;
        double doubleVal = Math.log10(byteVal);

        System.out.println("Log10 Results");
        System.out.println(Math.log10(1));
        System.out.println(doubleVal);
        System.out.println(Math.log10(shortVal));
    }
}

输出

Log10 Results
0.0
0.0
1.0

【讨论】:

  • 遵循 Java 命名约定,变量名以小写开头。
  • @MCEmperor,感谢您的输入,更新了我的答案。
  • 这样更好! ;-)
【解决方案2】:
Math.log10(x)

浮点数就足够了。

如果你需要以 10 为底的整数对数,并且可以使用第三方库,Guava 提供了IntMath.log10(int, RoundingMode)。 (披露:我为 Guava 做出了贡献。)

【讨论】:

    【解决方案3】:

    在Java中我们可以使用日志功能。 (int) 数学.log(val); int 是一种将其转换为 this 的类型,您将在其中存储您的答案。

    【讨论】:

      【解决方案4】:

      看起来Java实际上有一个log10函数:

      Math.log10(x)
      

      否则,只使用数学:

      Math.log(x) / Math.log(10)
      

      http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html

      【讨论】:

      • Java 1.5 已经过时六年了。我更新了答案以引用当前的内容。
      • answer of Louis 4 分钟后正好包含这个答案。这有点可惜。
      猜你喜欢
      • 1970-01-01
      • 2020-08-25
      • 2022-10-23
      • 2017-06-09
      • 2014-01-14
      • 2021-10-12
      • 2022-10-15
      • 2012-03-22
      • 1970-01-01
      相关资源
      最近更新 更多