PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 21, 2022

[FIXED] What is the fastest way to generate a random integer in javascript?

 July 21, 2022     floating-point, integer, javascript, math, random     No comments   

Issue

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.


Solution

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



Answered By - Dagg Nabbit
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing