我正在编写一个 python 脚本,在比较小数位的值时我没有得到我所期望的结果。我从 SQL 查询中提取一个值,该值读取小数点后 0.10 到 40 位。当我将它与 python 生成的 0.1 进行比较时,它告诉我 pythons 0.1 大于 SQL 0.1。我知道这与数字四舍五入有关,但我该如何解决它。我可以将 SQL 编号改为 0.0000001,但我更喜欢更简洁的方法。请参阅下面我的示例。
print(f"Dist: {round(abs(dist),2):.40f}, t.min_dbv: {round(0.10,2):.40f}")
print(f"Test 1: {round(abs(dist),2) <= round(0.10,2)}")
print(f"Dist: {round(abs(dist),2):.40f}, t.min_dbv: {round(t.min_dbv,2):.40f}")
print(f"Test 2: {round(abs(dist),2) <= round(t.min_dbv,2)}")
print(f"Dist: {Decimal(abs(dist)):.40f}, t.min_dbv: {Decimal(t.min_dbv):.40f}")
print(f"Test 3: {Decimal(abs(dist)) <= Decimal(t.min_dbv)}")
这将返回以下内容
Dist: 0.1000000000000000055511151231257827021182, t.min_dbv: 0.1000000000000000055511151231257827021182
Test 1: True
Dist: 0.1000000000000000055511151231257827021182, t.min_dbv: 0.1000000000000000000000000000000000000000
Test 2: False
Dist: 0.1000000000000000055511151231257827021182, t.min_dbv: 0.1000000000000000000000000000000000000000
Test 3: False
如你所见,我尝试过舍入和十进制
这是浮点数的典型问题。由于可能存在一些差异,因此您需要设置一些阈值并以此阈值设置条件。 有伪代码
threshold = 0.0000001
abs(a-b) <= threshold
您只需检查两个值之间的差异是否小于阈值。你说如果在这个阈值内你就可以使用它。