bgneal@29: """Chapter 5.3 exercise 3 in Allen Downey's Think Complexity book. bgneal@29: bgneal@29: "Write a function called plot_ccdf that takes a list of values and the bgneal@29: corresponding list of probabilities and plots the CCDF on a log-y scale. bgneal@29: bgneal@29: To test your function, use expovariate from the random module to generate 100 bgneal@29: values from an exponential distribution. Plot the CCDF on a log-y scale and see bgneal@29: if it falls on a straight line." bgneal@29: bgneal@29: """ bgneal@29: import random bgneal@29: import sys bgneal@29: bgneal@29: import matplotlib.pyplot as pyplot bgneal@29: bgneal@29: bgneal@29: def plot_ccdf(x_vals, y_vals, title=''): bgneal@29: """Given a set of x-values and y-values from a continuous distribution, plot bgneal@29: the complementary distribution (CCDF) on a log-y scale. bgneal@29: bgneal@29: """ bgneal@29: if len(x_vals) != len(y_vals): bgneal@29: raise ValueError bgneal@29: bgneal@29: ys = [1.0 - y for y in y_vals] bgneal@29: bgneal@29: pyplot.clf() bgneal@29: pyplot.xscale('linear') bgneal@29: pyplot.yscale('log') bgneal@29: pyplot.title(title) bgneal@29: pyplot.xlabel('x') bgneal@29: pyplot.ylabel('1-y') bgneal@29: pyplot.plot(x_vals, ys, label='1-y', color='green', linewidth=3) bgneal@29: pyplot.legend(loc='upper right') bgneal@29: pyplot.show() bgneal@29: bgneal@29: bgneal@29: def main(script, lambd): bgneal@29: bgneal@29: lambd = float(lambd) bgneal@29: bgneal@29: x_vals = range(100) bgneal@29: y_vals = [random.expovariate(lambd) for x in x_vals] bgneal@29: y_vals.sort() bgneal@29: bgneal@29: plot_ccdf(x_vals, y_vals, 'expovariate w/lambda = {}'.format(lambd)) bgneal@29: bgneal@29: bgneal@29: if __name__ == '__main__': bgneal@29: main(*sys.argv)