Elliot Bonneville
Elliot Bonneville

Reputation: 53311

Basic trig: math.atan() issue

I'm having a little trouble with some basic trig. I'm doing some math homework, and I finally got bored of converting rectangular coordinates to polar coordinates and vice versa, so I decided to whip up a little Python program to help me with the conversions. However, Math.atan() is giving me a little trouble. Here's the code:

def rect_to_polar_input(x, y):
    hypotenuse = math.sqrt((x * x) + (y * y))
    tangent = float(y / x);
    angle = round(math.degrees(math.atan(tangent)));

    if x <= 0:
        if(y >=0):
            angle += 90

        if(y <= 0):
            angle+= 180

    if x >= 0:
        if(y<0):
            angle+=270

    return hypotenuse, angle

In case you're wondering why I have those clunky if statements in there, it's to add the correct angle for the quadrant the rectangular coordinates are in. Quadrant 2 is 90 degrees away from Quadrant 1, and Quadrant 3 is 180 degrees from Quadrant 1, etc.

Now, if I enter a value like (5, 5), everything works as expected. However, if I enter (-5, 5), I get a value of 7.07, 45, where I should be getting 7.07, 135. If I enter (-5, -5), I get a value of 7.07, 225, which is expected. Finally, if I enter a value of (5, -5), I still get a value of 7.07, 225. I've tried everything I can think of, but it's not working. So, what am I missing?

Upvotes: 5

Views: 3876

Answers (1)

David Heffernan
David Heffernan

Reputation: 612964

You should use atan2 for this. It deals with the quadrants exactly as you need. Like so:

def rect_to_polar_input(x, y):
    hypotenuse = math.hypot(x, y)
    angle = round(math.degrees(math.atan2(y, x)))
    if angle<0:
        angle += 360
    return hypotenuse, angle

The if statement is to deal with the fact that you want results in the range 0..360, but atan2 gives angles in the range -180..180.

You can do this with atan using the basic approach you have taken, but you've not quite debugged it yet. In any case, everybody uses atan2 for this.

Also, you may as well use hypot rather than rolling your own.

Upvotes: 13

Related Questions