Understanding random numbers Math.floor(Math.random() * (max - min + 1) + min)

Understanding random numbers Math.floor(Math.random() * (max - min + 1) + min)


Preface

As we all know, Math.floor(Math.random() * (max - min + 1) + min) will get a random integer between [min,max]


1. So how to get a random number?

Everyone knows that the Math.random() method will get a random decimal between 0 and 1

But how do you get a random number between 2 and 99?
Insert image description here
The random number is: minimum value + expanded interval

min + Math.random() * (max - min)
So we get a random decimal between (2~99)

Next we just need to convert the decimal into an integer and we’re done!

2. Try

1. Use Math.round() to round decimals

Math.round(Math.random() * (max - min)+min)

function number(min,max){
    
    
return Math.round(Math.random() * (max - min)+min)
};
console.log(number(2,99))
VM495:4 64

It seems that we successfully got the random number but it seems to be different from the Math.floor(Math.random() * (max - min + 1) + min) function in the title.

Failure:
In fact, the number obtained is not random. Due to Math.round() rounding ,
(2~2.5) is 2, and [2.5~3.5) is 3. Obviously this is unfair to 2 and 99. Both of them The random probability is only half that of others


3. Use Math.floor?

To convert decimals to integers in js, we also have Math.floor() to round down to integers: Math.floor(2.8)==2

We got a random decimal between (min,max) above: min + Math.random() * (max - min)

The problem with floor is that
floor is rounded down!
Floor is rounded down!
floor is rounded down! The maximum value cannot be obtained
by using random decimals on the floor . Then (min,max+1), just expand the interval by +1 . Math.floor(Math.random() * (max - min) + min) cannot be obtained to the maximum value max so the final answer: Math.floor(Math.random() * (max - min + 1) + min)



Guess you like

Origin blog.csdn.net/qq_44646982/article/details/120310529