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()
は静的メソッドで、各引数の二乗の合計値の平方根を返します。
試してみましょう
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
構文
Math.hypot()
Math.hypot(value1)
Math.hypot(value1, value2)
Math.hypot(value1, value2, /* …, */ valueN)
引数
value1
, …,valueN
-
数値です。
返値
解説
直角三角形の斜辺や、複素数の大きさを計算するには 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() の使用
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 GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
hypot |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support