jmbejara / comp-econ-sp19

Main Course Repository for Computational Methods in Economics (Econ 21410, Spring 2019)
48 stars 26 forks source link

Numpy lecture #21

Closed erineidschun closed 5 years ago

erineidschun commented 5 years ago

From the numpy lecture, there seems to be some code we did not go over (the last 3 chunks of the numpy.ipynb lecture). Are we expected to know this for the midterm?

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))

""" Modifies ecdf.py from QuantEcon to add in a plot method

"""

class ECDF: """ One-dimensional empirical distribution function given a vector of observations.

Parameters
----------
observations : array_like
    An array of observations

Attributes
----------
observations : array_like
    An array of observations

"""

def __init__(self, observations):
    self.observations = np.asarray(observations)

def __call__(self, x):
    """
    Evaluates the ecdf at x

    Parameters
    ----------
    x : scalar(float)
        The x at which the ecdf is evaluated

    Returns
    -------
    scalar(float)
        Fraction of the sample less than x

    """
    return np.mean(self.observations <= x)

def plot(self, a=None, b=None):
    """
    Plot the ecdf on the interval [a, b].

    Parameters
    ----------
    a : scalar(float), optional(default=None)
        Lower end point of the plot interval
    b : scalar(float), optional(default=None)
        Upper end point of the plot interval

    """

    # === choose reasonable interval if [a, b] not specified === #
    if a is None:
        a = self.observations.min() - self.observations.std()
    if b is None:
        b = self.observations.max() + self.observations.std()

    # === generate plot === #
    x_vals = np.linspace(a, b, num=100)
    f = np.vectorize(self.__call__)
    plt.plot(x_vals, f(x_vals))
    plt.show()
jmbejara commented 5 years ago

No, these aren't going to be on the midterm. The exercises at the end of the QuantEcon Numpy and SciPy lecture are good practice, but writing your own classes like this wont be covered.