Math.log2()

Math.log2() 関数は、数値の 2 を底とした対数を返します。

x > 0 , Math.log2 ( x ) = log 2 ( x ) = the unique y such that 2 y = x \forall x > 0, \mathtt{\operatorname{Math.log2}(x)} = \log_2(x) = \text{the unique} ; y ; \text{such that} ; 2^y = x

試してみましょう

構文

Math.log2(x)

引数

x

数値です。

返値

与えられた数値の 2 を底とした対数です。数値が負の数であった場合、 NaN が返されます。

解説

x の値が 0 未満であった場合、返値は常に NaN です。

log2()Math の静的メソッドであるため、生成した Math オブジェクトのメソッドとしてではなく、常に Math.log2() として使用するようにしてください (Math はコンストラクターではありません)。

この関数は Math.log(x) / Math.log(2) と同等です。 log2(e) には定数 Math.LOG2E を使用してください (これは 1 / Math.LN2 です。)

ポリフィル

このポリフィルは Math.log2 関数をエミュレートします。なお、これは入力値によっては不正確な値を返すので (1 << 29 など)、ビットマスクで使用するときは Math.round() で囲んでください。

js
if (!Math.log2)
  Math.log2 = function (x) {
    return Math.log(x) * Math.LOG2E;
  };

Math.log2() の使用

js
Math.log2(3); // 1.584962500721156
Math.log2(2); // 1
Math.log2(1); // 0
Math.log2(0); // -Infinity
Math.log2(-2); // NaN
Math.log2(1024); // 10

仕様書

Specification
ECMAScript Language Specification
# sec-math.log2

ブラウザーの互換性

BCD tables only load in the browser

関連情報