Welcome to the Treehouse Community
Looking to learn something new?
Prakhar Patwa11,260 Points
i need some help regarding the js code of this function challenge
I entered the code :
var randomNumber = Math.floor( Math.random() * (upper - lower) ) + lower;
in the video i saw that they entered the code : var randomNumber = Math.floor( Math.random() * (upper - lower + 1) ) + lower;
i wonder why they add "1" in the code my code is still running
Without the +1 you will never have a random number reach the upper variable passed in.
The floor function will always truncate the value
Math.rand will return a number 0-.9999999*...*
.99999999 * (upper - lower) + lower
Will never reach the upper limit, it will be off by a small decimal
So with the +1 off set the highest value returned will be equivalent to .999999... + upper which is then truncated with Math.floor (Which would then make it the upper.)
The documentations reads:
"The Math.random() function returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user."
As you can see the ')' by the 1 means that it will contain every number up until 1 (Not including 1)
Jeff Lemay14,266 Points
Basically, when your upper limit is set to 100 and your lower limit is set to 1, you add the +1 so that you are finding a random number from 100 possibilities. If you exclude the +1, you will only have 99 possibilities (100-1=99).