# Numpy Exercises



In [ ]:

import numpy as np
import vizarray as vz
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('ggplot')



## Checkerboard

Write a Python function that creates a square (size,size) 2d Numpy array with the values 0.0 and 1.0 in a checkerboard pattern.



In [ ]:

def checkerboard(size):
"""Return a 2d checkboard of 0s and 1s as a NumPy array."""



Use vizarray to visualize the checkerboard.



In [24]:



Using tab completion and ? figure out how to list and change the colormap used by vizarray.



In [ ]:



## Stochastic Process

Here is a function that produces standard Brownian motion using NumPy.



In [ ]:

def brownian(maxt, n):
"""Return one realization of a Brownian (Wiener) process with n steps and a max time of t."""
t = np.linspace(0.0,maxt,n)
h = t[1]-t[0]
Z = np.random.normal(0.0,1.0,n-1)
dW = np.sqrt(h)*Z
W = np.zeros(n)
W[1:] = dW.cumsum()
return t, W




In [ ]:

t, W = brownian(1.0, 1000)



Visualize the process using plt.plot with t on the x-axis and W(t) on the y-axis:



In [ ]:



Use np.diff to compute the changes at each step of the motion and then use plt.hist to visualize the distributions of those changes with 30 bins.



In [ ]:



Write a function that takes $W(t)$ and converts it to geometric Brownian motion using the equation:

$$X(t) = X_0 e^{((\mu - \sigma^2/2)t + \sigma W(t))}$$

Use Numpy ufuncs in your function.



In [ ]:

def geo_brownian(t, W, X0, mu, sigma):
"Return X(t) for geometric brownian motion with drift mu, volatility sigma."""



Use your function to simulate geometric brownian motion for $\mu=0.5$ and $\sigma=0.3$ and visualize it using plt.plot.



In [ ]:




In [ ]:



## Factorial

Write a Python function that computes the factorial of small numbers using np.arange and np.cumprod.



In [ ]:

def my_fact(n):
"""Compute n! = n*(n-1)*...*1 using Numpy."""



## Gathering data

Go to http://www.wunderground.com/ and find today's hourly temperature predictions for some location on the planet. Enter that data into a text files named temps.txt using IPython's %%writefile magic command.



In [30]:

%%writefile temps.txt
## Enter your data below, one value per line




Overwriting temps.txt



Load that data as a Numpy array using np.loadtxt:



In [31]:




Out[31]:

array([ 1.,  2.,  3.])



Plot the temperature using plt.plot. For this, you will also need to create a Numpy array of the hours of the day. See if you can figure out how to use plt.title, plt.xlabel and plt.ylabel to label your plot.



In [ ]:



Compute the min, max, mean and variance of the temperature.



In [ ]: