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 trialRichard Barkinskiy
10,663 PointsMath.floor( Math.random() * upper ) + 1;
Just checking. Why is there a "+ 1" at the end of this function? Is it because we're looking for a number between 1 and 10, therefore without it, there's a chance the random number will be 0?
Thanks in advance.
3 Answers
sizwengubane
15,244 PointsExactly, if you want i will explain the entire line of code <blockquotes>
Math.floor( Math.random() * upper ) + 1;
</blockquotes> First we have Math.random() the 'random()' method which acts on the 'Math' object creates a random number between zero and upto but not including one (example: 0.54864038856). Say if you have the number '6' stored in the variable 'upper', when you multiply the method with 'upper' like this Math.random() * upper you will generate a random number between zero and 6. but these are all decimal values (example: 5.464075) so inorder to round them down to the nearest integer we use Math.floor() method. Ok now we are done..but one small error is there...sometimes you will get zero as the random number to avoid this we add 1 at the end of the code like this Math.floor(Math.random() * upper) + 1; If i helped please rate my answer as the best
Jason Anders
Treehouse Moderator 145,860 PointsHi Richard,
That is correct. Without the `+1' there is a chance of it returning a zero.
For example (using 1 to 5), if the Math.random
returns .1105 (as it will return a floating number from (and including 0) to (but NOT including) 1.
If you take that and multiply by 4 (Your high number minus your low number), you get 0.442. This is not between 1 and 5. But when you add 1, you now have 1.442. And, when you use .floor
, it rounds down to 1 and not to ZERO.
I hope this makes sense. Keep Coding! :)
rdaniels
27,258 PointsThe math.random() function only gives a decimal value that is less than 1 (between 0 and .99999).
The Math.random() function returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user.
The 1 being added makes sure that 0 is not a value being returned...
nelsongonzalezarango
6,385 Pointsnelsongonzalezarango
6,385 PointsThis was a very good explanation, thank you!