Meaning
Checks that two floating-point numbers are approximately equal within a given relative tolerance, using an assertion to raise an AssertionError if they are not.
Primary Function
Testing and validation
Communicative Purpose
Verify that computed floating-point results match expected values within acceptable error bounds.
Pattern
assert math.isclose(actual, expected, rel_tol=tolerance)
Core Structure
assert math.isclose(..., ..., rel_tol=...)
Função primária
Testing and validation
Propósito comunicativo
Verify that computed floating-point results match expected values within acceptable error bounds.
Situações de gatilho
Testing: unit testing numerical algorithms; Validation: validating outputs of simulations or financial calculations; Scientific computing: comparing results of floating-point operations
Contextos
Scientific computing, data science, finance, game development, any Python code that performs floating-point arithmetic.
Padrão
assert math.isclose(actual, expected, rel_tol=tolerance)
Estrutura central
assert math.isclose(..., ..., rel_tol=...)
Slots de substituição
actual: numeric expression (float or int), expected: numeric expression, tolerance: positive float (e.g., 1e-9)
Colocados típicos
- unittest.TestCase
- pytest
- numpy.testing.assert_allclose
- math.isclose
- assert statements
Substituições comuns
- using abs_tol instead of rel_tol: better for values near zero
- using both rel_tol and abs_tol: covers both small and large values
- using numpy.isclose: for array comparisons
- using pytest.approx: richer syntax in pytest
Erros comuns
forgetting to import math, using == for float comparison, setting tolerance too tight or too loose, omitting the assert keyword
Similar / contraste
pytest.approx (more expressive), numpy.testing.assert_allclose (array support), manual epsilon check (abs(a-b) < eps)
Interferências
Coming from C or Java: expecting exact equality with == for floats; may overlook rounding errors.
Família do chunk
- Floating-point comparison
- Assertion
- Numeric tolerance testing
Nuance
Relative tolerance scales with magnitude; for values near zero consider adding an absolute tolerance (abs_tol) to avoid always passing.
Efeito pragmático
Makes floating-point equality intent explicit and prevents false test failures due to rounding.
Dica de memória
Assert they're close enough
Nota
math.isclose was added in Python 3.5; earlier versions require manual epsilon checks. The default rel_tol is 1e-9, which is sufficient for most scientific computing but may need loosening for iterative algorithms with accumulated error.
Upgrade path
Use pytest.approx for richer assertion syntax in test frameworks.
Log in to save chunks.