%run set_env.py
%matplotlib inline
A universal function (ufunc) is:
The concept is similar to the map function in standard Python.
To see all the available ufuncs, see:
https://docs.scipy.org/doc/numpy-1.13.0/reference/ufuncs.html#available-ufuncs
Note:
# Example 1: no BC
np.set_printoptions(precision=5)
import numpy as np
x = np.random.random((2,3,7))
y = np.exp(x)
print(f" x:\n{x}\n")
print(f" y:\n{y}\n")
import math
z=0.5
print(np.exp(z))
# Example 2: with BC
x=np.arange(90,103,dtype=int)
y=np.arange(2,7,dtype=int).reshape((5,1))
print(f" x:{x.shape}\n{x}\n")
print(f" y:{y.shape}\n{y}\n")
z=np.mod(x,y)
print(f" z:{z.shape}\n{z}\n")
Besides Numpy functions which operate on ndarrays element-wise (UFuncs, vide supra),
there are also Numpy functions which perform reductions on ndarrays.
By default, the reductions operate on the whole ndarray.
However, we can specify a particular axis/dimension on which to perform the reduction.
The functions all have a similar syntax:
numpy.func_name(a,[axis=None],[dtype=None],[out=None])
The function func_name can be called in 2 different ways:
# Example 1:
# Invoke sum over the complete ndarray
a = np.arange(1,25).reshape((2,3,4))
print(f" a:\n{a}\n")
print(f" a.shape:{a.shape}\n")
print(f" a.sum() (Object-oriented syntax): {a.sum()}\n")
print(f" np.sum(a) (Procedural syntax) : {np.sum(a)}\n")
# Invoke sums over certain axes
a = np.arange(1,25).reshape((2,3,4))
red0 = a.sum(axis=0)
print(f" a.sum(axis=0) shape:{red0.shape}:\n{red0}\n")
red1 = a.sum(axis=1)
print(f" a.sum(axis=1) shape:{red1.shape}:\n{red1}\n")
red2 = a.sum(axis=2)
print(f" a.sum(axis=2) shape:{red2.shape}:\n{red2}\n")
np.set_printoptions(precision=4)
b = rnd.random((3,7))
print(f" b:\n{b}\n")
print(f" b.shape:{b.shape}\n")
av = b.mean(axis=0)
print(f" b.mean(axis=0):\n{av}\n")
bool_matrix = b < 0.05
print(f" bool_matrix:\n{bool_matrix}\n")
print(f" Are they any values < 0.01? {bool_matrix.any()}")
Generate the following vector [ 1, 3, 9, 27, ... , 729] using a UFunc.
Generate a 5x10 array A with random numbers $x$ $\in$ $[0,1[$.
Write the function calc_sn(n) (without the use of for loops!):
# %load ../solutions/ex5.py