Random number, Math.floor (...) vs Math.ceil (...)

I saw a lot of code where random numbers are generated, like

// random integers in the interval [1, 10] Math.floor(Math.random()*10 + 1) 

Anyway, I feel like something is missing. Why people do not use the more succinic way.

 Math.ceil(Math.random()*10); 

?

I tried to check for randomness and it seems so far.

In fact, the following code

 // will generate random integers from 1 to 4 var frequencies = [ 0, 0, 0, 0, 0 ]; // not using the first place var randomNumber; for ( var i = 0; i < 1*1000*1000; ++i ) { randomNumber = Math.ceil(Math.random()*4); frequencies[randomNumber]++; } for ( var i = 1; i <= 4; ++i ) { console.log(i +": "+ frequencies[i]); } 

displays

 1: 250103 2: 250161 3: 250163 4: 249573 

What am I missing?

Quick OT: is there a more succinic way of declaring and initializing frequencies? I mean frequencies[5] = { 0 }; from c ++ ...

+4
source share
3 answers

as indicated in the MDN link about Math.random()

Returns a pseudo-random floating-point number in the range [0, 1), which is 0 (inclusive), but not including 1 (exception), which you can scale to the desired range.

Since Math.random can return 0 , then Math.ceil(Math.random()*10) can also return 0 , and this value is outside your range [1..10] .


About your second question, see The most efficient way to create a null-filled JavaScript array?

+4
source

Math.floor() is preferred here due to the range of Math.random() .

For example, Math.random() * 10 gives the range [0, 10) . Using Math.floor() , you will never reach the value 10 , while Math.ceil() can give 0 .

+2
source

random integers in the interval [1, 10]:

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

random integers in the interval [0, 10]:

 Math.ceil(Math.random()*10); 

It just depends on what you need.

+1
source

All Articles