Python Glossary Русский

Python 3.5+cmathfunction

cmath.isclose()

checking

Compares two complex numbers with a tolerance: the relative rel_tol and the absolute abs_tol. The replacement for == in floating point.

Syntax

cmath.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)

The main trap is comparing with zero: the relative tolerance is scaled by the magnitude of the numbers, and zero has none, so isclose(sin(pi), 0) is False. Pass abs_tol, for example 1e-9, for such checks. Distance is measured as abs(a - b), over both parts at once rather than each part separately.

Examples

import cmath
z = cmath.exp(1j * cmath.pi)
print(z == -1, cmath.isclose(z, -1))  # → False True
import cmath
s = cmath.sin(cmath.pi)
print(cmath.isclose(s, 0))  # → False
print(cmath.isclose(s, 0, abs_tol=1e-9))  # → True

See also

Open in the full glossarydocs.python.orgReport an inaccuracy