矩形坐标到双曲坐标转换不可逆

0 投票
1 回答
652 浏览
提问于 2025-04-18 07:01

我最近在做一个模块,里面有一套坐标系统转换的功能。在处理双曲坐标的时候遇到了一些问题。根据维基百科的定义,双曲坐标 (u, v) 可以用笛卡尔坐标来表示,公式是 u = -1/2ln(y/x),这里的 ln 是自然对数,而 v = sqrt(xy)。反过来,x = ve^uy = ve^-u,其中 e 是欧拉常数。

知道这些后,我写了两个函数来进行转换,看看效果如何:

def rectangular_to_hyperbolic(coordinate):
    """
    Convert a rectangular (cartesian) coordinate to hyperbolic form.
    """
    x, y = coordinate
    u = -1/2*math.log1p(y/x)
    v = math.sqrt(x*y)
    return u, v

def hyperbolic_to_rectangular(coordinate):
    """
    Convert a hyperbolic coordinate to rectangular form.
    """
    u, v = coordinate
    x = v*(math.e**u)
    y = v*(math.e**-u)
    return x, y

看起来没什么问题,所以当我得到这个输出时我感到很震惊:

>>> hyperbolic_to_rectangular(rectangular_to_hyperbolic((5, 5)) 
(3.53553, 7.07107) # this should be (5, 5)

那可能是什么问题呢?

1 个回答

4

math.log1p(x)ln(1+x),而不是 ln(x)

log1p(x)

这个函数返回的是 1+x 的自然对数(以 e 为底)。它的计算方式对于接近零的 x 值非常准确。

你可能更想用 math.log

示例:

In [1]: import math

In [2]: def r2h(c):
   ...:     x, y = c
   ...:     return -math.log(y/x), math.sqrt(x*y)
   ...:

In [3]: def h2r(c):
   ...:     u, v = c
   ...:     return v*math.exp(u), v*math.exp(-u)
   ...:

In [4]: h2r(r2h((5, 5)))
Out[4]: (5.0, 5.0)

撰写回答