Math.atan(x) 返回數字 x 的反正切值,結果以弧度表示,範圍為 [-π/2, π/2](-90° 到 90°)。
Math.atan(x)
console.log(Math.atan(0)); // 0
console.log(Math.atan(1)); // 0.785398... (π/4, 45°)
console.log(Math.atan(-1)); // -0.785398... (-π/4, -45°)
console.log(Math.atan(Infinity)); // 1.570796... (π/2, 90°)
console.log(Math.atan(-Infinity)); // -1.570796... (-π/2, -90°)
console.log(Math.atan('abc')); // NaN
Math.atan(y/x) 只接收比值,無法知道 x 和 y 的正負號,因此無法區分向量所在象限:
// 這兩個向量 atan(y/x) 結果相同,但實際角度相差 180°
Math.atan(1 / 1); // 45° (第一象限)
Math.atan(-1 / -1); // 45° (第三象限,實際 225° 或 -135°)
Math.atan2(y, x) 接收 y, x 兩個分量,自動判斷象限,返回 [-π, π](-180° 到 180°)的完整角度。
Math.atan2(y, x)
注意參數順序:y 在前,x 在後(對應 y/x)。
const radToDeg = rad => rad * 180 / Math.PI;
const vectors = [
[1, 1], // 第一象限
[-1, 1], // 第二象限
[-1, -1], // 第三象限
[1, -1], // 第四象限
[0, 1], // 正 Y 軸
[0, -1], // 負 Y 軸
[1, 0], // 正 X 軸
[-1, 0], // 負 X 軸
];
vectors.forEach(([x, y]) => {
const atan = Math.atan(y / x);
const atan2 = Math.atan2(y, x);
console.log(`(${x},${y}) atan=${radToDeg(atan).toFixed(1)}° atan2=${radToDeg(atan2).toFixed(1)}°`);
});
/*
(1,1) atan=45.0° atan2=45.0°
(-1,1) atan=-45.0° atan2=135.0° ← atan 錯誤
(-1,-1) atan=45.0° atan2=-135.0° ← atan 錯誤
(1,-1) atan=-45.0° atan2=-45.0°
(0,1) atan=90.0° atan2=90.0°
(0,-1) atan=-90.0° atan2=-90.0°
(1,0) atan=0.0° atan2=0.0°
(-1,0) atan=-0.0° atan2=180.0° ← atan 錯誤
*/
function angleBetweenPoints(x1, y1, x2, y2) {
return Math.atan2(y2 - y1, x2 - x1); // 返回弧度
}
// 使元素朝向滑鼠
element.addEventListener('mousemove', e => {
const rect = element.getBoundingClientRect();
const centerX = rect.left + rect.width / 2;
const centerY = rect.top + rect.height / 2;
const angle = Math.atan2(e.clientY - centerY, e.clientX - centerX);
element.style.transform = `rotate(${angle}rad)`;
});
function rotateVector(x, y, angleRad) {
const cos = Math.cos(angleRad);
const sin = Math.sin(angleRad);
return [
x * cos - y * sin,
x * sin + y * cos
];
}
// 球面坐標 (r, θ, φ) → 笛卡爾 (x, y, z)
// θ: 極角 (0~π), φ: 方位角 (-π~π)
function sphericalToCartesian(r, theta, phi) {
return [
r * Math.sin(theta) * Math.cos(phi),
r * Math.sin(theta) * Math.sin(phi),
r * Math.cos(theta)
];
}
Math.atan2(y, x) 不是 Math.atan2(x, y)Math.atan2(0, 0) 返回 0,業務邏輯需自行判斷| 方法 | 參數 | 返回範圍 | 用途 |
|---|---|---|---|
Math.atan(x) | 比值 | [-π/2, π/2] | 已知斜率/比值求銳角 |
Math.atan2(y,x) | y, x 分量 | [-π, π] | 向量角度、兩點角度、極坐標 |
Math.asin(x) | 正弦值 | [-π/2, π/2] | 已知對邊/斜邊求角 |
Math.acos(x) | 餘弦值 | [0, π] | 已知鄰邊/斜邊、向量夾角 |
黃金法則:涉及二維/三維方向、角度、旋轉、**永遠使用 Math.atan2(y, x)**。Math.atan() 僅用於已知斜率/比值求銳角的簡單場景。