Número random entre dos valores

He resuelto este ejercicio pero haciendo una pequeña trampa.
Se supone que hay que sumar +1 a (myMax - myMin).
Pongamos que el mínimo es 5 y el máximo 10.
Math.random genera valores entre 0 y 1.
Para el valor mínimo de Math.random 0*(10-5+1)+5 = 5 y ese es el valor mínimo.
Pero para el valor máximo de Math.random 1*(10-5+1)+5 = 1*6+5 = 11, lo cual está mal porque el valor máximo que yo he definido es 10.

function randomRange(myMin, myMax) {
// Cambia solo el código debajo de esta línea
return Math.floor(Math.random() * (myMax - myMin)) + myMin;
// Cambia solo el código encima de esta línea

Desafío: Genera números enteros aleatorios dentro de un rango

Enlaza al desafío:

Math.random generates values between 0 and 1. …
But for the maximum value of Math.random 1 …

That’s not quite right. From the documentation:

The Math.random() function returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1) with approximately uniform distribution over that range.

Note “the range 0 to less than 1 (inclusive of 0, but not 1)”. That means that it might return 0, but it will never return 1. The most it will return is 0.999999… (Or as close as the rounding errors in JS will allow it.) Put another way:

0 <= Math.random() < 1

Why do we have to add 1?

If we want a range that includes the min and max, then what is our range? If we want a number between 1 and 5, then we need a range of 5, because we want 1, 2, 3, 4, or 5. If we use max - min, then we’d get a range of 4. That’s why we need range of 5. With a range of 5, our range of 0 - 0.9999999… becomes 0 - 4.9999999… when we multiply by our range. Then we round down (the range is now 0 - 4) and then add our min, giving us a range of 1 - 5, what we wanted.

Note that we can’t round up is because then our range would become 0 - 5. That would be range of 6. True, the 0 would be extremely, extremely rare, so it would almost work, but why settle for almost?

Does that help?

1 Like