annotate ch5ex3.py @ 32:a13c00c0dfe5

Chapter 5, exercise 6, #1: Barab?si and Albert.
author Brian Neal <bgneal@gmail.com>
date Wed, 09 Jan 2013 20:09:19 -0600
parents 65b70b4e12ad
children
rev   line source
bgneal@29 1 """Chapter 5.3 exercise 3 in Allen Downey's Think Complexity book.
bgneal@29 2
bgneal@29 3 "Write a function called plot_ccdf that takes a list of values and the
bgneal@29 4 corresponding list of probabilities and plots the CCDF on a log-y scale.
bgneal@29 5
bgneal@29 6 To test your function, use expovariate from the random module to generate 100
bgneal@29 7 values from an exponential distribution. Plot the CCDF on a log-y scale and see
bgneal@29 8 if it falls on a straight line."
bgneal@29 9
bgneal@29 10 """
bgneal@29 11 import random
bgneal@29 12 import sys
bgneal@29 13
bgneal@29 14 import matplotlib.pyplot as pyplot
bgneal@29 15
bgneal@29 16
bgneal@29 17 def plot_ccdf(x_vals, y_vals, title=''):
bgneal@29 18 """Given a set of x-values and y-values from a continuous distribution, plot
bgneal@29 19 the complementary distribution (CCDF) on a log-y scale.
bgneal@29 20
bgneal@29 21 """
bgneal@29 22 if len(x_vals) != len(y_vals):
bgneal@29 23 raise ValueError
bgneal@29 24
bgneal@29 25 ys = [1.0 - y for y in y_vals]
bgneal@29 26
bgneal@29 27 pyplot.clf()
bgneal@29 28 pyplot.xscale('linear')
bgneal@29 29 pyplot.yscale('log')
bgneal@29 30 pyplot.title(title)
bgneal@29 31 pyplot.xlabel('x')
bgneal@29 32 pyplot.ylabel('1-y')
bgneal@29 33 pyplot.plot(x_vals, ys, label='1-y', color='green', linewidth=3)
bgneal@29 34 pyplot.legend(loc='upper right')
bgneal@29 35 pyplot.show()
bgneal@29 36
bgneal@29 37
bgneal@29 38 def main(script, lambd):
bgneal@29 39
bgneal@29 40 lambd = float(lambd)
bgneal@29 41
bgneal@29 42 x_vals = range(100)
bgneal@29 43 y_vals = [random.expovariate(lambd) for x in x_vals]
bgneal@29 44 y_vals.sort()
bgneal@29 45
bgneal@29 46 plot_ccdf(x_vals, y_vals, 'expovariate w/lambda = {}'.format(lambd))
bgneal@29 47
bgneal@29 48
bgneal@29 49 if __name__ == '__main__':
bgneal@29 50 main(*sys.argv)