06.01.2013 Views

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

204 <strong>Learning</strong> <strong>Processing</strong><br />

Example 13-2: Random number distribution<br />

// An array <strong>to</strong> keep track of how often random numbers are picked.<br />

float[] randomCounts;<br />

void setup() {<br />

size(200,200);<br />

randomCounts = new float[20];<br />

}<br />

void draw() {<br />

background(255);<br />

// Pick a random number and increase the count<br />

int index = int(random(randomCounts.length));<br />

randomCounts[index] + + ;<br />

// Draw a rectangle <strong>to</strong> graph results<br />

stroke(0);<br />

fill(175);<br />

for (int x = 0; x < randomCounts.length; x + + ) {<br />

rect(x*10,0,9,randomCounts[x]);<br />

}<br />

}<br />

With a few tricks, we can change the way we use random( ) <strong>to</strong> produce a nonuniform distribution of<br />

random numbers and generate probabilities for certain events <strong>to</strong> occur. For example, what if we wanted<br />

<strong>to</strong> create a sketch where the background color had a 10% chance of being green and a 90% chance of<br />

being blue?<br />

13.4<br />

Probability Review<br />

Let’s review the basic principles of probability, fi rst looking at single event probability, that is, the<br />

likelihood of something <strong>to</strong> occur.<br />

Given a system with a certain number of possible outcomes, the probability of any given event occurring<br />

is the number of outcomes which qualify as that event divided by <strong>to</strong>tal number of possible outcomes. Th e<br />

simplest example is a coin <strong>to</strong>ss. Th ere are a <strong>to</strong>tal of two possible outcomes (heads or tails). Th ere is only<br />

one way <strong>to</strong> fl ip heads, therefore the probability of heads is one divided by two, that is, 1/2 or 50%.<br />

Consider a deck of 52 cards. Th e probability of drawing an ace from that deck is:<br />

number of aces/number of cards � 4/52 � 0.077 � � 8%<br />

Th e probability of drawing a diamond is:<br />

number of diamonds/number of cards � 13/52 � 0.25 � 25%<br />

fi g. 13.1<br />

We can also calculate the probability of multiple events occurring in sequence as the product of the<br />

individual probabilities of each event.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!