rougier/numpy-100

a couple of suggestions

ev-br opened this issue · 2 comments

ev-br commented

Here's a couple of examples I've stumbled upon when teaching/learning myself. All these are variations on existing themes, and none are very challenging.
Feel free to use as you see fit.

(demonstrates chaining of bitwise operations)
Given a 1D array, negate all elements which are between 3 and 8, in place.

>>> a = np.arange(11)
>>> a[(3 < a) & (a <= 8)] *= -1


Sum a small array faster than np.sum

>>> a = np.arange(10)
>>> np.add.reduce(a)


Given two arrays, ``x`` and ``y``, construct the Cauchy matrix, 
:math:`C_{i,j} = 1/(x_i - y_j)`

>>> x = np.arange(8)
>>> y = x + 0.5
>>> C = 1.0 / np.subtract.outer(x, y)
>>> print(np.linalg.det(C))


Repeat the previous excercise, but this time do the determinant computation
in logspace to avoid a possible over/underflow.

>>> x = np.arange(8)
>>> y = x + 0.5
>>> C = 1.0 / np.subtract.outer(x, y)
>>> # using the fact that log det C == tr log C
>>> from scipy.linalg import logm
>>> np.trace(logm(C))


Given an integer ``n`` and a 2D array ``x``, select from ``x`` the rows which
can be interpreted as draws from a multinomial distribution with ``n`` degrees,
i.e., the rows which only contain integers and which sum to ``n``.

>>> x = np.asarray([[1, 0, 3, 8],
...                 [2, 0, 1, 1],
...                 [1.5, 2.5, 1, 0]])
>>> mask = np.logical_and.reduce(np.mod(x, 1) == 0, axis=-1)
>>> mask &= (x.sum(axis=-1) == n)
>>> x[mask]
array([[ 2.,  0.,  1.,  1.]])

Thanks ! I've integrated them

ev-br commented

Thanks Nicolas