view ch5ex3.py @ 29:65b70b4e12ad

Chapter 5, exercise 3.
author Brian Neal <bgneal@gmail.com>
date Sun, 06 Jan 2013 18:11:17 -0600
parents
children
line wrap: on
line source
"""Chapter 5.3 exercise 3 in Allen Downey's Think Complexity book.

"Write a function called plot_ccdf that takes a list of values and the
corresponding list of probabilities and plots the CCDF on a log-y scale.

To test your function, use expovariate from the random module to generate 100
values from an exponential distribution. Plot the CCDF on a log-y scale and see
if it falls on a straight line."

"""
import random
import sys

import matplotlib.pyplot as pyplot


def plot_ccdf(x_vals, y_vals, title=''):
    """Given a set of x-values and y-values from a continuous distribution, plot
    the complementary distribution (CCDF) on a log-y scale.

    """
    if len(x_vals) != len(y_vals):
        raise ValueError

    ys = [1.0 - y for y in y_vals]

    pyplot.clf()
    pyplot.xscale('linear')
    pyplot.yscale('log')
    pyplot.title(title)
    pyplot.xlabel('x')
    pyplot.ylabel('1-y')
    pyplot.plot(x_vals, ys, label='1-y', color='green', linewidth=3)
    pyplot.legend(loc='upper right')
    pyplot.show()


def main(script, lambd):

    lambd = float(lambd)

    x_vals = range(100)
    y_vals = [random.expovariate(lambd) for x in x_vals]
    y_vals.sort()

    plot_ccdf(x_vals, y_vals, 'expovariate w/lambda = {}'.format(lambd))


if __name__ == '__main__':
    main(*sys.argv)