from pylab import * # library for making plots from random import * # library for simulating random numbers # toss n coins and count number of consecutive head pairs def consheads(n): count = 0 lastone = randint(0, 1) thisone = randint(0, 1) for i in range(n - 1): if lastone == 1 and thisone == 1: count = count + 1 lastone = thisone thisone = randint(0, 1) return count # for a sequence of event occurrences over time, # calculate the fraction of times the event has occurred so far def frac_occur(events): so_far = 0 frac_times = [] for i in range(len(events)): so_far = so_far + events[i] frac_times.append(so_far * 1.0 / (i + 1)) return frac_times # simulate an poll of size n of an unbiased electorate def poll(n): outcome = [] for i in range(n): outcome.append(randint(0, 1)) return outcome # plot the fraction of polled people voting blue in an unbiased electorate def plot_poll(num_polls, limit=1500): for i in range(num_polls): plot(range(limit), frac_occur(poll(limit))) xlim([0, limit]) ylim([0.0, 1.0]) # sets the boundary values of the y axis show() # displays the plot # indicate whether the triangle with the given vertices is acute def is_acute(x1, y1, x2, y2, x3, y3): def dot(x1, y1, x2, y2, x0, y0): return (x1 - x0) * (x2 - x0) + (y1 - y0) * (y2 - y0) a1 = dot(x2, y2, x3, y3, x1, y1) a2 = dot(x3, y3, x1, y1, x2, y2) a3 = dot(x1, y1, x2, y2, x3, y3) return a1 > 0 and a2 > 0 and a3 > 0 # count the fraction of acute triangles among n random samples # whose vertices are chosen uniformly at random in a square def simulate_triangles(n): count = 0 for i in range(n): if is_acute(uniform(0.0, 1.0), uniform(0.0, 1.0), uniform(0.0, 1.0), uniform(0.0, 1.0), uniform(0.0, 1.0), uniform(0.0, 1.0)): count = count + 1 return 1.0 * count / n