Python中的数字近似

1 投票
5 回答
18304 浏览
提问于 2025-04-16 09:34

我有一串浮点数,这些数字代表了点的 x 和 y 坐标。

(-379.99418604651157, 47.517234218543351, 0.0) #representing point x

一条边由两个这样的数字组成。

我想用一种图遍历算法,比如 Dijkstra 算法,但像上面那样的浮点数并不太好用。实际上,我想要的是一种方法来近似这些数字:

(-37*.*, 4*.*, 0.0)

有没有什么 Python 函数可以做到这一点?

5 个回答

1

给定你的向量

(-379.99418604651157, 47.517234218543351, 0.0) #representing point x

最简单的四舍五入方法,应该就是使用 decimal 模块:http://docs.python.org/library/decimal.html

from decimal import Decimal:
point = (-379.99418604651157, 47.517234218543351, 0.0) #representing point x
converted = [Decimal(str(x)) for x in point]

然后,为了得到一个近似值,你可以使用 quantize 方法:

>>> converted[0].quantize(Decimal('.0001'), rounding="ROUND_DOWN")
Decimal("-379.9941")

这种方法的好处是可以避免四舍五入时出现的错误。希望这对你有帮助。

编辑:

看到你的评论后,看来你是想检查两个点是否接近。这些函数可能能满足你的需求:

def roundable(a,b):
    """Returns true if a can be rounded to b at any precision"""
    a = Decimal(str(a))
    b = Decimal(str(b))
    return a.quantize(b) == b

def close(point_1, point_2):
    for a,b in zip(point_1, point_2):
        if not (roundable(a,b) or roundable(b,a)):
            return False
    return True

我不知道这是否比 epsilon 方法更好,但实现起来相对简单。

2

“...使用像上面那样的浮点数没有帮助...” - 为什么呢?我记得Dijkstra算法并没有要求使用整数。难道你不关心边的长度吗?即使端点是用整数表示的,边的长度更可能是浮点数。

我在引用Steve Skiena的《算法设计手册》:

Dijkstra算法是通过一系列轮次进行的,每一轮都会确定从起点s到某个新顶点的最短路径。具体来说,x是那个能让dist(s, vi) + w(vi, x)最小的顶点,在所有未完成的1 <= i <= n中...

距离 - 没有提到整数。

1

像这样吗?

>>> x, y, z = (-379.99418604651157, 47.517234218543351, 0.0)
>>> abs(x - -370) < 10
True
>>> abs(y - 40) < 10
True

撰写回答