萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript Math.asin() 方法詳解:計算反正弦值

Math.asin() 方法簡介

Math.asin(x) 返回數字 x 的反正弦值(反正弦),結果以弧度表示,範圍為 [-π/2, π/2](即 -90° 到 90°)。

語法

Math.asin(x)

參數與返回值

  • x:必須在 [-1, 1] 範圍內的數字
  • 返回:-π/2 到 π/2 之間的弧度值;若 x 超出範圍,返回 NaN

核心示例

// 標準值
console.log(Math.asin(-1));   // -1.5707963267948966 (-π/2, -90°)
console.log(Math.asin(0));    // 0 (0°)
console.log(Math.asin(1));    // 1.5707963267948966 (π/2, 90°)
console.log(Math.asin(0.5));  // 0.5235987755982989 (π/6, 30°)
console.log(Math.asin(-0.5)); // -0.5235987755982989 (-π/6, -30°)

// 邊界與異常
console.log(Math.asin(1.1));    // NaN
console.log(Math.asin(null));   // 0 (null → 0)
console.log(Math.asin('0.5'));  // 0.5235987755982989
console.log(Math.asin('abc'));  // NaN

弧度轉角度

const radToDeg = rad => rad * 180 / Math.PI;

console.log(radToDeg(Math.asin(0.5)));   // 30
console.log(radToDeg(Math.asin(-0.5)));  // -30
console.log(radToDeg(Math.asin(1)));     // 90

實戰應用場景

1. 直角三角形求銳角

// 已知對邊 a、斜邊 c,求角度 θ
function angleFromOppositeHypotenuse(opposite, hypotenuse) {
    const ratio = opposite / hypotenuse;
    // 限制範圍防止浮點誤差
    const clamped = Math.max(-1, Math.min(1, ratio));
    return Math.asin(clamped);
}

const angleRad = angleFromOppositeHypotenuse(3, 5);
console.log(radToDeg(angleRad)); // 36.87°

2. 向量與 X 軸夾角(二維)

// 向量 (x,y) 與正 X 軸夾角
// 注意:asin 只能得出 -90°~90°,無法區分象限
// 推薦使用 Math.atan2(y, x) 獲得完整 -180°~180°
function angleWithXAxis(x, y) {
    const len = Math.hypot(x, y);
    if (len === 0) return 0;
    // 僅當向量在右半平面 (x>0) 時 asin 可用
    return Math.asin(y / len);
}

// 正確通用做法
function angleWithXAxisCorrect(x, y) {
    return Math.atan2(y, x); // 返回 -π 到 π
}

3. 簡諧運動相位計算

// 簡諧運動:x = A * sin(ωt + φ)
// 已知位移 x、振幅 A,求相位
function phaseFromDisplacement(x, amplitude) {
    const ratio = x / amplitude;
    return Math.asin(Math.max(-1, Math.min(1, ratio)));
}

asin vs atan2:關鍵區別

特性Math.asin(y/r)Math.atan2(y, x)
返回範圍[-π/2, π/2] (-90°~90°)[-π, π] (-180°~180°)
象限判斷無(僅右半平面正確)自動根據 x,y 符號判斷
參數比值 y/r分量 y, x
適用場景已知對邊/斜邊比值已知向量分量(推薦通用)

常見錯誤避坑

  1. 未限制輸入範圍:浮點誤差導致 ratio > 1,產生 NaN,必須 clamp
  2. 用於全平面角度計算:asin 無法區分第二、三象限,**向量角度請用 Math.atan2(y, x)**
  3. 混淆弧度/角度:返回弧度,UI 顯示需轉換

相關方法

  • Math.acos(x) - 反餘弦,範圍 [0, π]
  • Math.atan(x) - 反正切,範圍 [-π/2, π/2]
  • Math.atan2(y, x) - **首選** 全平面向量角度
  • Math.sin(x) - 正弦(正向操作)

Math.asin() 適用於「已知正弦值求角度」的場景,但處理二維向量角度時,永遠優先使用 Math.atan2() 以獲得正確象限。

copyright © 萬盛學電腦網 all rights reserved