bhylu.com

Advertisements

NumPy Universal Functions

A universal function, or ufunc, applies a numerical operation element by element while handling compatible shapes and dtypes. np.add is one familiar example.

How it works

A ufunc can accept scalars or arrays and use broadcasting to align them. Some also expose reduce, accumulate and other methods. The operation’s dtype rules still matter: using an integer array does not guarantee that every operation returns integers. Learn the specific function’s domain and result contract rather than assuming all functions named in a reference behave identically.

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

ufuncs.py

import numpy as np

left = np.array([12, 18, 24])
right = np.array([1, 2, 3])
print(np.add(left, right).tolist())
print(np.add.nin, np.add.nout)
print(int(np.add.reduce(left)))

Expected result

[13, 20, 27]
2 1
54

add accepts two inputs and produces one output. Its reduction combines a sequence into one total, which is a different operation from adding corresponding positions in two arrays. The small fixture makes both results easy to verify.

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