首页 > 解决方案 > 创建一组涉及浮点数的实例

问题描述

我有一个具有浮点 x 列表的类(和 y,从 x 生成,所以如果 x 是等价的,y 也是等价的)。一旦初始化,实例就不会改变。我想做一组实例(使用.add()),所以我试图使类可散列:

class X:
    def __init__(self,x,y):
        self.x = x
        self.y = y
    def __hash__(self):
        return hash(tuple(self.x))
    def __eq__(self,other):
        return (
            self.__class__ == other.__class__ and
            self.x == other.x
            )

但由于浮点不准确,该集合会将两个非常接近的实例识别为不同的。我想将其设置__eq__

    def __eq__(self,other):
        diff = np.max(np.asarray(self.x)-np.asarray(other.x))
        if diff<1e-6:
            return True
        else:
            return False

但这并不能解决浮点问题。我可以使用元组(x,y)来解决这个问题,但我不需要比较y,而且我工作的真正类要复杂一些。

标签: pythonfloating-pointset

解决方案


您可以使用标准库中math.isclose数学模块来比较浮点数,也许还可以将用于生成哈希的值舍入(或截断)为默认使用的小数位数isclose。(最后一个值可以参数化)

class X:
    def __init__(self,x,y):
        self.x = x
        self.y = y
    def __hash__(self):
        return hash(tuple(round(self.x, 9))  # round the value hashed to match the default of math.isclose

    def __eq__(self,other):
        return (
            self.__class__ == other.__class__ and
            math.isclose(self.x, other.x)
            )

推荐阅读