Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
103
rated 0 times [  108] [ 5]  / answers: 1 / hits: 15713  / 11 Years ago, fri, april 5, 2013, 12:00:00

I've seen 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 I'm missing something. Why don't people use the more succint way



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


?



I tried to test the randomness and it seems true so far.



In fact, the subsequent 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]);
}


prints out



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


What am I missing?



Quick OT: Is there a more succint way to declare and initialize frequencies? I mean like frequencies[5] = { 0 }; from C++...


More From » random

 Answers
4

as stated in MDN reference about Math.random()




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




Since Math.random can return 0, then Math.ceil(Math.random()*10) could also return 0 and that value is out of your [1..10] range.






About your second question, see Most efficient way to create a zero filled JavaScript array?


[#79103] Thursday, April 4, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
debras

Total Points: 307
Total Questions: 98
Total Answers: 112

Location: Maldives
Member since Tue, Dec 21, 2021
2 Years ago
;