How to generate Math.random starting from a value other than 0?

1

Personally, I just know the Math.random method and I already know how to generate values starting from 0 to another number by multiplication, eg Math.random () * 20.

But I'm trying to do the same thing, starting from 5 to 20, I've already swept the net and nobody explains it: /

Thank you in advance for helping me!

    
asked by anonymous 04.10.2014 / 07:16

2 answers

2

The Math.random () is by definition a number between 0 and 1 . What you can do is add the value you want to have the result you want. That is:

var numeroAleatorio = 5 + (Math.random() * 15);

This ensures that the lowest possible result is 5 , and the highest possible is 20 .

In other words, the 5 in this case changes the minimum that this code can give, and the 15 in this case, added with the minimum, will be the maximum that the code can give.     

04.10.2014 / 07:38
2

You can use the following functions:

Returns a random number between the min (inclusive) and max (exclusive):

function getNumeroRandom(min, max) {
    return Math.random() * (max - min) + min;
}

Returns a random number between the min (inclusive) and max (inclusive):

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
  

obs: Using Math.round () will give you a non-uniform distribution, but with the getRandomInt () function you have a perfectly even distribution.

    
04.10.2014 / 09:25