我最近在处理一个包含一组坐标系转换的模块,在使用hyperbolic coordinates时遇到了问题。根据维基百科上给出的定义,双曲线坐标(u, v)
可以用笛卡尔坐标表示为u = -1/2ln(y/x)
,ln
是自然对数,v = sqrt(xy)
。相反的是x = ve^u
和y = 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)
可能是什么问题?
答案 0 :(得分: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)