If you're seeing this message, it means we're having trouble loading external resources on our website.

If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.

Course: Computer programming - JavaScript and the web>Unit 5

Lesson 2: Randomness

Normal distribution of random numbers

Let's say we want to make that program that generates a world of monkeys. Your program could generate a thousand Monkey objects, each with a height value between 200 and 300 (as this is a world of monkeys that have heights between 200 and 300 pixels).
var randomHeight = random(200, 300);
Does this accurately depict the heights of real-world beings? Think of a crowded sidewalk in New York City. Pick any person off the street and it may appear that their height is random. Nevertheless, it’s not the kind of random that random() produces. People’s heights are not uniformly distributed; there are a great deal more people of average height than there are very tall or very short ones. To simulate nature, we may want it to be more likely that our monkeys are of average height (250 pixels), yet still allow them to be, on occasion, very short or very tall.
A distribution of values that cluster around an average (referred to as the “mean”) is known as a “normal” distribution. It is also called the Gaussian distribution (named for mathematician Carl Friedrich Gauss) or, if you are French, the Laplacian distribution (named for Pierre-Simon Laplace). Both mathematicians were working concurrently in the early nineteenth century on defining such a distribution.
When you graph the distribution, you get something that looks like the following, informally known as a bell curve:
The curve is generated by a mathematical function that defines the probability of any given value occurring as a function of the mean (often written as μ, the Greek letter mu) and standard deviation (σ, the Greek letter sigma).
The mean is pretty easy to understand. In the case of our height values between 200 and 300, you probably have an intuitive sense of the mean (i.e. average) as 250. However, what if I were to say that the standard deviation is 3 or 15? What does this mean for the numbers? Looking at graphs can give us a hint. The graph above shows us the distribution with a very low standard deviation, where the majority of the values cluster closely around the mean. The graph below shows us a higher standard deviation, where the values are more evenly spread out from the average:
Not familiar with the concept of "standard deviation"? Don't worry! You can study Variance and standard deviation separately on Khan Academy before continuing.
The numbers work out as follows: Given a population, 68% of the members of that population will have values in the range of one standard deviation from the mean, 95% within two standard deviations, and 99.7% within three standard deviations. Given a standard deviation of 5 pixels, only 0.3% of the monkey heights will be less than 235 pixels (three standard deviations below the mean of 250) or greater than 265 pixels (three standard deviations above the mean of 250).
Calculating Mean and Standard Deviation
Consider a class of ten students who receive the following scores (out of 100) on a test:
85, 82, 88, 86, 85, 93, 98, 40, 73, 83
We calculate the mean (the average) by summing up all the scores and dividing by the number of scores.
Mean = $\left(85+82+88+86+85+93+98+40+73+83\right)/10=81.3$
The standard deviation is calculated as the square root of the average of the squares of deviations around the mean.
The first step is to calculate the deviations for each score (the difference from the mean) and square the deviations:
ScoreDeviationSquared deviation
$85$$85-81.3=$$3.7$$\left(3.7{\right)}^{2}=$$13.69$
$82$$82-81.3=$$0.7$$\left(0.7{\right)}^{2}=$$0.49$
$88$$88-81.3=$$6.7$$\left(6.7{\right)}^{2}=$$44.89$
$86$$86-81.3=$$4.7$$\left(4.7{\right)}^{2}=$$22.09$
$85$$85-81.3=$$3.7$$\left(3.7{\right)}^{2}=$$13.69$
$93$$93-81.3=$$11.7$$\left(11.7{\right)}^{2}=$$136.89$
$98$$98-81.3=$$16.7$$\left(16.7{\right)}^{2}=$$278.89$
$40$$40-81.3=$$-41.3$$\left(-41.3{\right)}^{2}=$$1705.69$
$73$$73-81.3=$$-8.3$$\left(-8.3{\right)}^{2}=$$68.89$
$83$$83-81.3=$$1.7$$\left(1.7{\right)}^{2}=$$2.89$
Then we calculate the average of the squared deviations, known as the variance. That's the sum of the final column divided by the number of rows:
Variance = $2288.1/10$ = $228.81$
Finally, we calculate the standard deviation by taking the square root of the variance:
Standard deviation = $\sqrt{228.81}$ = $15.13$.
Want to understand standard deviation better? You can study Variance and standard deviation in more depth here on Khan Academy.
Luckily for us, to use a normal distribution of random numbers in a program here, we don't have to do any of these calculations ourselves. Instead, we can make use of the Random object provided by ProcessingJS.
To use Random, we must first instantiate a new Random object, passing in 1 as the parameter. We call that variable "generator" because what we've created can be basically thought of as a random number generator.
var generator = new Random(1);
If we want to produce a random number with a normal (or Gaussian) distribution each time we run through draw(), it’s as easy as calling the function nextGaussian().
var num = generator.nextGaussian();
println(num);
So, now, what are we supposed to do with this value? What if we wanted to use it, for example, to assign the x-position of a shape we draw on screen?
The nextGaussian() function returns a normal distribution of random numbers with the following parameters: a mean of zero and a standard deviation of one. Let’s say we want a mean of 200 (the center horizontal pixel in a window of width 400) and a standard deviation of 60 pixels. We can adjust the value to our parameters by multiplying it by the standard deviation and adding the mean.
var standardDeviation = 60;
var mean = 200;
var x = standardDeviation * num + mean;
Now, we can create our program that draws semi-transparent circles according to a normal distribution. The darkest spot will be near the center, where most of the values cluster, but every so often circles are drawn farther to the right or left of the center.
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?

• During step 2 of challenge the Gaussain Walk, i didn't know whether to make a new variable or if i was just doing the stepsize equation wrong. I need help with the equation and whether or not to make a new variable.
• A year late but hopefully it helps. Yes you do create a new variable. Like this:

Walker.prototype.walk = function() {
var num1 = generator.nextGaussian();
var xStepSize = standardDeviation * num1 + mean;
var num2 = generator.nextGaussian();
var yStepSize = standardDeviation * num2 + mean;

this.x += xStepSize;
this.y += yStepSize;
};
• Hi guys can anyone explain to me why you have to use new Random? I understand that its making the generator a object, but why does random have to be capitalized and is there something I'm missing because I don't remember learning to make objects like that - with just the new key. Thanks.
• From the author:Have you gone through the object-oriented JS lessons in the intro? The Random() is an object that you have to initialize to use, and once you do, you can then call methods on it like nextGaussian(). It's like:
var winston = new Winston();winston.eat();
• why do you have the parameter set to one? i tried playing with the number, but it didn't seem to change that much on the canvas.
• The parameter of Random() is called a seed and it allows for reproducability. To fix a bug found in a program, it is necessary to have the code do the same thing every time, which is the purpose of a seed: by using a constant, such as 1, as the seed, the program will do the same thing every time you press reset; the same random numbers will be produced in the same order every time. If you switch to a different constant, such as pi, a different set of random numbers will be chosen, but the same new numbers will be chosen, in the same order, every time you restart the program. To get the code to choose different numbers every time the program is run, you must pass a number that changes every time the program is run. A common method, as AwesOmeMaster suggests in a comment above, is to call a function to get the time in seconds and use that as the seed.
• I don't understand what they want me to do for the Gaussian walk. I used the method shown here but it doesn't work. Could you give a hint that points me in the right direction. Here's my code:
var Walker = function() {    this.x = width/2;    this.y = height/2;};Walker.prototype.display = function() {    strokeWeight(3);    stroke(0, 0, 0);    point(this.x, this.y);};var generator = new Random(1);var num = generator.nextGaussian();var standardDeviation = 2;var mean =  0;// Randomly move up, down, left, right, or stay in one placeWalker.prototype.walk = function() {    var xStepSize = standardDeviation * num + mean;    var yStepSize = standardDeviation * num + mean;      this.x += xStepSize;    this.y += yStepSize;};var w = new Walker();var draw = function() {    w.walk();    w.display();};
• Okay, I don't think it wants you to make a new var named num. my walk function looks like this, and it seems more random.

Yours seems to go in a straight line, pretty much.

I had what you have at first, probably, because I expect whatever was recently done to be done again for the challenge, but it didn't work.

Anyways,

Walker.prototype.walk = function() {        var xStepSize = standardDeviation * generator.nextGaussian() + mean;    var yStepSize = standardDeviation * generator.nextGaussian() + mean;        this.x += xStepSize;    this.y += yStepSize;};

Granted, I already had this farther at the top outside of my functions.

var generator = new Random(1);var standardDeviation = 2;var mean = 0;

To be honest, mine isn't passing me either, and I don't know why.
Perhaps I have some weird mistake somewhere i'm just not seeing, but mine is going in random directions and all so I personally don't see what's wrong, but anyways perhaps my example can help you figure yours out. shrug
• Isn't the standard normal curve - standard deviation rule 68-95-99.7, you have listed 68 then 98? then 99.7? (I think it should be 95 instead of 98
• Excellent catch. Mistakes such as these can be reported using the "Report a mistake in the article" button at the top-right of the discussion section. I have done so.
• what number 1 in
var generator=new Random( 1 );
means?
• It's called a seed.
The Random class doesn't really generate random numbers. Computers aren't capable of generating truly random numbers. They can only generate numbers that seem random to us: pseudo random numbers.

The Random class generates the same sequence of numbers every time. That's not very random at all. You can try that with a program.
var generator = Random(1);var mouseClicked = function() {    println(generator.nextGaussian());};

You'll see a different number every time you click. But Restart the program and you'll see the same list of numbers again.

Now try it again, but change the seed.
var generator = Random(2);var mouseClicked = function() {    println(generator.nextGaussian());};

Restart the program and click the mouse. You'll get a different sequence of numbers.

Ideally you would want a different seed every time the program starts up. The best way to do that is to use time.
var generator = Random(hour() + minute() + second() + millis());var mouseClicked = function() {    println(generator.nextGaussian());};
• My "Paint Splatter" project keeps on producing a splatter plot with the same exact colors and spots every restart it, which raises some questions. I'm not sure what my issue is. I can't find any information on this Random object, is it a Khan Academy thing?

My code is below:

var generator = new Random(1);var stdDev = 200/3; var mean = 200; var numDrops = 1000;  //number of paint dropsvar  colorStdDev = 200;var randomColor = function(){        var rColor = colorStdDev * generator.nextGaussian() + 255/2;    var gColor = colorStdDev * generator.nextGaussian() + 255/2;    var bColor = colorStdDev * generator.nextGaussian() + 255/2;    var randColor = (rColor , gColor, bColor);    return randColor;};for(var i = 1; i < numDrops ; i++){        var xPos = mean + generator.nextGaussian()*stdDev; //random gaussian x-position    var yPos = mean + generator.nextGaussian()*stdDev; //random gaussian y-position    noStroke();    fill( randomColor() ); //color is from randomColor    ellipse( xPos, yPos, 10, 10);}
• The 1 as the argument to the Random constructor guarantees that it will reproduce exactly the same number sequence every time. If you want different results, then randomize the seed, e.g.
var generator = new Random(random(0, 2000000000));
• For step 2 of the upcoming challenge, I can't seem to progress, yet I have working code. Why?

var generator = new Random(1);
var standardDeviation=2;
var mean= 0;

var Walker = function() {
this.x = width/2;
this.y = height/2;
};

Walker.prototype.display = function() {
strokeWeight(3);
stroke(0, 0, 0);
point(this.x, this.y);
};
var num = generator.nextGaussian();
// Randomly move up, down, left, right, or stay in one place
Walker.prototype.walk = function() {

var xStepSize = standardDeviation * generator.nextGaussian() + mean;

var yStepSize = standardDeviation * generator.nextGaussian() + mean;

this.x += xStepSize;
this.y += yStepSize;
};

var w = new Walker();

draw = function() {
w.walk();
w.display();
};
var r1 = new Random( 1 ); // value is requiredvar r2 = new Random( 2 );println( r1.nextGaussian() );println( r2.nextGaussian() );