Mercurial > public > think_complexity
changeset 29:65b70b4e12ad
Chapter 5, exercise 3.
author | Brian Neal <bgneal@gmail.com> |
---|---|
date | Sun, 06 Jan 2013 18:11:17 -0600 |
parents | 15ff31ecec7a |
children | 5a9a6d1dbf1b |
files | ch5ex3.py |
diffstat | 1 files changed, 50 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/ch5ex3.py Sun Jan 06 18:11:17 2013 -0600 @@ -0,0 +1,50 @@ +"""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)