Main content
Computer programming
Course: Computer programming > Unit 1
Lesson 11: Logic and if Statements- If Statements
- Challenge: Bouncy Ball
- More Mouse Interaction
- Challenge: Your First Painting App
- Booleans
- Challenge: Number Analyzer
- Logical Operators
- Challenge: Your First Button
- Challenge: Smarter Button
- If/Else - Part 1
- Challenge: Flashy Flash Card
- If/Else - Part 2
- Review: Logic and if Statements
- Random numbers
- Project: Magic 8-Ball
© 2023 Khan AcademyTerms of usePrivacy PolicyCookie Notice
Random numbers
Learn how to generate random numbers in ProcessingJS using the random() function, and check their values with if conditions.
We've been using our
if
conditions to check values about the environment, like the user's current mouse position, and respond predictably.But what if we want unpredictability? What if we want our program to act differently each time it runs?
Randomness to the rescue!
We can generate random numbers and use
if
and else if
conditions to change our program's behavior based on the random values.For example:
var randNum = random(0, 10);
if (randNum < 5) {
text("Trick!", 200, 200);
} else {
text("Treat!", 200, 200);
}
The program outputs "Trick!" half of the time, and "Treat!" the other half.
How it works:
- The
randNum
variable is assigned a random number, starting at 0 and including numbers up to 10. Returned values could include 0, 0.2, 3.3, 4, 5.5, 6.9, 8, 9, or 9.99, but not 10 itself. - The condition checks if the returned number is less than 5, outputting "Trick!" if so and "Treat!' otherwise.
Sometimes it's easier to deal with whole numbers instead of floating point numbers, so that we can check exact values. Here are a few functions that turn floating point numbers into integers:
Typically we want to generate random numbers that are picked relatively evenly. For example, if we are simulating flipping a coin, then we expect there to be an equal chance of either "Heads" or "Tails".
This code accomplishes that goal:
var randFlip = floor(random(0, 2));
if (randFlip === 0) {
text("Heads", 200, 200);
} else {
text("Tails", 200, 200);
}
The variable
randFlip
will always be either 0 or 1, since it calls floor()
on the return value of random(0, 2)
. To give you a feel for why that's the case, here's the result of calling
floor()
on various values from random(0, 2)
:random(0, 2) | floor(result) |
---|---|
0.0 | 0 |
0.217… | 0 |
0.542… | 0 |
0.973… | 0 |
1.0 | 1 |
1.332… | 1 |
1.589… | 1 |
1.999… | 1 |
The return values from
random()
are random, so they won't necessarily look as equally distributed as the values in that table. If you run the coin-flipping code just 10 times, you might see a string of all "Heads" or all "Tails". However, if you run it thousands of times and keep count, you'll see "Heads" and "Tails" each about 50% of the time. As a general rule, when our goal is to obtain a fair and even distribution of integer values, it is best to use
floor()
with random()
. The
random()
function is a great way to add a little variety to your programs. However, use it carefully: figure out the range of numbers that you're generating, decide whether you need to round the numbers, and check the values appropriately.You'll have a chance to try that out yourself in the next project!
Want to join the conversation?
- What cases would you want to use
ceil()
?(86 votes)- You have a recipe that makes 20 loaves of bread and requires 3 bags of flour. You decide you only want 10 loaves. How many bags of flour will you need?
When you use floor(3/2)you get 1 and are half a bag short. when you use ceil(3/2), you get 2 and have enough flour.(30 votes)
- how does a computer come up with a random number? that's a question I have a always wondered.(72 votes)
- you can learn about random number generators here https://www.khanacademy.org/computing/computer-science/cryptography(9 votes)
- How come
random()
can return the minimum value passed, but not the maximum?(32 votes)- That is simply the definition of
random
. It is implemented usingMath.random
which return values between zero (inclusive) and one (exclusive).
It also makes sense.(23 votes)
- So the random value can be the first number, but can't be the second number right?(19 votes)
- Correct.
random(a, b)
may returna
, but notb
.(21 votes)
- What cases would you want to use floor()?(7 votes)
- Often you may just want to remove the decimal portion of a value, but floor is also used in cases where you need to segment a large set of numbers into a smaller set of numbers. For example, you divide the 400 X 400 screen into an 8 X 8 grid for some sort of game play. The player moves the mouse over the 400 X 400 screen, but the program needs to know which cell of the 8 X 8 grid the mouse is currently at. Moving horizontally, grid cell 0 extends from screen position 0 to screen position 24, cell 1 extends from position 25 to 49, and so on to cell 7 at positions 375 to 399. To convert from screen coordinates to grid coordinates the formula becomes: gx = floor(sx / 25);(19 votes)
- The randNum variable is assigned a random number, starting at 0 and including numbers up to 10. Returned values could include 0, 0.2, 3.3, 4, 5.5, 6.9, 8, 9, or 9.99, but not 10 itself.
'So how can i include 10 in this formula?'(5 votes)- To generate a random integer between integers
a
andb
inclusive, with a uniform distribution, tryvar r = floor(random(a, b+1));
(13 votes)
- What's the code to generate a random color?(6 votes)
- fill(random(0,255),random(0,255),random(0,255));(12 votes)
- but (random floor) may also lead to the possibility of generating exactly 2.0, then it will also be bias?(3 votes)
- Remember that
random
will never include the upper value.
Take the following code:var randNum = random(0, 10);
The randNum variable is assigned a random number, starting at 0 and including numbers up to 10. Returned values could include 0, 0.2, 3.3, 4, 5.5, 6.9, 8, 9, or 9.99, but not 10 itself.
So, if you had say:floor(random(0, 2));
You will either get 0 or 1, but never 2, becausefloor
always rounds down to the nearest integer value.(13 votes)
- how can I put a if statement to check if a variable is holding
a number or a string?(5 votes)typeof variable === "string"
typeof variable === "number"
(6 votes)
- Is the (a,b) in random() actually equivalent to [a,b) in mathematics?(4 votes)
- Hi Freezeen.
Yes,random(a, b);
will give you a random number within the range [a, b).(8 votes)