JavaScript Math atan2()

atan2() 方法将两个参数相除,并计算结果的反正切(正切的逆)。

示例

let num = Math.atan2(4, 3);
console.log(num); 

// Output: 0.9272952180016122

atan2() 语法

atan2() 方法的语法是:

Math.atan2(x, y)

在这里,tan() 是一个静态方法。因此,我们使用类名 Math 来访问该方法。


atan2() 参数

atan2() 方法接受两个参数:

  • x - 数字,它将被参数 y 除。
  • y - 数字,它将除参数 x

在这里,该方法计算 x / y 的反正切。


atan2() 返回值

该方法返回:

  • 计算 x / y 的反正切后的角度(以弧度为单位)。
  • 对于非数字参数 xy,返回 NaN (Not a Number)。

注意: 对于数字参数,返回的角度始终在 π 的范围内。


示例 1:JavaScript Math.atan2()

// compute the arctangent of 5 / 2 let result1 = Math.atan2(5, 2);
console.log(result1);
// compute the arctangent of 0 / 5 let result2 = Math.atan(0, 5);
console.log(result2); // Output: // 1.1902899496825317 // 0

在上面的例子中:

  • Math.atan2(5, 2) - 计算 2.5 ( 5 / 2 ) 的反正切。
  • Math.atan2(0, 5) - 计算 0 ( 0 / 5 ) 的反正切。

示例 2:Math.atan2() 与 Infinity(无穷大)

// atan2() with positive infinity
let num = Math.atan2(Infinity, 0);
console.log(num);   

// atan2() with negative infinity 
let num = Math.atan2(-Infinity, 0);
console.log(num);    

// atan2() with both infinities
let num = Math.atan2(Infinity, -Infinity);
console.log(num); 

// Output:
// 1.5707963267948966 (π/2)
// -1.5707963267948966 (-π/2)
// 2.356194490192345 (3*π/4)

这里,您可以看到我们成功地将 atan2() 方法与无穷大一起使用。即使与无穷大一起使用,结果仍然在 π 之间。


示例 3:Math.atan2() 与非数字参数

// string variables
let str1 = "John";
let str2 = "Wick";

// atan2() with string arguments let result = Math.atan2(str1, str2);
console.log(result); // Output: NaN

上面的代码显示了与字符串参数一起使用 atan2() 方法。这就是为什么我们得到 NaN 作为输出。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战