Подтвердить что ты не робот

Преобразование Python между координатами

Существуют ли функции для преобразования между различными системами координат?

Например, Matlab имеет [rho,phi] = cart2pol(x,y) для преобразования из декартовых координат в полярные. Похоже, это должно быть много или скудно.

4b9b3361

Ответ 1

Используя numpy, вы можете определить следующее:

import numpy as np

def cart2pol(x, y):
    rho = np.sqrt(x**2 + y**2)
    phi = np.arctan2(y, x)
    return(rho, phi)

def pol2cart(rho, phi):
    x = rho * np.cos(phi)
    y = rho * np.sin(phi)
    return(x, y)

Ответ 2

Существующие ответы могут быть упрощены:

from numpy import exp, abs, angle

def polar2z(r,theta):
    return r * exp( 1j * theta )

def z2polar(z):
    return ( abs(z), angle(z) )

Или даже:

polar2z = lambda r,θ: r * exp( 1j * θ )
z2polar = lambda z: ( abs(z), angle(z) )

Обратите внимание, что они также работают с массивами!

rS, thetaS = z2polar( [z1,z2,z3] )
zS = polar2z( rS, thetaS )

Ответ 3

Если вы не можете найти его в numpy или scipy, вот пара быстрых функций и класс точек:

import math

def rect(r, theta):
    """theta in degrees

    returns tuple; (float, float); (x,y)
    """
    x = r * math.cos(math.radians(theta))
    y = r * math.sin(math.radians(theta))
    return x,y

def polar(x, y):
    """returns r, theta(degrees)
    """
    r = (x ** 2 + y ** 2) ** .5
    theta = math.degrees(math.atan2(y,x))
    return r, theta

class Point(object):
    def __init__(self, x=None, y=None, r=None, theta=None):
        """x and y or r and theta(degrees)
        """
        if x and y:
            self.c_polar(x, y)
        elif r and theta:
            self.c_rect(r, theta)
        else:
            raise ValueError('Must specify x and y or r and theta')
    def c_polar(self, x, y, f = polar):
        self._x = x
        self._y = y
        self._r, self._theta = f(self._x, self._y)
        self._theta_radians = math.radians(self._theta)
    def c_rect(self, r, theta, f = rect):
        """theta in degrees
        """
        self._r = r
        self._theta = theta
        self._theta_radians = math.radians(theta)
        self._x, self._y = f(self._r, self._theta)
    def setx(self, x):
        self.c_polar(x, self._y)
    def getx(self):
        return self._x
    x = property(fget = getx, fset = setx)
    def sety(self, y):
        self.c_polar(self._x, y)
    def gety(self):
        return self._y
    y = property(fget = gety, fset = sety)
    def setxy(self, x, y):
        self.c_polar(x, y)
    def getxy(self):
        return self._x, self._y
    xy = property(fget = getxy, fset = setxy)
    def setr(self, r):
        self.c_rect(r, self._theta)
    def getr(self):
        return self._r
    r = property(fget = getr, fset = setr)
    def settheta(self, theta):
        """theta in degrees
        """
        self.c_rect(self._r, theta)
    def gettheta(self):
        return self._theta
    theta = property(fget = gettheta, fset = settheta)
    def set_r_theta(self, r, theta):
        """theta in degrees
        """
        self.c_rect(r, theta)
    def get_r_theta(self):
        return self._r, self._theta
    r_theta = property(fget = get_r_theta, fset = set_r_theta)
    def __str__(self):
        return '({},{})'.format(self._x, self._y)

Ответ 4

Вы можете использовать модуль cmath.

Если число преобразуется в сложный формат, тогда становится проще просто вызвать полярный метод для числа.

import cmath
input_num = complex(1, 2) # stored as 1+2j
r, phi = cmath.polar(input_num)

Ответ 5

Существует лучший способ написать polar(), вот он:

def polar(x,y):
  `returns r, theta(degrees)`
  return math.hypot(x,y),math.degrees(math.atan2(y,x))

Ответ 6

Если ваши координаты хранятся как комплексные числа, вы можете использовать cmath

Ответ 7

Размышляя об этом в целом, я бы настоятельно рекомендовал скрытую систему координат за хорошо продуманной абстракцией. Цитата: Дядя Боб и его книга:

class Point(object)
    def setCartesian(self, x, y)
    def setPolar(self, rho, theta)
    def getX(self)
    def getY(self)
    def getRho(self)
    def setTheta(self)

С таким интерфейсом любой пользователь класса Point может выбрать удобное представление, без явных преобразований. Все эти уродливые синусы, косинусы и т.д. Будут спрятаны в одном месте. Точечный класс. Только место, где вы должны заботиться о том, какое представление используется в памяти компьютера.