python - 创建一组涉及浮点数的实例
问题描述
我有一个具有浮点 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
,而且我工作的真正类要复杂一些。
解决方案
您可以使用标准库中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)
)
推荐阅读
- string - 查找特殊字符串的所有排列(递归)
- jenkins-groovy - 我们如何从詹金斯禁用和删除脚本控制台(groovy)
- r - 将多行中的值汇总为具有相同 ID 的唯一行
- android - 在我的 SQliteDatabase 中,日期未创建(Kotlin)
- go - 公式 V 中的运算符优先级 = 4/3πr3
- python - 解析嵌套的 JSON 并迭代到 Pandas Dataframe
- ios - 自上次 iOS 升级以来,HTTP 请求总是最终被取消
- sql - 管理模型中的 Django SQL get_queryset 无法使用执行原始查询
- python - 在 Dask.Distributed 中使用 mpirun 子进程
- docusignapi - DocuSign API 下载功能