CKTIS / JavaScript
Math.sqrt: radice quadrata
Math.sqrt converte l’argomento in Number e restituisce la radice quadrata non negativa, o NaN per un valore negativo.
Versione: ECMAScript 1 onward; example target: Node.js 24.22.2
Sintassi
Math.sqrt(x)Math.sqrt(x) applica ToNumber. Per un valore positivo finito restituisce la rappresentazione Number della radice matematica; sqrt(9) è 3, mentre il risultato per 2 è un’approssimazione binary64 del valore irrazionale sqrt(2). +Infinity resta Infinity.
+0 restituisce +0 e -0 restituisce -0, anche se la visualizzazione normale spesso nasconde il segno. Un valore negativo diverso da -0, incluso -Infinity, dà NaN; anche NaN e l’argomento mancante. Una stringa numerica viene convertita, mentre Symbol o BigInt genera TypeError.
La funzione esiste da ECMAScript 1 e non è un costruttore. Serve per lunghezze e distanze, ma preferisci Math.hypot(a, b) a sqrt(a*a + b*b) per limitare overflow e underflow intermedi. Elevare al quadrato una radice approssimata non riproduce sempre l’input bit per bit.
Esempi
console.log(Math.sqrt(9), Math.sqrt(2).toFixed(6));
console.log(Object.is(Math.sqrt(-0), -0), Math.sqrt(Infinity));
console.log(Number.isNaN(Math.sqrt(-1)), Number.isNaN(Math.sqrt()));
console.log(Math.sqrt("81"));
try { Math.sqrt(9n); } catch (error) { console.log(error instanceof TypeError); }Risultato
3 1.414214 true Infinity true true 9 true
Math.sqrt → 3, 1.414214, preserved -0, and errors