Differences

This shows you the differences between two versions of the page.

 cs190c:lab6_09 [2009/02/20 10:52]tang cs190c:lab6_09 [2009/02/26 15:53] (current) Both sides previous revision Previous revision 2009/02/26 15:53 tang solution2009/02/20 10:52 tang 2009/02/18 07:58 seh created Next revision Previous revision 2009/02/26 15:53 tang solution2009/02/20 10:52 tang 2009/02/18 07:58 seh created Line 41: Line 41: - Draw a histogram with the same data.  In both plots show the value of p and label appropriately. - Draw a histogram with the same data.  In both plots show the value of p and label appropriately. - Optional: run the VPython visualization of the grid during the simulation. Add this after you have the code producing the correct plots. - Optional: run the VPython visualization of the grid during the simulation. Add this after you have the code producing the correct plots. + + ===== Solution ===== + Note that this solution plots the ratio of red and blue to the TOTAL, rather than red to blue. + + ​from random import uniform, randint + import numpy + import pylab + + def random_grid(size,​ p): + """​ + Generates a grid with '​size'​ rows and '​size'​ columns. Each grid space is + randomly filled with a zero with probability p or a one with probability + (1-p). + + >>>​ random_grid(3,​ 1) + [[0, 0, 0], [0, 0, 0], [0, 0, 0]] + >>>​ random_grid(3,​ 0) + [[1, 1, 1], [1, 1, 1], [1, 1, 1]] + """​ + g = [] + for x in range(size):​ + g.append( * size) + + for row in range(size):​ + for col in range(size):​ + if uniform(0,​1) < p:        # true with probability p + g[row][col] = 1 + else: + g[row][col] = 0 + + return g + + if __name__ == '​__main__':​ + p = input('​Enter a probability p: ') + n = input('​Enter the size of the grid n: ') + TRIALS = 100 + trials = numpy.empty(TRIALS,​ dtype=numpy.float) + for i in xrange(TRIALS):​ + grid = random_grid(n,​ p) + count_red = 0                       # Count the red (=1) squares + for row in grid: + count_red = count_red + sum(row) + + trials[i] = count_red/​float(n**2) + + pylab.plot(range(len(trials)),​ trials, '​r',​ + ​range(len(trials)),​ 1 - trials, '​b',​ + ​range(len(trials)),​ [p]*len(trials),​ ':'​) + pylab.figure() + pylab.hist(trials,​ bins=10, fc='​r'​) + pylab.show()

cs190c/lab6_09.txt · Last modified: 2009/02/26 15:53 (external edit)        