跳到主要内容

Java Math log() 方法

log() 方法计算指定值的自然对数(以 e 为底)并返回。

示例

class Main {
public static void main(String[] args) {

// 计算 9 的 log()
System.out.println(Math.log(9.0));


}
}

// 输出:2.1972245773362196

Math.log() 的语法

log() 方法的语法是:

Math.log(double x)

这里,log() 是一个静态方法。因此,我们直接使用类名 Math 调用方法。

log() 参数

  • x - 需要计算对数的值

log() 返回值

  • 返回 x 的自然对数(即 ln a
  • 如果参数是 NaN 或小于零,则返回 NaN
  • 如果参数是正无穷大,则返回正无穷大
  • 如果参数是零,则返回负无穷大

示例:Java Math.log()

class Main {
public static void main(String[] args) {

// 计算 double 值的 log()
System.out.println(Math.log(9.0)); // 2.1972245773362196

// 计算零的 log()
System.out.println(Math.log(0.0)); // -Infinity

// 计算 NaN 的 log()
double nanValue = Math.sqrt(-5.0);
System.out.println(Math.log(nanValue)); // NaN

// 计算无穷大的 log()
double infinity = Double.POSITIVE_INFINITY;
System.out.println(Math.log(infinity)); // Infinity

// 计算负数的 log()
System.out.println(Math.log(-9.0)); // NaN

}
}

推荐教程