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 trialDinu Comendant
6,049 PointsWhat's the point?
I don't understand what's the point to write
Math.floor(Math.random() * (upper - lower + 1)) + 1;
When I get the same results with:
Math.floor(Math.random() * upper) + lower;
2 Answers
Peter Vann
36,427 PointsHi Dinu!
The actual formula is:
const rand = Math.floor(Math.random() * (upper - lower + 1)) + lower;
Which give you random numbers between and including the upper and lower values.
Your way:
const rand = Math.floor(Math.random() * upper) + lower;
Produces some values above/higher/larger than upper.
Try it with different upper and lower values, such as 17 and 13, or 20 and 15.
I hope that helps.
Stay safe and happy coding!
Thurston Daly
Full Stack JavaScript Techdegree Student 851 PointsHey jas0n,
You're missing the order of operations and that the formula is multiplying against Math.random()
first, which generates a random number using a floating point number. Math.floor()
then rounds down the product of Math.random() and (upper - lower + 1) to either the closest lower number or equal to the generated number (if its whole). Lastly, the final + lower
is increasing the produced number to be inside the range your upper and lower numbers.
Emerson French
Front End Web Development Techdegree Student 4,125 PointsEmerson French
Front End Web Development Techdegree Student 4,125 PointsThank you for Explaining, Peter Van.
ja5on
10,338 Pointsja5on
10,338 Pointswhy is there a + lower at the end?
const rand = Math.floor(Math.random() * (upper - lower + 1)) + lower;
In all my time here it still doesn't make sense! upper say is 6, - lower say 3 = 3. + 1 = 4 + lower again!! which is now 4+3 = 7??