Math.log()
Math.log() 靜態方法返回一個數字的自然對數(以 e 為底)。也就是說,對於所有大於 0 的 x,Math.log(x) 等於 ln(x),即滿足 e^y = x 的唯一 y。
試一試
function getBaseLog(x, y) {
return Math.log(y) / Math.log(x);
}
// 2 x 2 x 2 = 8
console.log(getBaseLog(2, 8));
// Expected output: 3
// 5 x 5 x 5 x 5 = 625
console.log(getBaseLog(5, 625));
// Expected output: 4
語法
js
Math.log(x)
引數
x-
大於或等於 0 的數字。
返回值
描述
由於 log() 是 Math 的一個靜態方法,您總是使用 Math.log() 來呼叫它,而不是作為您建立的 Math 物件的某個方法(Math 不是一個建構函式)。
如果您需要 2 或 10 的自然對數,可以使用常量 Math.LN2 或 Math.LN10。如果您需要以 2 或 10 為底的對數,請使用 Math.log2() 或 Math.log10()。如果您需要以其他底數為底的對數,請使用 Math.log(x) / Math.log(otherBase),如以下示例所示;您可能希望預先計算 1 / Math.log(otherBase),因為在 Math.log(x) * constant 中進行乘法運算要快得多。
請注意,非常接近 1 的正數可能會由於精度損失而導致其自然對數不夠精確。在這種情況下,您可能需要改用 Math.log1p。
示例
使用 Math.log()
js
Math.log(-1); // NaN
Math.log(-0); // -Infinity
Math.log(0); // -Infinity
Math.log(1); // 0
Math.log(10); // 2.302585092994046
Math.log(Infinity); // Infinity
使用不同底數的 Math.log()
以下函式返回 y 以 x 為底的對數(即,):
js
function getBaseLog(x, y) {
return Math.log(y) / Math.log(x);
}
如果您執行 getBaseLog(10, 1000),由於浮點數舍入,它將返回 2.9999999999999996,但仍然非常接近實際答案 3。
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-math.log |
瀏覽器相容性
載入中…