<New code>
//PROCESS:
Math.round()
— rounds a number to the nearest integer
//PROCESS:
Math.floor()
— rounds a number downward to the nearest integer
//PROCESS:
Math.ceil()
— rounds a number upward to the nearest integer
//PROCESS:
Math.random()
— creates a random decimal from 0 → 0.99999...
//PROCESS:
var dieRoll =Math.ceil( Math.random() * 6 );
— creates a random integer from 1 → 6
Generating random numbers
Generating a random number between 1 → 6 requires you to do the following:
- generate a random decimal using
Math.random()
- multiplying the random integer by 6
- rounding the result up to the nearest integer
Generating a random integer using Math.random()
There is a function, Math.random()
,
that returns a random number between 0 → 0.999999...
It is not truly random (you need to use something like reading
radioactive decay for that), but it is close enough for
our purposes at this point.
Here is what Math.random()
returns:
Rounding, Floors, and ceilings
There are often times when you want to normally round
a number, and Math.round()
will do this for you in the usual way:
2.3 round()
s normally to:
5.6 round()
s normally to:
Sometimes you want to round down to the nearest integer.
Math.floor()
will do this for you:
2.3 floor()
s down to:
5.6 floor()
s down to:
Sometimes you want to round up to the nearest integer.
Math.ceil()
will do this for you:
2.3 ceil()
s up to:
5.6 ceil()
s up to:
Rolling a die
Let's say for this example that we are using a six-sided die.
We will start off by generating a random decimal:
var randomDecimal =Math.random();
Then we need to multiply this number by six in order to simulate a range from 1 → 6.
-
var unroundedDecimal = randomDecimal * 6;
It still does not look like a die roll from 1 &rarr 6 yet.
Sometimes we get numbers less one, and we never get a number equal to 6.
The function that we need to shape the results into the proper integers is
Math.ceil()
.
-
var dieRoll =Math.ceil(unroundedDecimal);
Putting it all together in one line
So if you combine everything into one line, the resulting code is:
var dieRoll =Math.ceil( Math.random() * 6 );
What about 3 options? 5? 200?
-
var dieRoll = Math.ceil( Math.random() * 3 );
// 3 options -
var dieRoll = Math.ceil( Math.random() * 5 );
// 5 options -
var dieRoll = Math.ceil( Math.random() * 200 );
// 200 options
Common mistakes
-
using
Math.round()
instead ofMath.ceil
This will create a badly weighted die that will generate a number from 0 → 6, like this: - 0: 9%
- 1: 16%
- 2: 16%
- 3: 16%
- 4: 16%
- 5: 16%
- 6: 9%
Learn more
- w3schools.com's Math.round(), Math.floor(), Math.ceil(), and Math.random()