Reference · Math

math.isclose

signature
math.isclose(num, num, num=, num=) -> bool

What it does

Whether two numbers are close enough to count as equal, as Python's math.isclose: math.isclose(a, b, rel_tol, abs_tol) is true when |a - b| is within rel_tol times the larger of |a| and |b|, or within abs_tol. The defaults are a relative tolerance of 1e-9 and an absolute one of 0. It is the way to compare floats that came out of arithmetic, where 0.1 + 0.2 == 0.3 is false.

Examples

print(math.isclose(0.1 + 0.2, 0.3), 0.1 + 0.2 == 0.3)print(math.isclose(1.0, 1.0001), math.isclose(1.0, 1.0001, 1e-3))print(math.isclose(5, 5.5, 0.1), math.isclose(5, 5.5, 0.0, 0.5))
output
true falsefalse truetrue true

Edge cases

print(math.isclose(0.0, 1e-12), math.isclose(0.0, 1e-12, 1e-9, 1e-9))print(math.isclose(3, 4, 0.25), math.isclose(4, 3, 0.25))let inf = float("inf")let nan = float("nan")print(math.isclose(inf, inf), math.isclose(inf, 1e308), math.isclose(nan, nan), math.isclose(-0.0, 0.0))
output
false truetrue truetrue false false true

Errors

A negative tolerance is a runtime error, not an error value, as Python's ValueError. An argument that is not a number is a runtime error as well.

this one fails
print(math.isclose(1, 1, -1))
output
line 1: `math.isclose`: tolerances must be non-negative
this one fails
print(math.isclose(1, "1"))
output
line 1: `math.isclose` expects a number as argument 2, got str

Chaining

In a pipeline the first number comes first, so x | math.isclose(y). Checking that a computation lands where it should:

print(math.sqrt(2) * math.sqrt(2) | math.isclose(2))print([0.1 + 0.2, 0.3, 0.31] | map((x) => math.isclose(x, 0.3)))
output
true[true, true, false]

See also

math.isfinite, math.isnan, math.fabs, round

Thread
7Useful? Like it, or add to its thread below.

Thread 0 posts

On math.isclose(): questions, tips, corrections, and code that uses it.

No posts yet. The first one opens the thread.

    Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo