The problem of obtaining Random numbers by js

for example, if you get a random number of 0 to 10, you can think of the following two kinds of

Math.ceil(Math.random()*10);
Math.floor(Math.random()*(10+1));

but see that someone says to use Math.ceil (Math.random () * 10); the chance of taking 0 is very small.
when you use Math.floor (Math.random ()) * (10: 1));), you can get a balanced random integer from 0 to 10.
is this really the case? Is it possible to use floor instead of ceil to get random numbers later?

Feb.28,2021

ceil is rounded up, and Math.ceil (Math.random () * 10) is 0 only when 0 is taken, so the probability is very small.
floor is rounded down, Math.ceil (Math.random () *) (10: 1)), equals that you take between 0 and 11, and the number you get is rounded down. Relatively speaking, the integer probability of getting 0-10 is about


.

if it is an integer of [0code 10], the standard method is Math.floor (Math.random () * (103.1))
if it is an integer of [0heroin 10), the standard method is Math.floor (Math.random () * 10)
there is a problem no matter how you handle it with ceil.

if it is an integer of (0 code 10], the standard method is Math.ceil (Math.random () * 10) , then there will be problems with floor.


this is a mathematical problem. First of all, you have to understand that Math.ceil is rounded up, that is, if a decimal such as 0.0000000000000000000000001 is rounded up, it will also be 1 ; then there is the question of value range, $Math.random ()\ in [0,1) $$, $Math.ceil (Math.random ())\ in [0,1] $) after rounding up, at this time, $$Math.ceil (Math.random ()) = 0,1) is a necessary and sufficient condition for $Math.random. Suppose Math.random () is an ideal random number generator (accurate to infinity after the decimal point), then $$P (Math.random () = 0) = 0 percent, and if Math.random () is accurate to n place after the binary decimal point, then $$P (Math.random () = 0) = 1 / 2 ^ n $. See for yourself how small the probability is.


upstairs has explained the difference very well. There is another way to try ~ (0 + Math.random () * 10)

.
Menu