Java log 函数

Java log 函数是 Math 库函数之一,用于计算给定数字以 E 为底的对数值。

Java Math.log 函数的基本语法如下所示。该函数将接受一个正双精度值作为参数,并返回指定表达式的对数值。

static double log(double number); //Return Type is Double

// In order to use in program: 
Math.log(double number);

Number:可以是 double 或一个有效的数值表达式,您想为其查找对数值。

  • 如果 number 参数是一个正双精度值,Math.log 函数将返回其对数。
  • 如果 number 参数是负双精度值或非数字 (NaN),Math.log 函数将返回 NaN。
  • 当 number 参数为正无穷大时,它将返回正无穷大的结果。如果 number 参数为正零或负零,它将返回负无穷大的结果。

Java math log 函数示例

Math.log 函数允许查找指定表达式或单个双精度值的对数值。在此 Java 程序中,我们将查找相同的值并显示输出。

首先,我们声明了一个 Double 类型的变量并直接对其表达式进行操作。对于接下来的两行,我们直接对正双精度值使用了 Math.log 函数。

在最后两行中,我们直接对负双精度值使用了 log 函数。正如您从截图中看到的,它为负值返回 NaN。

// Example
package MathFunctions;

public class LogMethod {
	public static void main(String[] args) {
		double a = Math.log(10.90 + 15.10 - 22.50 + 1.50);
		System.out.println("Logarithmic Value = " + a);	

		System.out.println("\nLogarithmic Value of Zero: " + Math.log(0));
		
		System.out.println("\nLogarithmic Value of Positive Number: " + Math.log(1));
		System.out.println("Logarithmic Value of Positive Number: " + Math.log(10.95));
		
		System.out.println("\nLogarithmic Value of Negative Number: " + Math.log(-8.70));
		System.out.println("Logarithmic Value of Negative Number: " + Math.log(-5.00));		
	}
}
Java math log Function Example

Java math log 函数在数组上的应用

在此 log math 程序中,我们展示了如何查找批量数据的对数值。在这里,我们将声明一个 double 类型的 数组,并查找数组中每个元素的对数值。

package MathFunctions;

public class LogMethodOnArrays {
	public static void main(String[] args) {
		
		double [] logArray = {2.35, 4.98, -8.41, -9.5987, -0, 12.38, 14.4897};

		for (int i = 0; i < logArray.length; i++) {
			System.out.format("%.4f\n", Math.log(logArray[i]));
		}
	}
}
0.8544
1.6054
NaN
NaN
-Infinity
2.5161
2.6734

首先,我们声明了一个 double 类型的数组并为其分配了一些随机值。

double [] logArray = {2.35, 4.98, -8.41, -9.5987, -0, 12.38, 14.4897};

接下来,我们使用 For 循环 来迭代数组。在 For 循环内部,我们将 i 初始化为 0。然后,编译器将检查条件 (i < logArray.length)。当条件为 True 时,将执行 for 循环内的语句。

提示:logArray.length 用于查找数组的长度。

for (int i = 0; i < logArray.length; i++) {

下面的 System.out.format 语句将打印输出。如果您观察代码片段,我们在 System.out.format 语句中直接使用了 Math 函数。在这里,Javac 将调用 Math.log 方法 (static double log(double number)) 来查找相应数字的对数值。

注意:如果您想查找单个项的对数值,请使用:Math.log(myArray[index_position])

Java log 函数在 ArrayList 上的应用示例

在此 程序 中,我们声明了一个 double 类型的 ArrayList,并使用 log 函数查找列表中元素的对数值。

首先,我们声明了一个 double 类型的 ArrayList 并为其分配了一些随机值。接下来,我们使用 For 循环迭代 ArrayList 中的双精度值。

下面的 Java System.out.println 语句打印输出。在这里,编译器将调用 Math.log 方法(static double log(double x))来查找相应数字的对数值。

package MathFunctions;

import java.util.ArrayList;

public class LogMethodOnArrayList {
	public static void main(String[] args) {
		
		ArrayList<Double> logList = new ArrayList<Double>(5);
		logList.add(12.998);
		logList.add(-1480.05);
		logList.add(0.876);
		logList.add(0.01);
		logList.add(20.98);
		logList.add(-8.89);
		
		for (double x : logList) {
			System.out.println(Math.log(x));
		}
	}
}
2.564795499472157
NaN
-0.13238918804574562
-4.605170185988091
3.043569602968151
NaN