Calculating with python

( previous, home, next )

Goals of this laboratory…

Start up Spyder and work through examples below to see what you can learn.

Basic math

In Laboratory 1, you saw a little about how to do math calculations in python. But let’s go through the basics to make sure we’re all on the same page.

Floating point arithmetic

For most math problems, it’s easier to work with decimals rather than integers. Computers do this using something we call floating point arithmetic. It works pretty well, but you should just be aware of some of it’s quarks because you’ll probably encounter them.

Inside a computer CPU, floating point numbers can be stored in 32 bits for single precision or 64 bits for double precision. Mostly, we (and python) use double precision these days, which gives about 16 digits of accuracy for each number. That’s usually good enough. For each line below, try to guess what the output will be before you run it.

>>> u = 0.0
>>> v = 0.000000000000000005781
>>> u == v
>>> u - v

We expect u and v to be different from each other, and python agrees. But not always. Numbers that differ only by a very small relative amounts are considered equal.

>>> x = 0.1
>>> y = 0.100000000000000005781
>>> x == y
>>> x - y

The differences between x and y are so small relative to their sizes that python considers them equal. Another special thing about computer math is that our computers use base-2 (binary) representations instead of base-10 decimal representations. This difference in representation combined with the finite precision of calculations leads to small errors in even simple cases. This is called “representation error”.

>>> 0.1 + 0.7
>>> 0.1 + 0.7 - 0.8
>>> 1.1 ** 2 - 1.21

Notice the result is PRACTICALLY zero, in scientific notation. (see the ‘e’ at the end. That’s used to represent the \(10^{-16}\) part of the scientific notation, since primitive computers could only use ASCII characters).

Finite-precision arithmetic is one of the important topics covered in Math 451 and our other numerics courses, so we won’t spend much time on it unless essential. But it’s something you’ll probably want to study at some point. In particular, formulas that are the same formally are often not the same in practice.

>>> e = 1e-15
>>> x = 1 + e
>>> y = 1 - e
>>> u, v = (x/7 - y/7), (x-y)/7
>>> u
>>> v

Observe that u and v SHOULD be equal to each other, but in fact only agree to a few decimal places. Which one is closer to the true answer?


The python language itself (like all good modern languages) is simple, using only about 30 words. Python’s power comes from the rich collection of well-documented “modules” that are available to perform complex tasks. A module is python script that contains functions (and classes) to perform related tasks, like a library in C. Perhaps the simplest example of this is the “math” module.

You can load a module into your python interpreter’s global namespace and shell scripts with the “import” keyword.

>>> import math

You can use help to see the contents of the module you have imported.

>>> help(math)

To use one of the functions from the module, you put the modules name as a prefix, like

>>> math.exp(0.)
>>> math.pi

Function names can also be imported directly into the working namespace, although this can be dangerous and is discouraged.

>>> from math import sin, pi, exp, log
>>> sin(0), sin(pi/2)
>>> exp(0), exp(1), log(exp(1))

All other modules work the same way, and provide a variety of capabilities. Here are some common modules.

Scientific computing modules

For this next part of the lab, it will be useful to start with a clean environment, so go up to the menus and select “Restart Kernel”.

While python’s math module is useful for common highschool calculations, it won’t work well in our course because of a variety of limitations. Instead, there is a standard stack of modules we use for scientific computing called the “scipy stack”. Parts of this stack of modules are automatically loaded into Spyder’s global namespace. These are numpy (which creates arrays you can use to represent vectors, matrices, and tensors), scipy (which supplies all sorts of functions and algorithms that work with arrays), and matplotlib (for making plots and pictures). If you know matlab already, there are many similar things to python, but also some differences. If you write a script or use some other python interpreter, you can load these modules into the global namespace with the following three lines of code.

>>> from numpy import *
>>> from scipy import *
>>> from matplotlib.pyplot import *

Now, let’s see how we can use the scipy stack to solve some problems you have seen before.


Before running the following animations in spyder, follow the menus and go to “Tools -> Preferences -> IPython console -> Graphics”, and change “Backend” to “Automatic”. This should set up spyder so the figures below come out correctly.

The scipy stack has a useful set of plotting tools. For a simple example, here is a use of the rational parametric form of a circle.

>>> t = linspace(-10,10,64)
>>> x = (t*t-1)/(t*t+1)
>>> y = 2*t/(t*t+1)
>>> plot(x, y, 'ro-', cos(t), sin(t), 'k:')

The linspace(-10,10,64) function creates an array of 64 evenly spaced points from -10 to 10, including the endpoints. The extra strings in the plot command specify how to draw a line. Can you guess what each character means?

To clear the figure, you can use the command clf(). Of course, plots without labels are often more confusing than helpful. We can add titles and labels with the functions title(), ylabel(), xlabel(), and text.

>>> xlabel('x-values')
>>> title('A circle', fontsize=25)

To save your figure to a .png image file with the “savefig” command.

>>> cd Desktop
>>> savefig('mycircle.png')

Of course, vector formats for images are better, so we usually use portable document format (.pdf), encapsulated postscript (.eps), or scalable vector graphic format (.svg).

For a second example, let’s see if we can draw a cycloid.

>>> figure(2)
>>> clf()
>>> r = 1.
>>> theta =  linspace(0, 8 * pi, 257)
>>> x = r * (t - sin(t))
>>> y = r * (1 - cos(t))
>>> plot(x, y, 'r-')

The figure function is used to create a new figure or select an old figure for the plot. `

For more information, see Matplotlib’s gallery

Matplotlib will also allow us to construct animations. Check out this animation of a double pendulum and run it as a script. How does the motion change as you change the mass of the second pendulum weight?

Challenge: can you construct your own animation of the cycloid like this one?

Further reading …

( previous, home, next )