Reputation: 21
I´m new to programing so I have no idea what went wrong. please help
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)
Upvotes: 2
Views: 3640
Reputation: 113994
The reason for that error is that atan2
requires two arguments. Observe:
>>> from math import atan, atan2
>>> atan(2)
1.1071487177940904
>>> atan2(4, 2)
1.1071487177940904
Note that atan(y/x)
does not work if x
is zero but atan2(y, x)
will continue to work just fine:
>>> atan(4/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> atan2(4, 0)
1.5707963267948966
Upvotes: 2
Reputation: 134066
In Python, there are 2 arctangent functions: atan
is simply the inverse of tan
; but atan2
takes 2 arguments. In your case since you know both catheti, you could as well use the 2-argument function atan2
:
ang = atan2(y, x)
Alternatively, you might write
ang = atan(y / x)
The rationale for atan2
is that it works correctly even if x
is 0; while with atan(y / x)
a ZeroDivisionError: float division by zero
would be raised.
Additionally, atan
can only give an angle between -π/2 ... +π/2, whereas atan2
knows the signs of both y
and x
, and thus can know which of the 4 quadrants the value falls to; its value ranges from -π to +π. Though, of course you wouldn't have a triangle with negative width or height...
Upvotes: 5