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 The Random Challenge Solution

Math.floor(math.random() * (A - B + 1))+B Gives you a no. btwn 10 to 25 including 10.

as per the video. it gives a number between 10 and 25 including 10. because when math.random() randomly gives 0.02, it becomes 0.02 * (25-10+1) which is 0.32 and when you apply floor, it becomes 0. so 0 + B gives you 10. but not a number between 10 and 25.

whereas, if you put the +1 outside, it gives a number between 10 and 25. ex: Math.floor(math.random() * (A - B)) + 1+ B.

Please correct me If I'm wrong.!! Expecting a quicker response.

Thanks, Ravi.

My guess is that math.random returns only one decimal, for example 0.1, 0.2 etc. Then it makes sense. I don't think that it can return as you wrote 0.32. When you do that math the way I said it, it's gonna be a number between 10 and 25 in this case.

Hope it helps :D

Steven Parker
Steven Parker
231,268 Points

FYI: Regarding precision, here's a typical sample value from Math.random() :point_right: 0.3425137594155696

1 Answer

Steven Parker
Steven Parker
231,268 Points

This is the formula for an inclusive random number range. The reason that 1 is added to A - B is so that the range will be large enough to make it possible for the top number to be selected. If you add one to the value after multiplying, you're just raising (and excluding) the minimum.

So, for example if A = 25 and B = 10:
"Math.floor(Math.random() * (A - B + 1)) + B" will produce a number from 10 to 25, but
"Math.floor(Math.random() * (A - B)) + 1 + B" will produce a number from 11 to 25.

That second formula is halfway to being the one for an exclusive range, which is:
"Math.floor(Math.random() * (A - B - 1)) + 1 + B" .