numpy_solutions-checkpoint


quant-econ Solutions: NumPy

Tell the notebook to display figures embedded in the browser:


In [1]:
%matplotlib inline

Import numpy and some plotting functionality:


In [2]:
import numpy as np
import matplotlib.pyplot as plt

Exercise 1

This code does the job


In [3]:
def p(x, coef):
    X = np.empty(len(coef))
    X[0] = 1
    X[1:] = x
    y = np.cumprod(X)   # y = [1, x, x**2,...]
    return np.dot(coef, y)

Let's test it


In [4]:
coef = np.ones(3)
print coef
print p(1, coef)
# For comparison
q = np.poly1d(coef)
print q(1)


[ 1.  1.  1.]
3.0
3.0

Exercise 2

Here's our first pass at a solution:


In [5]:
from numpy import cumsum
from numpy.random import uniform

class discreteRV:
    """
    Generates an array of draws from a discrete random variable with vector of
    probabilities given by q.  
    """

    def __init__(self, q):
        """
        The argument q is a NumPy array, or array like, nonnegative and sums
        to 1
        """
        self.q = q
        self.Q = cumsum(q)

    def draw(self, k=1):
        """
        Returns k draws from q. For each such draw, the value i is returned
        with probability q[i].
        """
        return self.Q.searchsorted(uniform(0, 1, size=k))

The logic is not obvious, but if you take your time and read it slowly, you will understand

There is a problem here, however

Suppose that q is altered after an instance of discreteRV is created, for example by


In [6]:
q = (0.1, 0.9)
d = discreteRV(q)
d.q = (0.5, 0.5)

The problem is that Q does not change accordingly, and Q is the data used in the draw method

To deal with this, one option is to compute Q every time the draw method is called

But this is inefficient relative to computing Q once off

A better option is to use descriptors

A solution from the quantecon library using descriptors that behaves as we desire can be found here

Exercise 3

A solution from the quantecon library can be found here

Here's an example of usage


In [9]:
from quantecon import ECDF
F = ECDF(np.random.randn(1000))
F.plot()



In [ ]: