Skip to content

← JAX Profiling & Debugging step 6 of 12

Easy Primitives

jnp.allclose for Tolerance Equality

Jump to the task

Compare results with a tolerance

Two calculations can give slightly different floating-point results because they round at different steps. When small differences are acceptable, use a tolerance instead of requiring exact equality. Exact equality is still useful when exact agreement is the requirement.

For finite values, jnp.allclose(a, b, atol=atol) checks every pair using:

abs(a - b) <= atol + rtol * abs(b)

atol is an absolute allowance, useful near zero. rtol scales the allowance with the magnitude of b. This exercise keeps JAX's default rtol=1e-5, so the result is not an absolute-tolerance-only comparison. For that different check, you would explicitly set rtol=0.

Worked example

import jax.numpy as jnp

a = jnp.array([1.0, 2.0, 3.0], dtype=jnp.float32)
b = jnp.array([1.0001, 2.0001, 3.0001], dtype=jnp.float32)
loose = jnp.allclose(a, b, atol=1e-3)  # True
tight = jnp.allclose(a, b, atol=1e-5)  # False
result = jnp.where(loose, 1.0, 0.0)   # scalar 1.0

At the first element, the tight allowance is about 0.00002, smaller than the difference of about 0.0001. One failing pair is enough to make allclose false. At larger magnitudes, the relative term can allow differences greater than atol alone.

Problem

Implement values_equal_within_atol(a, b, atol) using jnp.allclose(a, b, atol=atol) and jnp.where. Return a scalar JAX floating-point value: 1.0 when all pairs are close, or 0.0 otherwise. Despite the function name, keep the default relative tolerance.

Inputs a and b are finite float32 arrays with the same shape (N,). atol is a finite, nonnegative scalar. Empty arrays compare close because there is no pair that fails the check.

Things to watch

  • The comparison returns one scalar boolean, not one per element. jnp.isclose provides the per-element result.
  • Under JIT, use the boolean in jnp.where, not a Python if.
  • The general API broadcasts compatible shapes. It does not verify that two arrays have identical shapes; incompatible shapes raise an error.
  • The formula uses abs(b), so swapping the arguments can change a result near the tolerance boundary.
  • Outside this exercise's finite-input contract, matching infinities compare close. NaNs do not by default, even at matching positions.