平面坐标与极坐标转换

import numpy as np
def pnt2polar(p):
    # 平面点转极坐标
    x, y = p
    length = np.sqrt(x * x + y * y)
    x = round(x, 6)
    y = round(y, 6)
    alpha = np.arctan(abs(y / x)) if x != 0. else 0.
    if x > 0:
        if y > 0:
            angle = alpha
        elif y == 0:
            angle = 0
        else:
            angle = pi * 2 - alpha
    elif x == 0:
        if y > 0:
            angle = pi / 2
        elif y == 0:
            angle = 0
        else:
            angle = 3 * pi / 2
    else:
        if y > 0:
            angle = pi - alpha
        elif y == 0:
            angle = pi
        else:
            angle = pi + alpha

    return round(length, 3), round(angle, 3)


def polar2pnt(p):
    # 极坐标转平面坐标
    length, angle = p
    eps = 1e-8

    if length == 0:
        x, y = 0
    else:
        if angle < eps:
            x = length
            y = 0
        elif angle - 3 * pi / 2 > eps:
            x = length * np.cos(2 * pi - angle)
            y = -length * np.sin(2 * pi - angle)
        elif angle - 3 * pi / 2 == eps:
            x = 0
            y = length
        elif angle - pi > eps:
            x = -length * np.cos(angle - pi)
            y = -length * np.sin(angle - pi)
        elif angle - pi == eps:
            x = -length
            y = 0
        elif angle - pi / 2 > eps:
            x = -length * np.cos(pi - angle)
            y = length * np.sin(pi - angle)
        elif angle - pi / 2 == eps:
            x = 0
            y = -length
        else:
            x = length * np.cos(angle)
            y = length * np.sin(angle)

    return round(x, 3), round(y, 3)

  

posted @ 2021-09-16 14:33  ddzhen  阅读(439)  评论(0编辑  收藏  举报