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.
Code
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 : TrueInside 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
GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Vector Similarity CalculatorCompute Cosine Similarity, Dot Product, Euclidean L2, Manhattan L1, and Chebyshev distances between numeric vectors with dimension checks.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.