我是编程新手,所以我不知道出了什么问题。请帮忙
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)
答案 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
知道y
和x
的符号,因此可以知道该值落入的四个象限中的哪一个;其值范围为-π到+π。当然,你当然不会有一个负宽度或高度的三角形......
答案 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