Ok, so this isn’t really in regards to the code so much as understanding HOW and WHY we would get to the conclusion of needing (myMax - myMin + 1)) + myMin ???
I’m just confused how it got there and the instructions didn’t help me make sense of this. Is this just some formula I’m meant to memorize? Was I meant to come to this conclusion naturally?? This is the second code I have just copied the instruction code directly and gotten the right answer, but not actually understood what was going on.
From the challenge:
"Here’s the formula we’ll use. Take a moment to read it and try to understand what this code is doing:
Math.floor(Math.random() * (max - min + 1)) + min"
I don’t under stand what this code is doing.
Thank you in advance for any help
Your code so far
// Example
function ourRandomRange(ourMin, ourMax) {
return Math.floor(Math.random() * (ourMax - ourMin + 1)) + ourMin;
}
ourRandomRange(1, 9);
// Only change code below this line.
function randomRange(myMin, myMax) {
return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin; // Change this line
}
// Change these values to test your function
var myRandom = randomRange(5, 15);
Your browser information:
Your Browser User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36.
I think there are 2 things that are important to understand here:
#1) is that Math.floor() always returns the largest integer less than or equal to a given real number, so even if the argument is (for ex.) 1.9999999, it will always return 1.
#2) is that Math.random() always returns a random number between 0 and 1, that is inclusive of 0 but not of 1
once you understand these 2 things, then for the given example , random range (1,9) take a look at the 2 extreme cases of Math.random(),
(1) Math.random() = 0
For this case, every thing in the parentheses will evaluate to 0 and if you don’t add the min of the range, your result will be 0. And this will not fall in the range of (1,9), hence you add the minimum of the range to it.
(2)Math.random = 0.9999999
For this case, the range (Max-Min) = 8, and when you multiply it by the random number you get 7.99999 , then, when you run Math.floor() on this real number it will evaluate to 7 , finally when you add the minimum of the range to it, the function will only evaluate to 8, meaning that the upper range of the request (9) will never be returned, therefore you must add 1 to your range beforeMath.floor() function is executed.
edit: @BenGitter, also responded with an answer along the same line of thought while I was typing this, just thought I’d post mine anyways.