CKTIS / Python
math.isclose
Overí, či absolútny rozdiel neprekročí väčšiu hranicu: absolútnu toleranciu alebo relatívnu toleranciu násobenú väčšou absolútnou hodnotou.
Verzia: Python 3.14; repository image, production runtime not attested
Syntax
math.isclose(a, b, *, rel_tol=1e-9, abs_tol=0.0)Overí, či absolútny rozdiel neprekročí väčšiu hranicu: absolútnu toleranciu alebo relatívnu toleranciu násobenú väčšou absolútnou hodnotou.
Pravidlo rozdielu platí pre konečné argumenty. Nekonečná sú si blízke iba s rovnakým znamienkom a NaN nikdy nevyhovie. Predvolená relatívna 1e-9 stačí pre 0,1 + 0,2 a 0,3.
Pri porovnaní s nulou absolútna tolerancia 1e-10 pripustí 1e-12.
import math
assert math.isclose(math.inf, math.inf) and not math.isclose(math.inf, -math.inf)
assert not math.isclose(math.nan, math.nan)
a, b = 0.1 + 0.2, 0.3
assert abs(a-b) <= max(1e-9 * max(abs(a), abs(b)), 0.0)
assert not math.isclose(0, 1e-12) and math.isclose(0, 1e-12, abs_tol=1e-10)
Príklady
import math
print(math.isclose(0.1 + 0.2, 0.3))
print(math.isclose(0, 1e-12, abs_tol=1e-10))
Výsledok
True True
Pri porovnaní s nulou absolútna tolerancia 1e-10 pripustí 1e-12.