Main content

## Computer programming

### Course: Computer programming > Unit 5

Lesson 2: Randomness# Probability & non-uniform distributions

Remember when you first started programming here? Perhaps you wanted to draw a lot of circles on the screen. So you said to yourself: “Oh, I know. I’ll draw all these circles at random locations, with random sizes and random colors.” In a computer graphics system, it’s often easiest to seed a system with randomness. In these lessons, however, we’re looking to build systems modeled on what we see in nature. Defaulting to randomness is not a particularly thoughtful solution to a design problem—particularly the kind of problem that involves creating an organic or natural-looking simulation.

With a few tricks, we can change the way we use

`random()`

to produce “non-uniform” distributions of random numbers. This will come in handy throughout this course as we look at a number of different scenarios. When we examine genetic algorithms, for example, we’ll need a methodology for performing “selection”—which members of our population should be selected to pass their DNA to the next generation? Remember the concept of survival of the fittest? Let’s say we have a population of monkeys evolving. Not every monkey will have an equal chance of reproducing. To simulate Darwinian evolution, we can’t simply pick two random monkeys to be parents. We need the more “fit” ones to be more likely to be chosen. We need to define the “probability of the fittest.” For example, a particularly fast and strong monkey might have a 90% chance of procreating, while a weaker one has only a 10% chance.Let’s pause here and take a look at probability’s basic principles. First we’ll examine single event probability, i.e. the likelihood that a given event will occur.

If you have a system with a certain number of possible outcomes

*and*each outcome has the same chance of happening, the probability of the occurrence of a given event is equal to the number of outcomes that qualify as that event divided by the total number of all possible outcomes. A coin toss is a simple example—it has only two possible outcomes, heads or tails. There is only one way to flip heads. The probability that the coin will turn up heads, therefore, is one divided by two: 1/2 or 50%.Take a deck of fifty-two cards. The probability of drawing an ace from that deck is:

**number of aces / number of cards = 4 / 52 = 0.077 = ~ 8%**

The probability of drawing a diamond is:

**number of diamonds / number of cards = 13 / 52 = 0.25 = 25%**

We can also calculate the probability of multiple events occurring in sequence. To do this, we simply multiply the individual probabilities of each event.

The probability of a coin turning up heads three times in a row is:

**(1/2) * (1/2) * (1/2) = 1/8 (or 0.125)**

That means that a coin is likely to turn up heads three times in a row

**one out of eight**times (each “time” being three tosses).Want to review probability before continuing? Study compound events and dependent probability.

There are a couple of ways in which we can use the

`random()`

function with probability in code. One technique is to fill an array with a selection of numbers—some of which are repeated—then choose random numbers from that array and generate events based on those choices.Running this code will produce a 40% chance of printing the value 1, a 20% chance of printing 2, and a 40% chance of printing 3.

We can also ask for a random number (let’s make it simple and just consider random decimal values between 0 and 1) and allow an event to occur only if our random number is within a certain range. Check out the example below, and keep clicking restart until the randomly picked number is finally less than the threshold:

This method can also be applied to multiple outcomes. Let’s say that Outcome A has a 60% chance of happening, Outcome B, a 10% chance, and Outcome C, a 30% chance. We implement this in code by picking a random number and seeing into what range it falls.

*between 0.00 and 0.60 (60%) –> Outcome A**between 0.60 and 0.70 (10%) –> Outcome B**between 0.70 and 1.00 (30%) –> Outcome C*

Click the restart button to see how often you get different outcomes:

We could use the above methodology to create a random walker that tends to move to the right. Here is an example of a

`Walker`

with the following probabilities:*chance of moving up: 20%**chance of moving down: 20%**chance of moving left: 20%**chance of moving right: 40%*

This "Natural Simulations" course is a derivative of "The Nature of Code" by Daniel Shiffman, used under a Creative Commons Attribution-NonCommercial 3.0 Unported License.

## Want to join the conversation?

- One question, how do I take the Processing.Js library and move it over to something such as Visual Studio 2013 or another site? Just wondering, it's not like I need any other site but I could do with a little more flexibility.(32 votes)
- Go to http://processingjs.org/download/ and download processing.js. Then you can open it in Visual Studio or any other text editor. If you want to try running Khan Academy programs on your computer, I've written an article on how to do that: http://www.petercollingridge.co.uk/blog/running-khan-academy-programs-your-computer(75 votes)

- why did you put random( 1 )?

don't you need to put two numbers in?(16 votes)- If you put only one parameter, it is assumed that you meant (in this case)
`random(0,1);`

.(36 votes)

- What do they mean by non-uniform(11 votes)
- In a uniform distribution the probability of each event is exactly the same. A non-uniform distribution is just any distribution where the probabilities are not the same.(28 votes)

- Is there a way to time when you get the random values, like if you wanted to get a different random value every 30 seconds?(7 votes)
- That would require some sort of timer, which, sadly, we don't have. (
`setInterval(function, delay)`

doesn't work, sadly)

Bob Lyon has created an excellent timer example, so I'm sure he wouldn't mind you using it (if you provide credit). Now, keep in mind, this will require a bit of adaption, for example, when your timer(s) have run out of time, you'll need to get your random value, and reset the timer. :)

https://www.khanacademy.org/computer-programming/multiple-realtime-timers/5670781774200832(10 votes)

- what's the difference between println and print? please answer.(2 votes)
`println`

will print the specified data to the canvas' console, on a new line.`print`

will print the specified data to the canvas' console, except, it won't create a new line.

http://www.khanacademy.org/cs/printlndata/6120466259378176

http://www.khanacademy.org/cs/printdata/5110798099677184(18 votes)

- I don't understand

if (r < 0.4) {

this.x++;

} else if (r < 0.6) {

this.x--;

} else if (r < 0.8) {

this.y++;

} else {

this.y--;

}

};

How do you know what numbers to put in the if statement?(4 votes)- The random number selector selects a random number between 0 and 1. The if statement is saying that If the random number is less than 0.4, it will move right, If it is between 0.4 and 0.6, it will move left, if it is between 0.6 and 0.8, it will move up, and otherwise (if it is between 0.8 and 1) it will move down. Therefore, each time there is a 40% chance that it will move right, and a 20% chance for each of the other directions. Hope this helps!(10 votes)

- In the up walker challenge I followed the instructions but it says that because I set the x movements both on ten percent it says it can never reach the first step.(1 vote)
- Ok, so you can leave the first one as 0.1 because that will return you a 10% value. Now, try making your next value 0.2. That will return you 10% as well, right, because if its 0.1 it would already be used! Then, for the last one, you put in 0.4 for the 20% and else just stays as else.

Hope this helps!(10 votes)

- I'm having trouble in the next challenge. I'm fairly sure that its right yet it won't let me go on. Here's my code:

Walker.prototype.walk = function() {

var r = random(1);

if (r < 0.2) {

this.x++;

} else if (r < 0.4) {

this.x--;

} else if (r < 0.8) {

this.y++;

} else {

this.y--;

}

};

Can someone point me in the right direction as to what is wrong?(3 votes)- If you look at the hint, it tells you that the walker should have a
`10%`

chance of walking right, a`10%`

chance of walking left, a`60%`

chance of walking up, and a`20%`

chance of walking down. Since the first`if`

statement has the probability of walking right, it should be`0.1`

instead of`0.2`

.

When deciding what values to put into the`if`

statements, it is important to take the difference of two values to find the actual percentage. For example, the probability of the Walker moving down is actually`0.4`

instead of`0.8`

because you must take the difference of`0.8 - 0.4`

to find the actual probability. If you recall what the challenge asks of you, it says that the chances of moving downward should be`20%`

, not`40%`

.

If we use this same idea to find the probability of moving upwards, we find that`1 - 0.8`

is actually`20%`

instead of`60%`

like the challenge asked for. Now that you know something about probability, all you need to do is adjust the numbers to fit the criteria of the challenge.

Good luck and happy coding!(3 votes)

- Is khan academy made with java script?(2 votes)
- However, in a more technical sense, it is a form of JavaScript known as KhanScript, made especially for Khan Academy.(3 votes)

- Can I get some help with the Up Walker challenge? I guess I just don't get it and would like some help.(2 votes)
- First of all, what direction is it going in?

Work that out each time.

Then change the numbers:

If a random number is less than 1 and greater than 0, then here is a way to work out the probability of it being less than 0.1:

Visualise a number line from 0 to 1.There are 10 (1/0.1) sections of 0.1 in there, but it must fall in a specific one.

So the probability equals 1/10.

To work that out for any number:

Do the same thing, but replace 0.1 with the maximum value minus the minimum value, and

when you work the probability in the last step, do 1 divided by, in brackets, 1 divided by the maximum value minus the minimum value.If you check the probability bit you can see why this works.(1 vote)