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?
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.
Javascript creates pseudo-random numbers with the function Math. random() . This function takes no parameters and creates a random decimal number between 0 and 1. The returned value may be 0, but it will never be 1.
2) The preferred way to generate random integer values is by using the nextInt(bound) method of java. util. Random class. This method returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive).
Math. random() is a built-in method that can be used to generate random numbers in JavaScript. The function returns a value between 0 (inclusive) and 1 (exclusive), but we can use another function called Math. floor() to turn our number into a whole random number.
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).
If you want to avoid floating point calculation then you can do that by writing your own pseudo random number generator. Here is a list of well known pseudo random number generators (PRNG). Linear congruential generator is the easiest one to implement and probably most effective in terms of performance too. However, you will need to understand the theory behind PRNGs well enough to write an effective one. That might not be worth of effort though. The JS implementation should be effective enough. At the end there is a high possibility that you will find Math.random()
is running faster than your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With