bhylu.com

Advertisements

NumPy Rounding

Rounding changes a displayed or stored approximation according to a rule. floor, ceil and trunc do not implement the same rule as rounding to the nearest value.

How it works

NumPy’s nearest rounding uses ties-to-even, so a halfway value can move in either numerical direction depending on the neighbouring even value. Binary representation means some decimal ties are not represented exactly. Avoid using display rounding as a substitute for a domain’s exact accounting or measurement policy. Keep full precision internally when that is appropriate and round only at an explicitly chosen boundary.

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 rounding.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

rounding.py

import numpy as np

values = np.array([1.5, 2.5, -1.5, -2.5])
print(np.rint(values).tolist())
print(np.floor(values).tolist())
print(np.trunc(values).tolist())

Expected result

[2.0, 2.0, -2.0, -2.0]
[1.0, 2.0, -2.0, -3.0]
[1.0, 2.0, -1.0, -2.0]

The three results deliberately differ, especially for negative values. These exact half values make the tie rule visible without an unrelated decimal representation issue. Choose the method from the required meaning, not from an attractive display.

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