view ch5ex3.py @ 31:a2358c64d9af

Chapter 5.4, exercise 5: Pareto distribution and city populations.
author Brian Neal <bgneal@gmail.com>
date Mon, 07 Jan 2013 20:41:44 -0600
parents 65b70b4e12ad
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)