Math.log()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
試してみましょう
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
構文
Math.log(x)
引数
x
0 以上の数値です。
返値
解説
log()
は Math
の静的メソッドであるため、生成した Math
オブジェクトのメソッドとしてではなく、常に Math.log()
として使用するようにしてください (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() の使用
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() の使用
以下の関数は、 x
を底とした y
の対数を返します (すなわち )。
function getBaseLog(x, y) {
return Math.log(y) / Math.log(x);
}
getBaseLog(10, 1000)
を実行すると、実際の答えが 3 であるのに対し、浮動小数点の丸め処理により近似値の 2.9999999999999996
を返します。
仕様書
Specification |
---|
ECMAScript® 2026 Language Specification # sec-math.log |