Basic trig: math.atan() issue

与世无争的帅哥 提交于 2019-12-12 11:06:52

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/9624515/basic-trig-math-atan-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!