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 2015年7月.
Math.log() は静的メソッドで、数値の(e を底とした)自然対数を返します。
試してみましょう
function getBaseLog(x, y) {
return Math.log(y) / Math.log(x);
}
// 2 x 2 x 2 = 8
console.log(getBaseLog(2, 8));
// 予想される結果: 3
// 5 x 5 x 5 x 5 = 625
console.log(getBaseLog(5, 625));
// 予想される結果: 4
構文
Math.log(x)
引数
x-
0 以上の数値です。
返値
x の(e を底とした)自然対数です。 x が ±0 の場合は、 -Infinity を返します。 x < 0 の場合は、 NaN が返されます。
解説
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> |
ブラウザーの互換性
Loading…