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
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# Make the numpy library available under the name 'np'.
import numpy as np

# Create a 3-element zero vector (all floating point)
z = np.zeros((3))
print(z)

# Create a 3-element zero vector (integer)
z = np.zeros((3), dtype=np.int)
print(z)

# Create a 3x4 zero matrix (3 rows, 4 columns).
z = np.zeros((3,4))
print(z)

# Create an uninitialized 2x3 matrix (2 rows, 3 columns).
u = np.ndarray((2,3))
print(u)

# Create a 3x3 identity matrix.
I = np.array(((1.0,0,0),(0,1.0,0),(0,0,1.0)))
print(I)

# Create a 3x3 identity matrix.
I = np.eye(3)
print(I)

# Create a random 3-element vector.
R = np.random.rand(3)
print(R)

# Multiply by a scalar.
print(10 * R)

# Vector arithmetic.  The following operate element-by-element.

print(10 * R**2 + R)

print(np.sin(R))


# The same notation provides efficient access to large arrays.

big = np.random.rand(10000)

# Calculate the magnitude of the high-dimensional vector:

magnitude = np.sqrt(np.dot(big,big))

print("Long vector magnitude:", magnitude)

# The same is available as a primitive:
print("Long vector magnitude:", np.linalg.norm(big))

# 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