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
Gavin Broekema
Full Stack JavaScript Techdegree Student 22,443 PointsMath.random [0,1)
In the random number generator challenge, it is said that Math.random selects a random number between 0 and 1 (with 0 inclusive). This is what I came up with from the exercise:
var randInt = Math.floor(Math.random() * (userIntHigh - userIntLow + 1)) + userIntLow;
In the very rare case that Math.random actually chooses 0, wouldn't the outcome of var randInt become userIntLow? Isn't the intent of this challenge to generate a number between userIntLow and userIntHigh? PS I'm probably just overthinking this.
1 Answer
Steven Parker
243,318 PointsYou're right that if the random function returns 0, you get your lower limit. And if it returns something close to 1 (it can never be exactly 1), you will get your upper limit.
The trick here is that the word between refers to a range that is inclusive of the limits, which is different from what it means in a strictly mathematical sense. In computers it's often used in the inclusive way, another good example is SQL (the common database language).
Gavin Broekema
Full Stack JavaScript Techdegree Student 22,443 PointsGavin Broekema
Full Stack JavaScript Techdegree Student 22,443 PointsSo by adding 1 to (userIntHigh - userIntLow), I am ensuring not only that userIntLow can be generated, but also that userIntHigh can be generated as well? Which leads me to another question... Wouldn't this make the probability of generating userIntLow much lower than the probablity of generating userIntHigh? (seeing that a Math.random value of 0 is much less probable than a value that could be Math.floor--ed down into a userIntHigh equivalent)
Steven Parker
243,318 PointsSteven Parker
243,318 PointsBut 0 is not the only value that will yield your low limit. Because of the decimal multiply, the chances of any of the possible results are the same. Consider this sample mapping of raw random values to five final function values:
Gavin Broekema
Full Stack JavaScript Techdegree Student 22,443 PointsGavin Broekema
Full Stack JavaScript Techdegree Student 22,443 PointsAha! Thank you Steven, this was very helpful. My head sometimes goes to mush after staring at a screen for too long lol.