Reputation: 147
In Python, if one wanted to create the effect of atan2() from the atan() function, how would one go about this? For example, if I had cartesian coordinates (x, y) and wanted to find the arctan of (x, y) using the atan() function such that it worked in all quadrants, so regardless of the sign of x or y, how could I do this without using the atan2() function? In the example of converting between cartesian and polar:
def cartopol(x, y):
r = (x**2 + y**2)**0.5
p = math.atan(y/x)
return(r,p)
This formula for returning the correct angle in radians would not currently work using the atan() function, so what must change?
Upvotes: 2
Views: 3807
Reputation: 59304
In a nutshell, math.atan
only works for quadrants 1 and 4. For quadrants 2 and 3 (i.e. for x < 0), then you'd have to add or subtract pi (180 degrees) to get to quadrants 1 and 4 and find the respective value for the theta. In code, it means that
if (y < 0 and x < 0):
print(math.atan(y/x) - math.pi)
elif (y > 0 and x < 0):
print(math.atan(y/x) + math.pi)
For more reference, take a look at atan2
. The other two use cases are those in which x > 0
, which works well with atan
.
Upvotes: 2