js实现arctan
使用 Math.atan() 方法
JavaScript 提供了内置的 Math.atan() 函数来计算反正切值(arctan)。该函数接受一个数值参数,返回介于 -π/2 和 π/2 之间的弧度值。

const result = Math.atan(1); // 返回 π/4 弧度(即 45 度)
console.log(result); // 输出: 0.7853981633974483(约等于 π/4)
转换为角度
如果需要将弧度转换为角度,可以使用以下公式:
[ \text{角度} = \text{弧度} \times \frac{180}{\pi} ]

const radians = Math.atan(1);
const degrees = radians * (180 / Math.PI);
console.log(degrees); // 输出: 45
计算 atan2
对于需要计算两个参数的反正切值(即 atan2(y, x)),可以使用 Math.atan2()。该函数返回从 x 轴到点 (x, y) 的角度,范围在 -π 到 π 之间。
const angle = Math.atan2(1, 1); // 返回 π/4 弧度
console.log(angle); // 输出: 0.7853981633974483
手动实现 arctan 近似
如果需要手动实现 arctan 的近似计算,可以使用泰勒级数展开(适用于小范围内的输入):
[ \arctan(x) \approx x - \frac{x^3}{3} + \frac{x^5}{5} - \frac{x^7}{7} + \cdots ]
function customAtan(x, terms = 10) {
let result = 0;
for (let n = 0; n < terms; n++) {
const exponent = 2 * n + 1;
const term = Math.pow(-1, n) * Math.pow(x, exponent) / exponent;
result += term;
}
return result;
}
console.log(customAtan(1)); // 输出近似值: 0.7604599047323508(接近 π/4)
注意事项
Math.atan()和Math.atan2()是 JavaScript 内置的高精度方法,推荐优先使用。- 泰勒级数展开在输入值较小时效果较好,对于大输入值需要调整或使用其他近似方法。
- 如果需要更高精度,可以考虑引入数学库(如
math.js)。






