Section 1.2 Vectors in Python
Now that we have been introduced to vectors, it’s time to learn how to work with vectors in Python.
Subsection 1.2.1 Introduction to Python
SageMath is a free open-source mathematics software system licensed under the GPL. It builds on top of many existing open-source packages: NumPy, SciPy, matplotlib, SymPy, Maxima, GAP, FLINT, R and many more. Access their combined power through a common, Python-based language or directly via interfaces or wrappers. In this book we will use SageMath as a way to embed Python cells that you can edit and execute as you learn linear algebra.
Here is a Python cell containing a command that asks Python to multiply 5 and 3. You may execute the command by pressing the Evaluate button.
Of course, you can run this sort of Python code in other Python environments as well, including in a Jupyter notebook, in an RMarkdown or Quarto document, in posit RStudio, in a Sage cell server, etc. The Python cells in this text provide a handy way to try things out as you are reading, but you should adopt one of these other platforms for saving work.
Throughout the text, we will introduce new Python commands that allow us to explore linear algebra concepts. These commands are collected and summarized in the reference found in
Appendix A.
Activity 1.2.1. Basic Python commands.
-
Python uses the standard operators +
, -
, *
, and /
for the usual arithmetic operations. **
is used for exponentiation. By entering text in the cell below, ask Python to evaluate
\begin{equation*}
3 + 4(2^4 - 1)
\end{equation*}
-
Notice that we can create new lines by pressing Enter and entering additional commands on them. What happens when you evaluate this cell?
Notice that we don’t see any output from the cell we just evaluated. In order to see the results, we use print()
:
-
We may give a name to the result of one command and refer to it in a later command.
Suppose you have three tests in your linear algebra class and your scores are 90, 100, and 98. In the cell below, add your scores together and call the result total
. On the next line, find the average of your test scores and print it.
-
We can run other sorts of Python code in these Python cells as well. For example, you may be familiar with Python for loops:
Answer.
Only the results of the last line are displayed.
total = 90 + 100 + 98
average = total / 3
print(average)
This cell prints the integers from 0 to 9.
Solution.
Only the results of the last line are displayed.
total = 90 + 100 + 98
average = total / 3
print(average)
This cell prints the integers from 0 to 9.
Subsection 1.2.2 numpy
vectors
Since a vector is just a list of numbers, if you know Python, you might expect that we will create vectors using Python lists. This is partially correct. But Python lists don’t know about our operations (scalar multiplication and vector addition). In order to get vectors that know about these operations, we will convert our Python lists into ndarrays (n-dimensional arrays) using the Python package numpy
.
In numpy
parlance, a vector is a 1-dimensional array. Vectors are created using np.array()
, which is provided with a list of numbers. Python can perform scalar multiplication and vector addition. We define a vector using np.array()
; then *
and +
denote scalar multiplication and vector addition.
Especially when we work with vectors with many components, we will often want to have Python tell us how many components there are. We can use .shape
to find out how many components are in one of our vectors. Give it a try. Type print(v.shape)
in the code block above and re-evaluate.
For low dimensional vectors, manually typing in each component is reasonable. But ofen we will work with vectors with many components. So we will need some better ways to create these vectors. Here are some examples showing how to create structured or random vectors.
Indexing in Python is 0-based. So the first component of the vector v
is v[0]
. If v
has 100 components, then the last component is v[99]
. We can also use v[-1]
to access the last component. More generally, v[-k]
is the same as v[v.shape - k]
when k
is positive (so -k
is negative).
Once we have an ndarray, we can compute various summaries of it. The sum, mean, and standard deviation are commonly used summaries. For output purposes, it is often useful to round output values.
Example 1.2.4.
In the cell below, we can refer to the vector v
and w
from above -- if we have executed the cell where they were defined (and have not subsequently changed their values).
Subsection 1.2.3 Vector length
We can compute the (Euclidean) length of a vector two ways. The first takes advantage of python comprehension. The second uses the numpy.linalg.norm()
function.
List comprehension is a powerful feature of Python that lets us compute with lists, including numpy arrays. Here is a simple exmaple that creates a new list that contains the squares of the elements in the original list.
Notice that the code above computes all the terms we need to add when computing the length of a vector. So we can combine with numpy.sum()
to get the square of the length. Also notice that squares
is a Python list, not an numpy array. We can see that from the way that numbers
and squares
are printed. (The are no commas in the dispaly of numbers
.) You can confirm the types using type()
.
Computing the length of a vector is common enough that numpy includes a function for this: numpy.linalg.norm()
. It can compute several different norms, but the default is the familiar Euclidean norm.
Subsection 1.2.4 Plotting vectors
We can use matplotlib.pyplot.quiver()
to visualize 2-d and 3-d vectors. Below are two examples showing the sum of two vectors. For simplicity, we plot each vector as a separate command, but it is possible to plot multiple arrows all at once. This explain the name quiver
.
The arguments to quiver
include the coordiantes of the starting point for the arrow and coordinates specifying the amount of change in each direction. This makes it easy to plot vectors originating at the origin or originating at some other place, as is useful to illustrating the sum. Notice the use of *
in these examples. *origin
, for example, is shorthand for origin[0], origin[1]
(in the 2-d case). By default, for the 2-d plots, Matplotlib will rescale the lengths of the vectors. Additional arugments are included here so that the vectors are plotted on their natural scale.
NumPy documentation.
Official
numpy
documentation can be found at
numpy.org/doc
. You may also find it handy to use
devdocs.io
which provides documentation on many languages (including Python) and packages (including
numpy
) and provides a powerful mechanism for searching within documentation.
Matplotlib documentation.
personal.math.ubc.ca/~cass/piscript/