Jupyter Snippet CB2nd 03_numpy

Jupyter Snippet CB2nd 03_numpy

1.3. Introducing the multidimensional array in NumPy for fast array computations

import random
import numpy as np
n = 1000000
x = [random.random() for _ in range(n)]
y = [random.random() for _ in range(n)]
x[:3], y[:3]
([0.926, 0.722, 0.962], [0.291, 0.339, 0.819])
z = [x[i] + y[i] for i in range(n)]
z[:3]
[1.217, 1.061, 1.781]
%timeit [x[i] + y[i] for i in range(n)]
101 ms ± 5.12 ms per loop (mean ± std. dev. of 7 runs,
    10 loops each)
xa = np.array(x)
ya = np.array(y)
xa[:3]
array([ 0.926,  0.722,  0.962])
za = xa + ya
za[:3]
array([ 1.217,  1.061,  1.781])
%timeit xa + ya
1.09 ms ± 37.3 µs per loop (mean ± std. dev. of 7 runs,
    1000 loops each)
%timeit sum(x)  # pure Python
3.94 ms ± 4.44 µs per loop (mean ± std. dev. of 7 runs
    100 loops each)
%timeit np.sum(xa)  # NumPy
298 µs ± 4.62 µs per loop (mean ± std. dev. of 7 runs,
    1000 loops each)
d = [abs(x[i] - y[j])
     for i in range(1000)
     for j in range(1000)]
d[:3]
[0.635, 0.587, 0.106]
da = np.abs(xa[:1000, np.newaxis] - ya[:1000])
da
array([[ 0.635,  0.587,  ...,  0.849,  0.046],
       [ 0.431,  0.383,  ...,  0.646,  0.158],
       ...,
       [ 0.024,  0.024,  ...,  0.238,  0.566],
       [ 0.081,  0.033,  ...,  0.295,  0.509]])
%timeit [abs(x[i] - y[j]) \
         for i in range(1000) \
         for j in range(1000)]
134 ms ± 1.79 ms per loop (mean ± std. dev. of 7 runs,
    1000 loops each)
%timeit np.abs(xa[:1000, np.newaxis] - ya[:1000])
1.54 ms ± 48.9 µs per loop (mean ± std. dev. of 7 runs
    1000 loops each)