Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Understanding Math.random()

Hello,

I am trying to understand the math logic behind Math.random().

For example, take this equation:

Math.floor(Math.random() * 6 ) +1

Now we will get a random number between 1-6, but WHY?

This is my understanding so far:

Math.random will generate a number between 0-1, but never 1. So, if we add Math.floor, that will round the number down. Then we multiply whatever number that is by 6 and add 1. I don't understand how this produces whole numbers between 1-6. Something is missing in my understanding!

Thanks! Liz

2 Answers

james south
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
james south
Front End Web Development Techdegree Graduate 33,271 Points

the first thing that happens is the random number, from 0 (inclusive) to 1 (exclusive), is generated and multiplied by 6. the result can be as low as 0 and as high as 5.99999999999. the next step is we take the floor of this, so we just drop any decimal part, so the result is a integer from 0 to 5, including 5. then we add 1, so now our range is 1 to 6, including 6.

Aha! That makes so much sense! Thank you!