Skip to main content

MATH 345: Linear Algebra and Optimization

Section B.1 How to Read Computational Cells

In this course, code is usually included to express a mathematical idea, not to teach software engineering.
  • Read imports as setup. Commands such as import numpy as np, import sympy as sp, and import matplotlib.pyplot as plt make a library available under a short name; they have no mathematical output.
  • Read comments as notes. A line beginning with # is ignored by Python and is included only to help a reader.
  • Read display commands as output choices. The last line of many notebook cells is displayed automatically, while print(...) explicitly displays a value.
  • Read assertions as sanity checks. A command such as assert A.shape == (2, 3) checks that a condition is true.
  • Read shape requests as dimension checks. A command such as A.shape returns a tuple describing the dimensions of an array or matrix.
  • Read display settings as display only. A command such as np.set_printoptions(...) changes how arrays are printed, not the underlying numerical values.
import numpy as np

A = np.array([[1, 2, 3],
              [4, 5, 6]])

print(A.shape)
assert A.shape == (2, 3)
np.set_printoptions(precision=3, suppress=True)
The command np.set_printoptions(precision=3, suppress=True) only changes how arrays are displayed. It does not change the underlying numerical values.

Warning B.1.1. Read code as mathematical notation.

In the labs, read the code as compressed mathematical notation. The important question is usually what object is represented, what operation is being performed, and what the output means.
Most sections below follow the same pattern. First, a short code fragment shows the kind of computation used in the labs. Then a reading guide translates code patterns into a mathematical reading, expected output or shape, and where the pattern is used. When a command has a common trap, a short warning explains what to watch for.