Base de conocimientosCentro de exámenes
ESEspañol
Elegir idioma13

CKTIS / JavaScript

Math.hypot: longitud euclídea

Math.hypot convierte cualquier número de componentes a Number y calcula de forma estable la raíz de su suma de cuadrados.

Versión: ECMAScript 2015 onward; example target: Node.js 24.22.2

Sintaxis

Math.hypot(...values)

Math.hypot(...values) devuelve √(x₁² + x₂² + …) como Number no negativo. Sin argumentos devuelve +0 y los signos no afectan la longitud. Su escalado evita desbordamiento y subdesbordamiento prematuros mejor que Math.sqrt(x*x + y*y).

Cada argumento pasa por ToNumber en orden. Symbol o BigInt lanza TypeError incluso junto a un infinito. Tras convertir, ±Infinity da Infinity incluso con NaN; sin infinito, cualquier NaN da NaN. Las cadenas numéricas se convierten y los objetos pueden ejecutar código.

No es constructor y es estándar desde ECMAScript 2015. Para magnitud vectorial o distancia Math.hypot(x2-x1, y2-y1) en varias dimensiones. El Number sigue sujeto a límites de precisión IEEE 754.

Ejemplos

console.log(Math.hypot(3, 4), Math.hypot());
console.log(Object.is(Math.hypot(-0), 0));
const stable = Math.hypot(3e200, 4e200);
const naive = Math.sqrt((3e200) ** 2 + (4e200) ** 2);
console.log(stable, Number.isFinite(stable), naive);
console.log(Math.hypot(Infinity, NaN), Number.isNaN(Math.hypot(NaN, 1)));
try { Math.hypot(Infinity, 1n); } catch (error) { console.log(error instanceof TypeError); }

Resultado

5 0
true
4.9999999999999995e+200 true Infinity
Infinity true
true

Fuentes