直角坐标与极坐标之间的转换。希望结果是积极的

时间:2020-02-15 16:15:00

标签: python numpy

我需要掩盖从直角坐标到极坐标的几点。但是从某些方面来说,我得到的结果是负值。

例如,系统的原点或中心是(50,50),而我要隐蔽的点是(10,43)。我从代码中得到的角度是-170.07375449,但我希望角度是189.92624551。 (希望转换后所有角度都在0〜360度之间)

我该如何解决?

谢谢!

import numpy as np
points = np.array([(10, 43), (10, 44), (10, 45), (10, 46), (10, 47)])
#Set the center (origin) at (50, 50). Not (0, 0)
def cart_to_pol(coords, center = [50,50], deg = True):
    complex_format = np.array(coords, dtype = float).view(dtype = np.complex) -\
                     np.array(center, dtype = float).view(dtype = np.complex)
    # return np.abs(complex_format).squeeze(), np.angle(complex_format, deg = deg).squeeze()
    return np.angle(complex_format, deg=deg).squeeze()

print(cart_to_pol(points))

3 个答案:

答案 0 :(得分:1)

如果您需要转换[-180; 180]与[0; 360]您可以使用以下代码:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> 

答案 1 :(得分:1)

您可以使用np.where向负角添加360:

import numpy as np
points = np.array([(10, 43), (10, 44), (10, 45), (10, 46), (10, 47)])
#Set the center (origin) at (50, 50). Not (0, 0)
def cart_to_pol(coords, center = [50,50], deg = True):
    complex_format = np.array(coords, dtype = float).view(dtype = np.complex) -\
                     np.array(center, dtype = float).view(dtype = np.complex)
    angles = np.angle(complex_format, deg=deg).squeeze()
    summand = 360 if deg else 2*np.pi
    return np.where(angles < 0, angles+summand, angles)

print(cart_to_pol(points))

输出:

[189.92624551 188.53076561 187.12501635 185.71059314 184.28915333]

请注意,此处不需要复数。 arctan2(y, x)计算所需的角度。要获取距离:np.linalg.norm(diff_with_center, axis=-1)

def cart_to_pol(coords, center=[50, 50], deg=True):
    conversion = 180 / np.pi if deg else 1
    diff_with_center = points - center
    angles = np.arctan2(diff_with_center[:, 1], diff_with_center[:, 0])
    return conversion * np.where(angles < 0, angles + 2*np.pi, angles)

答案 2 :(得分:1)

在这里结合其他一些解决方案...

如果您将原点和/或点指定为浮点数,则可以使用一个视图以复数形式对它们进行操作,然后简单地以360度为模数返回角度:

points = points - origin    
np.angle(points.view(np.complex), deg=True) % 360
>>> array([[189.92624551],
           [188.53076561],
           [187.12501635],
           [185.71059314],
           [184.28915333]])

或者,就地操作,假设这些点已经是浮点:

np.subtract(points, origin, out=points)
v = points.view(np.complex)
np.arctan2(v.imag, v.real, out=v.real)
np.degrees(v.real, out=v.real)
np.mod(v.real, 360, out=v.real)
print(points[0])  # or print(v.real)
>>> array([[189.92624551],
           [188.53076561],
           [187.12501635],
           [185.71059314],
           [184.28915333]])

在这种情况下,由于没有angle选项,因此无法使用out,但是可以通过视图在点[0]上就地计算arctan2。它使用的内存不会比原始(浮点)points数组多,并且尽管我没有计时,但不应执行更多操作。

相关问题