typestar

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

  1. A ufunc applies to every element and returns an array.
  2. out= writes into an existing buffer, avoiding an allocation.
  3. np.errstate decides what a divide by zero prints.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 4 in Maths & memory, step 16 of 22 in NumPy.

← Previous Next →