numpy-basics.py

NumPy is a Python library for efficient numeric computation, supporting vector and matrix calculations using efficient native data types. The following script demonstrates some basic vector and matrix operations using NumPy.

 1# Make the numpy library available under the name 'np'.
 2import numpy as np
 3
 4# Create a 3-element zero vector (all floating point)
 5z = np.zeros((3))
 6print(z)
 7
 8# Create a 3-element zero vector (integer)
 9z = np.zeros((3), dtype=np.int)
10print(z)
11
12# Create a 3x4 zero matrix (3 rows, 4 columns).
13z = np.zeros((3,4))
14print(z)
15
16# Create an uninitialized 2x3 matrix (2 rows, 3 columns).
17u = np.ndarray((2,3))
18print(u)
19
20# Create a 3x3 identity matrix.
21I = np.array(((1.0,0,0),(0,1.0,0),(0,0,1.0)))
22print(I)
23
24# Create a 3x3 identity matrix.
25I = np.eye(3)
26print(I)
27
28# Create a random 3-element vector.
29R = np.random.rand(3)
30print(R)
31
32# Multiply by a scalar.
33print(10 * R)
34
35# Vector arithmetic.  The following operate element-by-element.
36
37print(10 * R**2 + R)
38
39print(np.sin(R))
40
41
42# The same notation provides efficient access to large arrays.
43
44big = np.random.rand(10000)
45
46# Calculate the magnitude of the high-dimensional vector:
47
48magnitude = np.sqrt(np.dot(big,big))
49
50print("Long vector magnitude:", magnitude)
51
52# The same is available as a primitive:
53print("Long vector magnitude:", np.linalg.norm(big))
54
55# For more, see https://docs.scipy.org/doc/numpy/reference/routines.linalg.html

Sample Output

[0. 0. 0.]
[0 0 0]
[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]
[[-1.72723371e-077 -1.72723371e-077  6.93956885e-310]
 [ 6.93956886e-310  0.00000000e+000  4.17201348e-309]]
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
[0.61211597 0.02198595 0.71464565]
[6.12115971 0.21985947 7.14645645]
[4.35897559 0.02681977 5.82182963]
[0.57460053 0.02198418 0.6553498 ]
Long vector magnitude: 57.72461409382304
Long vector magnitude: 57.72461409382304