math.isclose Compares Floats With Tolerance

math.isclose replaces == on floats: relative tolerance absorbs rounding error, and abs_tol covers comparisons against zero that rel_tol cannot express.

PythonData Integrity

Code

pythonsnippet
16 lines
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))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

Inside the snippet

Everything operates on top-level bindings: price, charge.

What to watch for

  • The dependency list is empty; the language runtime covers it all.

The structure at work

Look for the == on floats:, isclose :, rel fails : prefixes when the file runs; they tie each line to its step.

Interactive Tools for This Topic

FAQ

Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free. Its state lives in module-level bindings: `price`, `charge`.