Exercises on numpy array

Squared numbers

Create a list (using a loop) and an array (without loop) containing the square of integer number from 0 to N-1. Compare execution speed with N=10^6.

Calculation of pi

Without any loop, calculates \pi using the formula :

\pi = \sqrt{12}\sum_{k=0}^{\infty} \frac{(-1)^k}{3^k(2k+1)}

Take care of the integer division in the 2.7 version of Python.

Allan variance

The allan variance of a set of measurements y_k, where each point corresponds to a frequency measured during \tau is defined as :

\sigma_y^2(\tau) = \frac 12 \left<\left(y_{k+1} - y_k\right)^2\right>_k

  1. Write a function that calculates the Allan variance without any loop

Using a data set where the duration of each measurement is \tau_0, it is possible to calculate the Allan variance for duration \tau = n\tau_0 that are mutiple of \tau_0. In this case, the new value is calculated by taking the average value of n consecutive measurements. There is no overlap between the values (there is n times less points compared to the initial set).

  1. Write a function average_frequency(data, n) that calculate the mean value of data with packets of size n.

It is possible to make this function without any loop. Let us start with an array of size 10 and take n=2. The shape of the array is initially:

+--+--+--+--+--+--+--+--+--+--+
|x0|x1|x2|x3|x4|x5|x6|x7|x8|x9|
+--+--+--+--+--+--+--+--+--+--+

Using the rechape method (x.reshape((5,2))), the array will look like:

+--+--+
|x0|x1|
+--+--+
|x2|x3|
+--+--+
|x4|x5|
+--+--+
|x6|x7|
+--+--+
|x8|x9|
+--+--+

The method mean(axis=1) will perform the average line by line.

  1. Write the function AllanVariance(data, n) that calculate the Allan variance for a measurement duration of n\tau_0.

Mandelbrot set

The Mandelbrot set is defined as the set of points c of the complex plane such that the following sequence :

z_0=0

z_{n+1}=z_n^2+c

is bounded.

One can show that if there is a value of n such that |z_n|>2 the the sequence is divergent. To calculate the Mandelbrot set, for each value of c one calculate 100 iterations. The picture is plotted by giving to each point the smallest value of n < 100 such that |z_n|>2 (and 0 if this value doesn’t exist).

Calculate and plot the Mandelbrot set for c such that -2.13 < \operatorname{Re}(c) < 0.77 and -1.13 < \operatorname{Im}(c) < 1.13. One can then zoom on the edge of the set.

Note : to plot an image, use the imshow function of pylab.

The total computation time using numpy efficiently is less than 10 seconds for a 1024x1024 matrix.

_images/mandel_couleur.png

Table Of Contents

Previous topic

Numpy Array

Next topic

Graphics in Python

This Page