Skip to content Skip to sidebar Skip to footer

Explanation Of Code: Dealing With Min And Max - Javascript

function randomRange(myMin, myMax) { return Math.floor(Math.random() * (myMax - myMin + 1)) +myMin; } I need a refresher on what the return statement is doing. I understand it c

Solution 1:

But I don't get why im subtracting the max from the min and adding + 1 and then +myMin.

First remember that Math.random() returns a value in the range of [0, 1).

Lets start from the end:

  • + myMin is done to ensure that the result is larger or equal to myMin. Lets assume Math.random() returns 0. Then Math.floor(...) returns 0. If we didn't + myMin, return result would be 0 instead of myMin.

  • + 1 is done to get random values that includemyMax. Remember that Math.random() never returns 1, only values close to 1. I.e. the Math.floor(Math.random() * myMax) can never be myMax unless we add 1.

  • myMax - myMin is done because we do + myMin above. We have to account for increasing the result by myMin.

    Lets assume Math.random() returns 0.5 and our range is 100 - 120. Without - myMin, we would get

     Math.floor(0.5 * 120) + 100 = 60 + 100 = 160

    That's clearly larger than 120. If we include - myMin:

     Math.floor(0.5 * (120 - 100)) + 100 = (0.5 * 20) + 100 = 110

    we get 110 which is exactly in the middle of our range (which makes sense intuitively since we get 0.5 as a random value).

Solution 2:

Math.random returns float number between 0 to 1. For example if you take 1 to 10 range. Then Math.random will return minimum 0 and maximum 1 then you multiply it with 10-1=9. And you get 0 to 9. But when you add the minimum it will be increased to 1 to 10.

Solution 3:

Correction - it's not creating a range, it is generating a random Integer number between a given range of numbers ( minimum and maximum number).

E.g. (5, 15) = (min, max)

Will result in a number that is in between this range.

Code explanation :

Math.floor(Math.random() * (myMax - myMin + 1)) +myMin;

Let's assume both max and min are = 15

So the above will look like:

Math.floor(Math.random() * (15 - 15 + 1)) + 15;

Which is equal to = 15, since 0 <= Math.random() * (1) < 1 so the floor of this is 0.

If you don't add that 1, it will not be valid for this corner case.

You add minimum to make sure the value remains between min and max.

Post a Comment for "Explanation Of Code: Dealing With Min And Max - Javascript"