December 25, 2025
So far we’ve been exposed to the following ideas about Jupyter Notebooks and Google Colab
Google Colab provides an interface for writing Jupyter notebooks in your web browser via Google Drive
Jupyter notebooks allow you to mix text (white background) and executable Python code (grey background) in a single document.
Shift and hitting Enter (or Return).At our first class meeting, we got a broad overview of Python. We introduced the following ideas.
for and while loops to carry out the same sets of instructions over and over again.if/else if/else) to control when certain instructions are to be run.We also explored Python lists quite a bit and, while we won’t often explicitly use them, they’ll be part of how we define arrays (ie. vectors and matrices)
This notebook covers a crash course in numerical python and the numpy module.
After working through this notebook, you’ll have enough to get you started, but we’ll continue to learn more about python and numpy as the semester progresses.
\(\bigstar\) You will not, and should not expect to, be an expert or be fluent after today’s discussion. Expect to come back here and to our initial slide deck often. \(\bigstar\)
Today, we’ll revisit items in greater detail and visit some new ones as well. We’ll see…
importing modules – specifically {numpy}np.array()print() statements{numpy} functionality{matplotlib}Base Python can do basic things like limited math, printing, etc.
When users want to engage in specialized activities, they’ll import modules that extend Python’s functionality by running import module_name.
{numpy} (numerical python) is a module that supports arrays and mathematics on arrays – we’ll make use of this module often.{matplotlib} is a plotting library that will also come in handy for us.Using functionality from a module requires namespacing – that is, we call numpy.function_name() to access and use a function from the {numpy} module.
as keyword.import numpy as np is extremely common.Many modules are nested.
np.linalg.det() to compute the determinant of a matrix.import matplotlib.pyplot as plt and then use plt.function_name() for plotting.{numpy}The {numpy} module is one that we’ll make extensive use of this semester.
In the majority of our work, we’ll be using scalars (single component, numerical values) and arrays.
In order to make use of arrays, we’ll need to extend Python’s functionality by importing the {numpy} module.
np.array().
np.array() to create an array, as we did in our first notebook.We can perform arithmetical operations on arrays as long as their dimensions are compatible.
Recall the contents of myVec_v1, myVec_v2, myVec_v3, and myMatrix_A.
We’ll try executing arithmetic operations on these vectors and matrix below.
Do you notice anything surprising or questionable?
If you haven’t been playing along in a Colab/Jupyter notebook, please consider doing it.
You’ll notice that the error messages in these slides are abridged versions of what you’ll see in your notebook environment.
In the notebooks, you’ll see a full error traceback.
\(\bigstar\) Learn not to be afraid, intimidated, or frustrated by errors – with practice, you will get better at deciphering them. \(\bigstar\)
We’ve already seen several examples of where Python might not behave in ways we would expect.
We’ve experienced the pass by reference pitfall with lists.
We’ve seen that Python will execute mathematically inappropriate expressions.
All of this means we must be diligent, compare our results to our expectations, and not blindly trust that Python has done what we expected.
I’ll try to highlight quirks that have bitten me in the past so that you don’t get caught by them. Inevitably, we’ll encounter new quirks as well.
Importance of Explicitly Declaring Float Arrays: Python will sometimes try to save space by storing numbers using an integer data type, but integer arithmetic is not the same as float arithmetic.
We’ll define two matrices below.
Can you tell that they are not treated the same by Python?
Sometimes we need to create somewhat large arrays, and typing in their entries one-by-one is not convenient or desirable.
We can construct an array of the appropriate size and then edit its contents via loops or accessing individual indices.
Each of the following are examples of methods that can be used to quickly construct arrays of a desired size.
array([[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])
array([[1., 0., 0., 0.],
[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]])
array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
If the top-left and bottom-right entries of the my_2x5_zeros matrix should be \(2\) and \(-8\), respectively, we can make that happen.
A sparse matrix (or sparse array) is a matrix/array whose entries are mostly \(0\)’s, but with a few non-zero entries.
If the array is large enough, using a specialized data structure can result in significant space savings.
Below, we’ll construct a \(5\times 7\) matrix whose only non-zero entries are
{matplotlib}For low-dimensional problems, it is often useful to draw pictures.
We’ll use this from time to time to motivate examples or to gain some intuition about problems.
The {matplotlib} module/library is quite useful for plotting – in particular, we’ll use matplotlib.pyplot().
Below is an example of plotting a function.
The {matplotlib.pyplot} submodule provides lots of support for customizing your plots.
You can add axes, gridlines, axis labels and titles, plot multiple objects/functions, change colors, fonts, and more!
Example: Below is a code cell that creates a function \(f\left(x\right) = x\cos\left(x\right)\) and plot it with some extras to make the plot more readable.
x_vals = np.linspace(-6, 6, num = 500)
#y_vals = np.sin(x_vals)
def f(x):
y_vals = x*np.cos(x)
return y_vals
y_vals = f(x_vals)
plt.figure(figsize = (9, 5))
plt.plot(x_vals, y_vals, color = "purple",
linewidth = 5)
plt.grid()
plt.axhline(y = 0, color = "black")
plt.axvline(x = 0, color = "black")
plt.title("My function $f(x) = x\cos(x)$",
fontsize = 36))
plt.xlabel("x", fontsize = 22)
plt.ylabel("y", fontsize = 22)
plt.show()
That’s all for now. Next time, we’ll have a Colab, Python, and \(\LaTeX\) workshop.