NumPy exercises

Contents

NumPy exercises#

Some of these come from / are inspired from rougier/numpy-100 and http://www.scipy-lectures.org/intro/numpy/exercises.html

You might want to look over these lists as well.

import numpy as np

Q1#

We can use np.random.random_sample() to create an array with random values. By default, these will be in the range [0.0, 1.0). You can multiple the output and add a scalar to it to get it to be in a different range.

Create a 10 x 10 array initialized with random numbers that lie between 0 and 10.

Then compute the average of the array (there is a numpy function for this, np.mean()).

Q2#

Create the array:

[[1,  6, 11],
 [2,  7, 12],
 [3,  8, 13],
 [4,  9, 14],
 [5, 10, 15]]

with out explicitly typing it in.

Now create a new array containing only its 2nd and 4th rows.

Q3#

Create a 2d array with 1 on the border and 0 on the inside, e.g., like:

1 1 1 1 1
1 0 0 0 1
1 0 0 0 1
1 1 1 1 1

Do this using array slice notation to let it work for an arbitrary-sized array

Q4#

  • Create an array with angles in degrees 0, 15, 30, … 90 (i.e., every 15 degrees up to 90).

  • Now create 3 new arrays with the sine, cosine, and tangent of the elements of the first array

  • Finally, calculate the inverse sine, inverse cosine, and inverse tangent the arrays above and compare to the original angles

Q5#

Given the array:

x = np.array([1, -1, 2, 5, 8, 4, 10, 12, 3])

calculate the difference of each element with its neighbor.

Q6#

Here we will read in columns of numbers from a file and create a histogram, using NumPy routines. Make sure you have the data file “sample.txt” in the same directory as this notebook (you can download it from https://raw.githubusercontent.com/sbu-python-summer/python-tutorial/master/day-3/sample.txt

  • Use np.loadtxt() to read this file in.

  • Next, use np.histogram() to create a histogram array. The output returns both the count and an array of edges.

  • Finally, loop over the bins and print out the bin center (averaging the left and right edges of the bin) and the count for that bin.

Q7#

NumPy has a standard deviation function, np.std(), but here we’ll write our own that works on a 1-d array (vector). The standard deviation is a measure of the “width” of the distribution of numbers in the vector.

Given an array, \(a\), and an average \(\bar{a}\), the standard deviation is:

\[ \sigma = \left [ \frac{1}{N} \sum_{i=1}^N (a_i - \bar{a})^2 \right ]^{1/2} \]

Write a function to calculate the standard deviation for an input array, a:

  • First compute the average of the elements in a to define \(\bar{a}\)

  • Next compute the sum over the squares of \(a - \bar{a}\)

  • Then divide the sum by the number of elements in the array

  • Finally take the square root (you can use np.sqrt())

Test your function on a random array, and compare to the built-in np.std()