我收到错误,“atan2()只需要2个参数(给定1个)”

时间:2016-08-21 22:23:56

标签: python atan2

我是编程新手,所以我不知道出了什么问题。请帮忙

from math import atan2, pi
x = int(input("value of x"))
y = int(input("value of y"))
r = (x**2 + y**2) ** 0.5
ang = atan2(y/x)
print("Hypotenuse is", r, "angle is", ang)

2 个答案:

答案 0 :(得分:4)

在Python中,有2个反正切函数:atan只是tan的反函数;但是atan2有2个参数。在你的情况下,因为你知道两个catheti,你也可以使用双参数函数atan2

ang = atan2(y, x)

或者,你可以写

ang = atan(y / x)

atan2的基本原理是,即使x为0,它也能正常工作;与atan(y / x)同时,ZeroDivisionError: float division by zero会被提升。

此外,atan只能给出-π/ 2 ... +π/ 2之间的角度,而atan2知道yx的符号,因此可以知道该值落入的四个象限中的哪一个;其值范围为-π到+π。当然,你当然不会有一个负宽度或高度的三角形......

答案 1 :(得分:2)

该错误的原因是atan2需要两个参数。观察:

>>> from math import atan, atan2
>>> atan(2)
1.1071487177940904
>>> atan2(4, 2)
1.1071487177940904

请注意,如果atan(y/x)为零,则x无效,但atan2(y, x)将继续正常工作:

>>> atan(4/0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> atan2(4, 0)
1.5707963267948966