Strict Standards: Declaration of Doku_Renderer_metadata::table_open() should be compatible with Doku_Renderer::table_open(\$maxcols = NULL, \$numrows = NULL, \$pos = NULL) in /home2/cp-wiki/htdocs/inc/parser/metadata.php on line 480

Strict Standards: Declaration of Doku_Renderer_metadata::table_close() should be compatible with Doku_Renderer::table_close(\$pos = NULL) in /home2/cp-wiki/htdocs/inc/parser/metadata.php on line 480

# CS 190C LAB 6: Friday, February 20, 2009

## Demo Problems

### Optional Arguments for Functions

>>> def f(a, b, c):
print a, b, c

>>> f(1, 2, 3)
1 2 3
>>> f(c=1, b=2, a=3)
3 2 1
>>> def f(a, b, c=3):
print a, b, c

>>> f(1, 2, 3)
1 2 3
>>> f(1, 2)
1 2 3
>>> def f(l=[]):
l.append(1)
return l

>>> f()
[1]
>>> f()
[1, 1]
>>> f()
[1, 1, 1]

## In-Lab Problem

1. The current randomization has a 50% chance to generate red/blue. Change function random_grid(n) to a function random_grid(n,p) where p is the probability of a red box and (1-p) is the probability of a blue box.
2. Change the main code to first prompt the user for n and p. Use a constant TRIALS = 100. Write a simulation which TRIALS times does the following: (i) generate a random grid of size n by n with probability p, (ii) count the number of red and blue squares, (iii) record the ratio.
1. Draw a graph (scatter plot) of the ratio of the observed grid colors using matplotlib (which means you need to keep track of this data).
2. Draw a histogram with the same data. In both plots show the value of p and label appropriately.
3. 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([0] * 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()