Tell us what’s happening:
so im learning javascript and reached this challenge, which requires me to generate a random whole number within a range(104th challenge). I use the formula in the example and passed the challenge. But then im wondering why not just use round function instead of floor function? so i wrote a new code with the round function to see if i’ll pass the challenge. As you can guess this code doesn’t work, i pass all the challenge requirement except the last one and i just can’t understand why this code doesn’t work.
-challenge requirement :
The lowest random number that can be generated by randomRange should be equal to your minimum number, myMin .
Passed
The highest random number that can be generated by randomRange should be equal to your maximum number, myMax .
Passed
The random number generated by randomRange should be an integer, not a decimal.
Passed
randomRange should use both myMax and myMin , and return a random number in your range. Your code so far
function randomRange(myMin, myMax) {
// Only change code below this line
return Math.round(Math.random() * (myMax - myMin)) + myMin;
// Only change code above this line
}
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36.
Challenge: Generate Random Whole Numbers within a Range
I like this explanation I found on reddit, essentially, the odds aren’t equal for each number in the range when using Math.round().
Math.floor(Math.random() * 3) . Here, 0-0.999999 will give you 0, 1.0 to 1.999999 will give you 1, and 2.0 to 2.999999 will give you 2. Every number has a 33% chance of being the result.
Math.round(Math.random() * 2)` . Here, 0-0.499999 will give you 0, 0.5 to 1.499999 will give you 1, and 1.5 to 1.999999 will give you 2. Note that the range of numbers that lead to a 1 is twice as big as those that lead to 0 or 1. That is 25% chance of 0, 50% chance of 1, and 25% chance of 2.
but why does it matter what the odd for each number are? as long as the code generate numbers within a range, i should pass the challenge right? i understand that using math.floor is more consistent, but that’s not the point right?
I think since the goal is to generate a random number, the odds for each number in the range have to be equal. If Math.random() had higher odds to display 0.5-0.99 it wouldn’t be as useful as a function.