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 JavaScript Basics (Retired) Working With Numbers Create a random number

Why not use *7 to scale the Math.random() number?

Can you tell me if I'm understanding this correctly?

Math.random() returns a floating point number between 0(included) and 1(excluded).

We're trying to get numbers between 1 and 6, like a die.

So, adding the *6 will scale that random number up by six (right?) For example, the highest random number would be something like .99999999999, and then *6 = 5.99999, and then when Math.floor is applied, it's rounded down to 5. Right?

So why do we add the +1? Why can't we just scale the random number up higher? Like *7?

I know I'm missing a chunk of understanding here, I'm just not sure what it is and my brain is being fuzzy.

I looked here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random to further understand how math.random functions, and I think we're dealing with this formula

// Returns a random integer between min (included) and max (included) // Using Math.round() will give you a non-uniform distribution! function getRandomIntInclusive(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }

This looks like a way to generate numbers between and including two numbers, but how would I use that (max-min) part?

Thank you for your help.

2 Answers

Matt F.
Matt F.
9,518 Points

I believe the reason you add 1 is that you have the six sides required [0, 1, 2, 3, 4, 5] but you just need each one of those values to be one higher [1, 2, 3, 4, 5, 6]. If you multiplied it by 7, you could have 0-6 instead of the desired 1-6.

Oh okay! thank you - that makes a lot of sense!

Hi Stephanie, Another point to consider is when counting using (I believe) all programming languages the count starts at 0 vs. 1. If you want to understand more of why they start at 0 vs. 1 you could look here: http://aplawrence.com/Basics/countfromzero.html