Rob Cable - 8 months ago 41

Javascript Question

`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 creates a range for instance, 5 - 15. But I don't get why im subtracting the max from the min and adding + 1 and then +myMin.

Answer

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**include**`myMax`

. 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).

Source (Stackoverflow)