Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
46
rated 0 times [  51] [ 5]  / answers: 1 / hits: 27097  / 13 Years ago, sun, january 8, 2012, 12:00:00

Normally this is how you get a random number in javascript.


Math.random();

However, this method seems to be inefficient when it comes to generating random integers.


Firstly, the random function has to generate a random decimal, like 0.1036098338663578, then it has to be multiplied to a suitable range (10.464593220502138). Finally, the floor function subtracts the decimals to produce the result (which in this case, 10).


var random_integer = Math.floor(Math.random()*101);

Is there a faster way to generate random integers in javascript?


Edit1:


I am using this for creating a canvas HTML5 game. The FPS is about 50, and my code is pretty optimized, apart from generating a random number.


More From » math

 Answers
92

This code is faster... to type.



var random_integer = Math.random()*101|0;


It won't work right for huge numbers though.



(and it doesn't run any faster, at least not in chrome.)



You could achieve a much faster speed during the game if you generate the random numbers beforehand, though.



for (var i=1e6, lookupTable=[]; i--;) {
lookupTable.push(Math.random()*101|0);
}
function lookup() {
return ++i >= lookupTable.length ? lookupTable[i=0] : lookupTable[i];
}


lookup will rotate through an array with a million random integers. It is much faster than calling random and floor (of course, there is a loading time penalty up front from generating the lookup table).


[#88164] Friday, January 6, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
pariss

Total Points: 255
Total Questions: 99
Total Answers: 117

Location: Hungary
Member since Wed, Nov 9, 2022
2 Years ago
;