Skip to content
AITroveRead. Build. Understand.
Make this comfortable

NumPy finite gate: reject NaN and infinity before computing totals

Last updated: 30 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

A finite-value gate marks array elements that are neither NaN nor positive or negative infinity.

Download Python source kit

Operation contract

The imported amount array contains a valid positive value, NaN, infinity and a negative value. isfinite finds the first two invalid representations; a separate domain check rejects the finite negative amount. The accepted mask therefore selects only the positive value. A production import should reject the whole batch or document partial acceptance before replacing a ledger.

Failure and ownership boundary

Floating-point arrays cannot represent every decimal minor-unit amount exactly. If money is the domain, parse bounded integers or Decimal before using a numeric array for secondary analysis. NumPy floating-point checks: finite values and declared tolerances, Python NumPy shape validation: reject accidental broadcasting before arithmetic and Python Decimal money: parse decimal text and choose rounding explicitly set adjacent constraints.

Tested environment

Dependency check: this program was executed on CPython 3.14.6 with numpy==2.5.3. Install these versions in a separate virtual environment. The download includes the recorded environment snapshot; no third-party package is part of the website runtime.

Working program

python
import numpy as np

amounts = np.array([125.0, np.nan, np.inf, -3.0], dtype=np.float64)
finite = np.isfinite(amounts)
accepted = finite & (amounts >= 0)
print("finite:", finite.tolist())
print("accepted:", accepted.tolist())
print("selected:", amounts[accepted].tolist())

Output

Output
finite: [True, False, False, True]
accepted: [True, False, False, False]
selected: [125.0]

Costs and limits

isfinite scans n elements and allocates a Boolean mask; the second comparison and selection allocate more arrays. This small fixture does not measure large-buffer memory peaks. Reject input shape and byte budgets before constructing a huge array.

Common Mistakes

  • NaN fails ordinary equality assumptions and must be handled deliberately.
  • A finite negative value can still violate a nonnegative business contract.

Connected lessons

NumPy floating-point checks: finite values and declared tolerances, Python NumPy shape validation: reject accidental broadcasting before arithmetic, Python Decimal money: parse decimal text and choose rounding explicitly.

python
numpy-finite-gate
Storage details