Exercises

Simple array manipulation

Investigate the behavior of the statements below by looking at the values of the arrays a and b after assignments:

a = np.arange(5)
b = a
b[2] = -1
b = a[:]
b[1] = -1
b = a.copy()
b[0] = -1

In [ ]:

Generate a 1D NumPy array containing numbers from -2 to 2 in increments of 0.2. Use optional start and step arguments of np.arange() function.


In [ ]:

Generate another 1D NumPy array containing 11 equally spaced values between 0.5 and 1.5. Extract every second element of the array


In [ ]:

Create a 4x4 array with arbitrary values.


In [ ]:

Extract every element from the second row


In [ ]:

Extract every element from the third column


In [ ]:

Assign a value of 0.21 to upper left 2x2 subarray.


In [ ]:

Simple plotting

Plot to the same graph sin and cos functions in the interval $[-\pi/2, \pi/2]$. Use $\theta$ as x-label and insert also legends.


In [ ]:

Pie chart

The file "../data/csc_usage.txt" contains the usage of CSC servers by different disciplines. Plot a pie chart about the resource usage.


In [ ]:

Bonus exercises

Numerical derivative with finite differences

Derivatives can be calculated numerically with the finite-difference method as:

$$ f'(x_i) = \frac{f(x_i + \Delta x)- f(x_i - \Delta x)}{2 \Delta x} $$

Construct 1D Numpy array containing the values of xi in the interval $[0, \pi/2]$ with spacing $\Delta x = 0.1$. Evaluate numerically the derivative of sin in this interval (excluding the end points) using the above formula. Try to avoid for loops. Compare the result to function cos in the same interval.


In [ ]:

Game of Life

Game of life is a cellular automaton devised by John Conway in 70's: http://en.wikipedia.org/wiki/Conway's_Game_of_Life

The game consists of two dimensional orthogonal grid of cells. Cells are in two possible states, alive or dead. Each cell interacts with its eight neighbours, and at each time step the following transitions occur:

  • Any live cell with fewer than two live neighbours dies, as if caused by underpopulation
  • Any live cell with more than three live neighbours dies, as if by overcrowding
  • Any live cell with two or three live neighbours lives on to the next generation
  • Any dead cell with exactly three live neighbours becomes a live cell

The initial pattern constitutes the seed of the system, and the system is left to evolve according to rules. Deads and births happen simultaneously.

Implement the Game of Life using Numpy, and visualize the evolution with Matplotlib's imshow. Try first 32x32 square grid and cross-shaped initial pattern: Try also other grids and initial patterns (e.g. random pattern). Try to avoid for loops.


In [ ]: