bhylu.com

Advertisements

NumPy Numerical Limits

Fixed-width integers have limited ranges, and floating-point values approximate many decimal fractions. Treat those representation limits as part of numerical correctness.

How it works

NumPy arrays do not behave exactly like Python’s arbitrary-precision integers. Use a wide enough type and check the expected range before arithmetic that could overflow. Floating-point equality can also fail after apparently simple decimal operations, so compare with a tolerance appropriate to the problem. A tolerance is an explicit error budget, not a universal way to make an inconvenient test pass.

Run the code

Select Try in playground to preload the complete code into the NumPy editor. Nothing executes on import; choose Run when ready. The first execution loads the local Pyodide runtime and NumPy package. Each ordinary run starts fresh, with no access to this page’s cookies or personal files. In-memory streams and temporary virtual files belong to the runtime, not your PC.

For local work, use a separate virtual environment and run python numeric-limits.py. Download the complete source. The reviewed local environment uses Python 3.12.14 and NumPy 2.5.4; the browser uses Pyodide 0.27.7 with NumPy 2.0.2. Compatible examples are checked in both. See the environment setup. No Apache or database server is required.

Example

numeric-limits.py

import numpy as np

a = np.array([30000], dtype=np.int16)
wide = a.astype(np.int64) + 10000
print(wide.tolist())
print((0.1 + 0.2) == 0.3)
print(np.isclose(0.1 + 0.2, 0.3, rtol=0, atol=1e-12))

Expected result

[40000]
False
True

The type is widened before addition, and the decimal comparison uses a stated absolute tolerance. This demonstrates a deliberate representation choice without presenting an overflowed result as a meaningful measurement.

Use NumPy’s official reference for precise contracts, supported versions and numerical limitations.