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