【问题标题】:Basic trig: math.atan() issue基本触发:math.atan() 问题
【发布时间】:2012-03-08 20:34:53
【问题描述】:

我在一些基本的触发方面遇到了一点麻烦。我正在做一些数学作业,我终于厌倦了将直角坐标转换为极坐标,反之亦然,所以我决定编写一个 Python 小程序来帮助我进行转换。但是, Math.atan() 给我带来了一些麻烦。代码如下:

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

如果您想知道为什么我在其中有那些笨拙的 if 语句,它是为直角坐标所在的象限添加正确的角度。象限 2 与象限 1 成 90 度,而象限 3 在与象限 1 成 180 度等。

现在,如果我输入像 (5, 5) 这样的值,一切都会按预期工作。但是,如果我输入(-5, 5),我会得到7.07, 45 的值,我应该得到7.07, 135。如果我输入(-5, -5),我会得到7.07, 225 的值,这是预期的。最后,如果我输入(5, -5) 的值,我仍然会得到7.07, 225 的值。我已经尝试了我能想到的一切,但它不起作用。那么,我错过了什么?

【问题讨论】:

    标签: python trigonometry


    【解决方案1】:

    您应该为此使用atan2。它完全按照您的需要处理象限。像这样:

    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
    

    if 语句用于处理您希望结果在 0..360 范围内的事实,但 atan2 给出的角度在 -180..180 范围内。

    您可以使用您采用的基本方法通过atan 执行此操作,但您还没有完全调试它。无论如何,每个人都为此使用atan2

    另外,您也可以使用hypot 而不是自己滚动。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-06
      • 2011-07-18
      • 2012-04-24
      相关资源
      最近更新 更多