Python Math Power with Numpy

Python is extremely well equipped to deal with math problems. Here we will focus on features from the Numpy package. 

It pays off to invest some time in really understanding the power of the Numpy library - before you start coding something that might already be available in the package. Creation and manipulation of matrices, calculating products of vectors and matrices, calculation inverse matrices, it is all there - and without having to write for loops.

So be sure to check out the NumPy homepage first and follow that up with the Quickstart.

Numpy is used in many advanced Python packages. It is the de facto standard for mathematical operations.

Below are a few of the Numpy features that I use frequently. 

Numpy arrays and matrices

import numpy as np

arr = np.array([1, 2, 3])
mat = np.array([[1, 2, 3], [4, 6, 5], [7, 8, 9]])

# Multiplication of array and matrix, without the use of for loops

prod1 = arr * mat

# Multiplication of matrix * transposed array 
# (should be equal to previous answer)

prod2 = mat * np.transpose(arr)

prod3 = 3 * prod1 # Elementwise multiplication

prod4 = prod1.dot(prod2) # Matrixwise multiplication

# Matrixwise multiplication of matrix with its inverse should lead
# to identity matrix (with almost-zeros off the diagonal).
prod5 = np.dot(mat, np.linalg.inv(mat))

# Identity creates an identity matrix. 
prod6 = np.identity(3)

# Creating, then reshaping an array
m= np.arange(10).reshape(2,5)

print('Initial array = \n', arr)
print('Initial matrix = \n', mat)
print('prod1 = \n', prod1)
print('prod2 = \n', prod2)
print('prod3 = \n', prod3)
print('prod4 = \n', prod4)
print('prod5 = \n', prod5)
print('prod6 = \n', prod6)
print('m = \n', m)

Previous chapter | Next chapter