comparison ch5ex4.py @ 30:5a9a6d1dbf1b

Chapter 5.4, exercise 4, Pareto distributions.
author Brian Neal <bgneal@gmail.com>
date Mon, 07 Jan 2013 20:10:32 -0600
parents
children
comparison
equal deleted inserted replaced
29:65b70b4e12ad 30:5a9a6d1dbf1b
1 """Chapter 5.3 exercise 4 in Allen Downey's Think Complexity book.
2
3 "Write a version of plot_ccdf that plots the complementary CCDF on a log-log
4 scale.
5
6 To test your function, use paretovariate from the random module to
7 generate 100 values from a Pareto distribution. Plot the CCDF on a log-y scale
8 and see if it falls on a straight line. What happens to the curve as you
9 increase the number of values?"
10
11 """
12 import random
13 import sys
14
15 import matplotlib.pyplot as pyplot
16
17
18 def plot_ccdf_log_log(x_vals, y_vals, title=''):
19 """Given a set of x-values and y-values from a continuous distribution, plot
20 the complementary distribution (CCDF) on a log-log scale.
21
22 """
23 if len(x_vals) != len(y_vals):
24 raise ValueError
25
26 ys = [1.0 - y for y in y_vals]
27
28 pyplot.clf()
29 pyplot.xscale('log')
30 pyplot.yscale('log')
31 pyplot.title(title)
32 pyplot.xlabel('x')
33 pyplot.ylabel('1-y')
34 pyplot.plot(x_vals, ys, label='1-y', color='green', linewidth=3)
35 pyplot.legend(loc='upper right')
36 pyplot.show()
37
38
39 def main(script, n, alpha):
40
41 n = int(n)
42 alpha = float(alpha)
43
44 x_vals = range(n)
45 y_vals = [random.paretovariate(alpha) for x in x_vals]
46 y_vals.sort(reverse=True)
47
48 plot_ccdf_log_log(x_vals, y_vals, 'paretovariate w/alpha = {}'.format(alpha))
49
50
51 if __name__ == '__main__':
52 main(*sys.argv)