Review: NumPy Linear Algebra

Module 3: NumPy

Session 3.7: Linear Algebra

import numpy as np
Exercise

We run this code. What will z be?

x = np.array([[1, 2], [3, 4]])
y = np.linalg.inv(x)
z = np.dot(x, y)

print(z)

::: {.callout-tip collapse=“true”} ## Solution z is the unitary matrix, but due to floating errors, a 0 appears as a very low number instead.

How would you fix that?

:::
# Option A: convert z to integer
print(z.astype(int))
# Bad choice, remember int does not round, just cuts the decimals!
print(int(0.999999999))
x = np.array([1.2, 3.4])

# In addition, remember that you need to use "x.astype(int)"
# to convert every element of the array
# If you simply call "int(x)", you will be trying to convert a
# whole array into a single integer. That is not possible!
print(int(x))
# Option B: Using the round method instead
print(z.round(0))
print(x.astype(int))
  1. The identity matrix.

  2. A zero matrix.

  3. The code will cause an error.

Exercise

How to find the eigenvalues of a square matrix X?

X = np.array([[1, 2], [3, 4]])

# Option A
print(np.eigen(X))

# Option B
print(np.eigvals(X))

# Option C
print(np.linalg.eig(X))