在 Java 中計算對數
Sheeraz Gul
2022年4月27日
本教程將演示如何使用 Math.log
函式在 Java 中計算對數。
在 Java 中使用 Math.log
計算給定值的對數
在 Java 中,java.lang.Math
庫具有函式 Math.log()
來計算給定值的對數。輸入值可以是雙精度、整數或浮點數,並返回雙精度值。
我們必須確保數字不是負數、零或無窮大; 否則,輸出將不是雙精度資料型別。
下面的例子展示了 Java 中 Math.log
的使用。
import java.lang.Math;
class Java_Log {
public static void main(String args[])
{
double p = -4.3;
double q = 6.0 / 0;
double r = 0;
double s = 130.333;
double u = 130.333/30;
int v = 5;
float w = 34;
// The negative double in the Math.log function will output: NaN
System.out.println("The Output for Negative Integer:");
System.out.println(Math.log(p));
// The positive infinity in the Math.log function will output: Infinity
System.out.println("The Output for Positive Infinity:");
System.out.println(Math.log(q));
// The positive zero in the Math.log function will output: - Infinity
System.out.println("The Output for Zero:");
System.out.println(Math.log(r));
//The positive double argument in the Math.log function will output: logarithm answer
System.out.println("The Output for positive double:");
System.out.println(Math.log(s));
//The positive double argument in the Math.log function will output: logarithm answer
System.out.println("The Output for Positive double in division form:");
System.out.println(Math.log(u));
//The positive integer argument in the Math.log function will output: logarithm answer
System.out.println("The Output for Positive Integer:");
System.out.println(Math.log(v));
//The positive integer float argument in the Math.log function will output: logarithm answer
System.out.println("The Output for Positive float:");
System.out.println(Math.log(w));
}
}
輸出:
The Output for Negative Integer:
NaN
The Output for Positive Infinity:
Infinity
The Output for Zero:
-Infinity
The Output for positive double:
4.870092713769228
The Output for Positive double in division form:
1.468895332107073
The Output for Positive Integer:
1.6094379124341003
The Output for Positive float:
3.5263605246161616
上面的程式碼計算每種資料型別的對數,並返回雙精度、整數、浮點數、無窮大和零輸入值的輸出值。
Author: Sheeraz Gul
Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.
LinkedIn Facebook