← 中文资源

简体中文版本

math.isclose 带容差比较浮点数

math.isclose 用相对容差比较浮点数,rel_tol 吸收累积舍入误差;与零比较时相对容差失效,必须补 abs_tol 才判得上。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

== on floats: False
isclose    : True
rel fails  : False
abs_tol    : True
price ok   : True

实现说明

顶层就这几处状态:price、charge。

使用要点

  • 演示输出是带标签的(== on floats:),每个操作都会留下自己的一行标注。

常见问题

需要标准库之外的东西吗?

除标准库外不引入任何东西——这个示例没有依赖。 文件用顶层绑定保存自己的状态:price、charge。

代码示例

import math

# 0.1 + 0.2 不等于 0.3:二进制浮点的经典问题
print("== on floats:", 0.1 + 0.2 == 0.3)

# isclose 用相对容差比较:默认 rel_tol=1e-09
print("isclose    :", math.isclose(0.1 + 0.2, 0.3))

# 接近零的值相对容差失效:与 0 比较必须给 abs_tol
print("rel fails  :", math.isclose(1e-12, 0.0))
print("abs_tol    :", math.isclose(1e-12, 0.0, abs_tol=1e-9))

# 价格校验:允许一分钱的舍入误差
price = 19.99
charge = 20.00 - 0.01
print("price ok   :", math.isclose(charge, price, abs_tol=0.001))