Python conversion between coordinates

前端 未结 7 1679
我寻月下人不归
我寻月下人不归 2020-12-01 05:03

Are there functions for conversion between different coordinate systems?

For example, Matlab has [rho,phi] = cart2pol(x,y) for conversion from cartesian

相关标签:
7条回答
  • 2020-12-01 05:35

    Using numpy, you can define the following:

    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)
    
    0 讨论(0)
  • 2020-12-01 05:37

    There is a better way to write polar(), here it is:

    def polar(x,y):
      `returns r, theta(degrees)`
      return math.hypot(x,y),math.degrees(math.atan2(y,x))
    
    0 讨论(0)
  • 2020-12-01 05:37

    If your coordinates are stored as complex numbers you can use cmath

    0 讨论(0)
  • 2020-12-01 05:39

    The existing answers can be simplified:

    from numpy import exp, abs, angle
    
    def polar2z(r,theta):
        return r * exp( 1j * theta )
    
    def z2polar(z):
        return ( abs(z), angle(z) )
    

    Or even:

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

    Note these also work on arrays!

    rS, thetaS = z2polar( [z1,z2,z3] )
    zS = polar2z( rS, thetaS )
    
    0 讨论(0)
  • 2020-12-01 05:39

    Thinking about it in general, I would strongly consider hiding coordinate system behind well-designed abstraction. Quoting Uncle Bob and his book:

    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)
    

    With interface like that any user of Point class may choose convenient representation, no explicit conversions will be performed. All this ugly sines, cosines etc. will be hidden in one place. Point class. Only place where you should care which representation is used in computer memory.

    0 讨论(0)
  • 2020-12-01 05:42

    You can use the cmath module.

    If the number is converted to a complex format, then it becomes easier to just call the polar method on the number.

    import cmath
    input_num = complex(1, 2) # stored as 1+2j
    r, phi = cmath.polar(input_num)
    
    0 讨论(0)
提交回复
热议问题