Universal functions in Python
Element-wise maths that loops in C, not in Python.
import numpy as np
values = np.array([1.0, 4.0, 9.0, 16.0])
print(np.sqrt(values))
print(np.exp(np.log(values)).round(6))
print(np.clip(values, 2, 10))
target = np.empty_like(values)
np.multiply(values, 2, out=target)
print(target)
with np.errstate(divide="ignore"):
print(np.log(np.array([0.0, 1.0])))
How it works
- A ufunc applies to every element and returns an array.
out=writes into an existing buffer, avoiding an allocation.np.errstatedecides what a divide by zero prints.
Keywords and builtins used here
asprintwith
The run, in numbers
- Lines
- 14
- Characters to type
- 306
- Tokens
- 115
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 63 seconds.
Step 1 of 4 in Maths & memory, step 16 of 22 in NumPy.