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.

Main content

Generating random numbers

Have you ever flipped a coin or rolled a dice? If so, you generated a random value — and you probably used that value to make a decision.
We can also generate random values in our computer programs, and use those to make decisions and simulate natural processes.

Generating random values

Computers aren't naturally very good at randomness. Their strength is in generating predictable output by performing sequences of programmed operations. That's just about the opposite of randomness.
To generate a truly random number, a computer would need to monitor a naturally occurring non-deterministic process, like the nuclear decay of an uranium particle. That's both expensive and slow, so most personal computers do not have true random number generators.
However, computer scientists have figured out ways to generate "pseudo-random" numbers in computer software, and the pseudo-random numbers are good enough for most purposes.
Programming languages and libraries provide procedures to generate those pseudo-random numbers.
In JavaScript, Math.random() generates a pseudo-random number between 0 (inclusive) and 1 (exclusive).
The program below displays a number generated from Math.random(). Press "Restart" to see how it changes each time.
When called enough times, Math.random() will eventually generate the number 0. However, it will never generate 1. That's why we say it's "inclusive" of 0 and "exclusive" of 1.
This number line visualizes all the possible generated values in blue:
What if we need a bigger number? Perhaps our program is drawing a tree and is choosing to draw it at a height from 0 to 6 feet.
We can do that by multiplying the result of Math.random() by 6. Try it out below.
That program generates values between 0 (inclusive) to 6 (exclusive):

Generating random integers

What about limiting the random values to just integers? If we're simulating a dice roll, we don't want to end up with numbers like "1.267" or "5.431". We just want to see integers, representing each side of the die.
For this, we need to round the result using Math.floor(). The floor() procedure will round the value down to the nearest integer.
Try it out below. Can you generate all the possible integers in the range?
Once you restart that program enough times, you should eventually see it display all of the integers from 0 to 5:
We're very close to simulating the roll of a die, but not quite there. Our program generates the numbers 0-5, but a standard 6-sided die corresponds to the numbers 1-6:
This is an easy fix. We'll just add 1 to the rounded result, and presto, we have a dice rolling simulation!
We might find that we frequently want to generate random integers between two values. We could copy and paste the code from above... or, better, we could make our own reusable procedure!
The procedure randomInt() is a handy abstraction on top of Math.random(), allowing us to generate random integers without worrying about the details:

Checking random values with conditionals

Now that we know how to generate many ranges and types of random numbers, let's actually use those numbers.
We can use a conditional to check the value of a random number and select different code to execute based on the value.
For example, this code simulates a random coin flip:
if (Math.random() < 0.5) {
} else {
📝 See similar code in: App Lab | Snap | Python
When we're using a conditional to check a random value, we need to make sure our condition corresponds to the chance that the event should happen. In the code above, Math.random() generates values from 0 to 1, so the condition checks whether the value is in the first half of that range.
If we're simulating chances like "1 in 4", that's a great time to use a chained if/else with the randomInt() procedure from above:
var val = randomInt(1, 4);
if (val === 1 ) {
} else if (val === 2 ) {
} else if (val === 3 ) {
} else {
📝 See similar code in: App Lab | Snap | Python
When we're checking to make sure code like that works as expected, we can't just run it once; that will only show one value and one code path. We need to run it multiple times, making sure the computer eventually selects every possible path.
If we want even more confidence, we could run it thousands of times and verify that the distribution of code paths matches our expectations. For the code above, we'd see each path selected about 25% of the time. It wouldn't be exactly 25%, but it'd be close.
✏️ The program below simulates a Magic 8-Ball toy with 7 different responses. Change the messages to your liking and restart the program enough times to make sure all your messages get displayed.
📝 See similar code in: App Lab | Snap | Python

Random numbers in pseudo-code

There's a lot of variance in the random number generation procedures across programming languages and libraries.
This pseudocode represents the common case of generating a number between start and end (including both start and end):
RANDOM(start, end)
Here's a pseudocode version of the code that generates 1 in 4 chances:
val ← RANDOM(1, 4)
IF (val = 1 )
ELSE IF (val = 2 )
ELSE IF (val = 3 )
🙋🏽🙋🏻‍♀️🙋🏿‍♂️Do you have any questions about this topic? We'd love to answer— just ask in the questions area below!

Want to join the conversation?