ML Foundations

Choose the reference value for NumPy isclose

See why NumPy’s relative tolerance can depend on argument order.

Example results for Choose the reference value for NumPy isclose. absolute difference: 1.0
Illustration: Original illustration by Tensor Almanac
Evidence and testing

Review record: Tensor Almanac automated evidence gate (no independent human review). Example versions, recorded outputs and limitations appear below.

The second input sets the relative scale

NumPy compares the absolute difference between two values with an absolute allowance plus a relative allowance based on the magnitude of the second input. Consequently, swapping the inputs can change the result. Treat the second input as the reference when that matches the meaning of the comparison. [1]

The same reference convention applies to allclose, which reduces elementwise comparisons to one Boolean result. Choosing tolerances remains an application decision; neither function establishes a universally appropriate error bound. [1, 2]

References: [1], [2]

Calculate both tolerances

Run python examples/numpy_isclose_reference.py. The measured value is nine and the reference is ten. With relative tolerance 0.1 and absolute tolerance zero, the difference is one. Comparing nine to ten allows a difference of one, so the comparison passes. [1]

Reversing the order makes nine the reference, giving an allowance of 0.9. The same difference now fails. The example prints and asserts both results; it uses finite one-element arrays without missing values. [1]

Executed with local Python and NumPy; stdout and checksum are stored in private evidence.

import numpy as np

measured = np.array([9.0])
reference = np.array([10.0])
forward = np.isclose(measured, reference, rtol=0.1, atol=0.0)
reverse = np.isclose(reference, measured, rtol=0.1, atol=0.0)
assert bool(forward[0]) and not bool(reverse[0])
print("absolute difference:", float(np.abs(measured - reference)[0]))
print("forward tolerance:", float(0.1 * np.abs(reference)[0]))
print("reverse tolerance:", float(0.1 * np.abs(measured)[0]))
print("measured close to reference:", bool(forward[0]))
print("reference close to measured:", bool(reverse[0]))

Recorded output

absolute difference: 1.0
forward tolerance: 1.0
reverse tolerance: 0.9
measured close to reference: True
reference close to measured: False

References: [1]

Document the comparison policy

Put the intended baseline second and record both relative and absolute tolerances. When the reference is near zero, the relative allowance shrinks and the absolute tolerance can determine the result. The default absolute tolerance may be inappropriate for small values. [1]

This example tests a deliberately chosen boundary. Floating-point rounding, nonfinite values and broadcasting can affect other inputs, so use representative cases and explicitly decide how NaN values should be handled. [1, 2]

References: [1], [2]

Sources

  1. NumPy isclose
  2. NumPy allclose