Computational Methods in Physics ASU Physics PHY 494

06 Introduction to NumPy

We saw in the Introduction to Python that the Python language has the control and data structures to do numerical calculations. For instance, a vector denoting the position of a particle could be represented as a Python list r = [x, y, z] and a matrix as a list of lists sigma_y = [[0, -1j], [1j, 0]].

When it comes to doing numerical work, Python by itself is rather slow. By slow we mean compared to languages like C and Fortran, which benefit from being compiled languages in which a program is preprocessed into machine code by a compiler. Python by contrast is an interpreted language, in which each line in a program is fed to the Python interpreter in sequence, then executed. The flexiblity and ease of use that come with Python come at the cost of pure performance.

However, though Python code itself may be slow, Python can be used to run code that is written in a compiled language and already compiled. We will use a library (a.k.a., a Python package) that does exactly this underneath the hood to get fast performance for numerical operations on arrays: We load the NumPy package:

import numpy

Class material

The class will be live-coded in a Jupyter notebook. The annotated notebook is available as 06-intro-numpy.ipynb.

You can load the notebook yourself: first update your local PHY494-resources repository1

cd ~/PHY494-resources
git pull

Copy the notebook to your work directory

cd
mkdir ~/PHY494/06_numpy
cd ~/PHY494/06_numpy
cp ~/PHY494-resources/06_numpy/06-intro-numpy.ipynb .

and launch the Jupyter notebook interface in your web browser2:

jupyter notebook

Select the notebook 06-intro-numpy.ipynb from the list.

Basic Jupyter notebook commands:

  • Look at the Help menu! (see also the Jupyter Notebook Online Help)
  • A notebook has two modes
    • edit mode:
      • green box around a cell: you can type into the cell
      • enter edit mode by pressing Enter (or Return) or click on a cell
    • command mode:
      • gray box around a cell (you cannot type into a cell!)
      • keys perform many different actions (don't type randomly…), e.g., cursor keys move up/down, c copies a cell, shift + enter evaluates a cell.
      • enter command mode by pressing ESC or clicking outside a cell's area
  • Evaluate a cell: in command mode (gray cells with blue side bar): shift + return
  • Change a cell type: menu (code is Python, Markdown is text in Markdown format)

Resources


Footnotes

  1. If you have not set up your PHY494-resources repository then revisit Git Basics: Class resources

  2. If you have problems launching the notebook interface on Mac OS X, try

     jupyter notebook --ip=127.0.0.1
    

    If problems persist, google for the error message and ask for help.