Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / JavaScript

Math.acos: arcocoseno

Math.acos restituisce l’arcocoseno di un numero in radianti, con dominio reale da -1 a 1 e risultato da 0 a π.

Versione: ECMAScript 1 onward; example target: Node.js 24.22.2

Sintassi

Math.acos(x)

Math.acos(x) applica ToNumber e calcola il valore principale del coseno inverso. Per x in [-1, 1], il risultato è in [0, π]: acos(1) è +0, acos(0) circa π/2 e acos(-1) circa π. Il Number è generalmente approssimato.

Un valore finito fuori [-1, 1], ±Infinity, NaN o argomento mancante produce NaN. Una stringa numerica viene convertita, ma Symbol o BigInt genera TypeError; un oggetto può eseguire valueOf o toString. L’approssimazione può dipendere dall’implementazione.

Non è un costruttore ed è standard da ECMAScript 1. Il risultato è in radianti; gradi = radians * 180 / Math.PI. Per un angolo da prodotto scalare, limitare il quoziente a [-1, 1] affinché un piccolo errore floating-point non produca NaN.

Esempi

function angleBetween([ax, ay], [bx, by]) {
  const quotient = (ax * bx + ay * by) / (Math.hypot(ax, ay) * Math.hypot(bx, by));
  return Math.acos(Math.max(-1, Math.min(1, quotient)));
}
const angle = angleBetween([1, 0], [0, 1]);
console.log(angle.toFixed(6), (angle * 180 / Math.PI).toFixed(1));
console.log(Math.acos(1), Math.acos(-1).toFixed(6));
console.log(Number.isNaN(Math.acos(1.1)), Number.isNaN(Math.acos()));
try { Math.acos(1n); } catch (error) { console.log(error instanceof TypeError); }

Risultato

1.570796 90.0
0 3.141593
true true
true

Fonti