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.

Math.log() は静的メソッドで、数値の(e を底とした)自然対数を返します。

x>0,𝙼𝚊𝚝𝚑.𝚕𝚘𝚐(𝚡)=ln(x)=the unique y such that ey=x\forall x > 0,\;\mathtt{\operatorname{Math.log}(x)} = \ln(x) = \text{the unique } y \text{ such that } e^y = x

試してみましょう

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 以上の数値です。

返値

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() の使用

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() の使用

以下の関数は、 x を底とした y の対数を返します (すなわち logxy\log_x y)。

js
function getBaseLog(x, y) {
  return Math.log(y) / Math.log(x);
}

getBaseLog(10, 1000) を実行すると、実際の答えが 3 であるのに対し、浮動小数点の丸め処理により近似値の 2.9999999999999996 を返します。

仕様書

Specification
ECMAScript® 2025 Language Specification
# sec-math.log

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
log

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

関連情報