18

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.

4
  • 6
    "However this method seems inefficient " - have you measured it? Jan 8, 2012 at 7:12
  • 7
    How fast do you need it to be? With the code above I can get 10M random numbers in 500ms on my old laptop. Jan 8, 2012 at 7:17
  • 1
    In most languages, you'd want a random number generator by seeding and mod'ing against some prime. In JavaScript, however, there is more overhead in the evaluation of the language than in the overhead of calls to something like Math.random() meaning that native calls are almost always faster than anything you can implement.
    – user578895
    Jan 8, 2012 at 7:38
  • Try saving the canvas width in a var rather than accessing it everytime. It may be that simple. Jan 8, 2012 at 7:48

8 Answers 8

30

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).

11
  • 1
    It runs significantly faster in almost everything but chrome
    – user578895
    Jan 8, 2012 at 7:39
  • hmm, interesting. I usually do this because I'm lazy and it's easier to read. Jan 8, 2012 at 7:46
  • 1
    @cwolves I just ran it in firefox with the same results... jsperf.com/floor-or-or Jan 8, 2012 at 7:52
  • 2
    @Rasu Don't pre allocate the array. you can achieve 1000x faster for a very large array :)
    – Ghominejad
    Feb 3, 2015 at 22:15
  • 3
    @DaggNabbit In node js it took more than 50 seconds then i had to stop it! because node have to change the default type of the array elements at runtime for million items. but generating 1 million items without pre-allocation took about 100ms! because it pre-allocates itself by type of the first value. you can achieve even more performance by pre-allocating Typed arrays in javascript.
    – Ghominejad
    Feb 5, 2015 at 14:05
4

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.

2

Heres what I use:

function getRandomInt(max) {
    return Math.floor(Math.random() * max);
}

An example of how this would be used would be

function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
if(getRandomInt(420) == 69){
console.log("nice")
}
1

i mostly use

    var a = Math.floor(Math.random((number you'd like to be minimum, (number you'd like to be maximum) * (number you'd like to be maximum);
2
  • 4
    Have you ever heard of using comments in snippets?
    – user9016207
    Jul 29, 2018 at 15:39
  • 6
    Math.random() * (max - min) + min?
    – bryc
    Aug 17, 2018 at 23:18
0

No, there is no easier or shorter way. You can create a function if you need to do it multiple times, though.

0
0
const getRandomInt = (base = 10) => {
  return Math.floor(Math.random() * base)
}
2
  • This is a more 2017-appropriate method than the previous answers Jun 9, 2017 at 19:50
  • This is a more "let's just ignore that Dagg Nabbit has already posted almost the exact same answer" method than the previous answers. Although your code "works", it is a near duplication of Dagg Nabbit's answer. In such a case as this, I would recommend making an edit suggested to his answer instead of posting it as your own answer.
    – Jack G
    Oct 18, 2018 at 20:36
-1

Your way is the right way to retrive a random integer in javascript, don't worry about performance it will run fast.

0
-1

This is the shortest one-liner Random Number Generator code

rnd=(a,b)=>~~(Math.random()*(b-a))+a

How To Use: rnd(min,max) Example : rnd(10,100)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.