bgneal@30: """Chapter 5.3 exercise 4 in Allen Downey's Think Complexity book. bgneal@30: bgneal@30: "Write a version of plot_ccdf that plots the complementary CCDF on a log-log bgneal@30: scale. bgneal@30: bgneal@30: To test your function, use paretovariate from the random module to bgneal@30: generate 100 values from a Pareto distribution. Plot the CCDF on a log-y scale bgneal@30: and see if it falls on a straight line. What happens to the curve as you bgneal@30: increase the number of values?" bgneal@30: bgneal@30: """ bgneal@30: import random bgneal@30: import sys bgneal@30: bgneal@30: import matplotlib.pyplot as pyplot bgneal@30: bgneal@30: bgneal@30: def plot_ccdf_log_log(x_vals, y_vals, title=''): bgneal@30: """Given a set of x-values and y-values from a continuous distribution, plot bgneal@30: the complementary distribution (CCDF) on a log-log scale. bgneal@30: bgneal@30: """ bgneal@30: if len(x_vals) != len(y_vals): bgneal@30: raise ValueError bgneal@30: bgneal@30: ys = [1.0 - y for y in y_vals] bgneal@30: bgneal@30: pyplot.clf() bgneal@30: pyplot.xscale('log') bgneal@30: pyplot.yscale('log') bgneal@30: pyplot.title(title) bgneal@30: pyplot.xlabel('x') bgneal@30: pyplot.ylabel('1-y') bgneal@30: pyplot.plot(x_vals, ys, label='1-y', color='green', linewidth=3) bgneal@30: pyplot.legend(loc='upper right') bgneal@30: pyplot.show() bgneal@30: bgneal@30: bgneal@30: def main(script, n, alpha): bgneal@30: bgneal@30: n = int(n) bgneal@30: alpha = float(alpha) bgneal@30: bgneal@30: x_vals = range(n) bgneal@30: y_vals = [random.paretovariate(alpha) for x in x_vals] bgneal@30: y_vals.sort(reverse=True) bgneal@30: bgneal@30: plot_ccdf_log_log(x_vals, y_vals, 'paretovariate w/alpha = {}'.format(alpha)) bgneal@30: bgneal@30: bgneal@30: if __name__ == '__main__': bgneal@30: main(*sys.argv)