Warning: This document is for an old version of IntroQG. The main version is master.

This page was generated from source/notebooks/L1/numpy.ipynb.
Binder badge
Binder badge CSC badge

A few more useful NumPy functions

In this course we focus more on using simple numerical models and solving equations, rather than on loading and manipulating data files. Thus, one of the things we will often need to do is create an array for a variable that has a range from one value to another. There are two handy NumPy functions we can use for this, which we introduce below.

Getting started

As always, we should start by importing NumPy.

[1]:
import numpy as np

Defining arrays with a fixed number of increments

Let’s say that we want to calculate the sin() of a variable x at 10 points from 0 to \(2 \pi\). We can do this as follows.

[2]:
x = np.linspace(0., 2 * np.pi, 10)
[3]:
print(x)
[ 0.          0.6981317   1.3962634   2.0943951   2.7925268   3.4906585
  4.1887902   4.88692191  5.58505361  6.28318531]

np.linspace() is a NumPy function that will create an array that starts at one value, ends at another, and uses a fixed number of steps between the values. The general syntax is of the form

np.linspace(start, stop, num)

where start will be the first value in the array, stop will be the last, and num is total number of values in the array, with steps that are divided equally between start and stop.

With x defined, we can now move on to calculating sin(x).

[4]:
y = np.sin(x)
[5]:
print(y)
[  0.00000000e+00   6.42787610e-01   9.84807753e-01   8.66025404e-01
   3.42020143e-01  -3.42020143e-01  -8.66025404e-01  -9.84807753e-01
  -6.42787610e-01  -2.44929360e-16]

In this case, x starts at zero and goes to \(2 \pi\) in 10 increments, and y is simply the sine function at those values of x.

Defining arrays with a fixed increment between values

Alternatively, if we wanted to specify the size of the increments for a new variable x2, we could use the np.arange() function.

[6]:
x2 = np.arange(0.0, 2 * np.pi, 0.5)
[7]:
print(x2)
[ 0.   0.5  1.   1.5  2.   2.5  3.   3.5  4.   4.5  5.   5.5  6. ]

In this case, x2 starts at zero and goes to the largest value that is smaller than \(2 \pi\) in increments of 0.5. np.arange() is similar to the linspace() function in the sense that it can be used to create arrays of values. The difference is that here we specify the size of the increment (or step) between values, rather than the number of values in the array. Thus, the syntax is

np.arange(start, stop, step)

where start will be the first value in the array, stop will be excluded from the array, and step is the size of the increment between array values. With this function, the last value in the array will be the largest multiple of step that is smaller than stop.

Both np.linspace() and np.arange() array creation options can be useful in different situations.