Math.hypot()

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.hypot() は静的メソッドで、各引数の二乗の合計値の平方根を返します。

𝙼𝚊𝚝𝚑.𝚑𝚢𝚙𝚘𝚝(v1,v2,,vn)=i=1nvi2=v12+v22++vn2\mathtt{\operatorname{Math.hypot}(v_1, v_2, \dots, v_n)} = \sqrt{\sum_{i=1}^n v_i^2} = \sqrt{v_1^2 + v_2^2 + \dots + v_n^2}

試してみましょう

console.log(Math.hypot(3, 4));
// Expected output: 5

console.log(Math.hypot(5, 12));
// Expected output: 13

console.log(Math.hypot(3, 4, 5));
// Expected output: 7.0710678118654755

console.log(Math.hypot(-5));
// Expected output: 5

構文

js
Math.hypot()
Math.hypot(value1)
Math.hypot(value1, value2)
Math.hypot(value1, value2, /* …, */ valueN)

引数

value1, …, valueN

数値です。

返値

与えられた引数の二乗和の平方根を返します。引数のいずれかが ±Infinity の場合、 Infinity を返します。 それ以外の場合、引数の少なくとも 1 つが NaN であるか、または NaN に変換された場合、NaN を返します。引数が指定されていない場合、またはすべての引数が ±0 の場合、0 を返します。

解説

直角三角形の斜辺や、複素数の大きさを計算するには Math.sqrt(v1*v1 + v2*v2) という公式を用い、ここで v1 と v2 は三角形の辺の長さであったり、複素数の実数と複素数部分であったりします。二次元またはそれ以上の次元における対応する距離は、 Math.sqrt(v1*v1 + v2*v2 + v3*v3 + v4*v4) のように平方根の下にさらに多くの平方を足すことで計算できます。

この関数はこの計算をより簡単に、より高速に行います。 Math.hypot(v1, v2) または Math.hypot(v1, /* …, */, vN) を呼び出すだけです。

Math.hypot はまた、数値が非常に大きい場合のオーバーフロー/アンダーフローの問題を回避します。 JS で表現できる最大の数は Number.MAX_VALUE で、これは約 10308 です。数字の大きさが約 10154 よりも大きい場合、その 2 乗を取ると無限大になります。例えば、 Math.sqrt(1e200*1e200 + 1e200*1e200) = Infinity です。代わりに hypot() を使うと、 Math.hypot(1e200, 1e200) = 1.4142...e+200 となり、より良い答えが得られます。これは非常に小さな数の場合にも当てはまります。 Math.sqrt(1e-200*1e-200 + 1e-200*1e-200) = 0 ですが、 Math.hypot(1e-200, 1e-200) = 1.4142...e-200 となります。

引数が 1 つの場合、 Math.hypot()Math.abs() と同等です。 Math.hypot.length は 2 であり、これは少なくとも 2 つの引数で扱うことを示す弱いシグナルです。

hypot()Math の静的メソッドなので、常に Math.hypot() として使用し、自分で Math オブジェクトを生成してそのメソッドとして使用しないでください。 (Math にはコンストラクターがありません)。

Math.hypot() の使用

js
Math.hypot(3, 4); // 5
Math.hypot(3, 4, 5); // 7.0710678118654755
Math.hypot(); // 0
Math.hypot(NaN); // NaN
Math.hypot(NaN, Infinity); // Infinity
Math.hypot(3, 4, "foo"); // NaN, +'foo' => NaN なので
Math.hypot(3, 4, "5"); // 7.0710678118654755, +'5' => 5
Math.hypot(-3); // 3、Math.abs(-3) と同じ

仕様書

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

ブラウザーの互換性

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
hypot

Legend

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

Full support
Full support

関連情報