Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Elizabeth Eymann
Elizabeth Eymann
12,196 Points

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,258 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.

Elizabeth Eymann
Elizabeth Eymann
12,196 Points

Aha! That makes so much sense! Thank you!