python中的数字近似

2024-05-18 11:05:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个表示点的x和y坐标的浮点数列表。

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

一条边包含两个这样的数字。

我想使用一个图遍历算法,比如dijkstra,但是使用上面的浮点数没有帮助。 我实际上在寻找一种近似这些数字的方法:

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

有没有一个python函数可以做到这一点?


Tags: 方法函数算法列表数字point浮点数dijkstra
3条回答

给你的向量

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

执行舍入的最简单方法可能是使用十进制模块: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]

然后,要获得近似值,可以使用量化方法:

>>> 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方法好,但实现起来相当简单。

“…使用浮点数(如上面的浮点数)没有帮助…”-为什么不呢?我不记得整数是Dijkstra的要求。你不关心边缘的长度吗?这更可能是一个浮点数,即使端点是用整数值表示的。

我引用史蒂夫·斯基纳的“算法设计手册”:

Dijkstra's algorithm proceeds in a series of rounds, where each round establishes the shortest path from s to some new vertex. Specifically, x is the vertex that minimizes dist(s, vi) + w(vi, x) over all unfinished 1 <= i <= n...

距离-不提整数。

像这样?

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

相关问题 更多 >