Javascript Function: Random Number Generator
Yesterday, I wrote a short article on generating random numbers in Javascript. The Javascript random number generator is similar to C/++ – it gives you a random number from 0 to 1 and you need to make it useful.
At the suggestion of a reader (thanks Justin), I decided to go ahead and turn the general formula for this into a short helper function to generate a random number.
Random Numbers: General Formula
First, let’s take a minute and recap the general formula for finding a random number.
Javascript’s Math.random() method returns a random number between 0 and 1. By multiplying this decimal value by a whole number, we can generate a desired range of values. For example, by multiplying Math.random()’s result by 10, we get a range of 0 to 10.
Next, we take the Math.floor value of that random number. This gives us just the integer portion – and it effectively cuts our range to 0 through 9. Finally, we can modify this by adding an offset number. So if we wanted a random number between 51 and 60, we’d add 51 to that result.
Creating a Random Number Function
The basic formula we end up with is…
(Math.floor( Math.rand() * setSize)) + setOffset;
Our code would be much more readable if we had a helper function that could be called like this…
randomNumber = rand(min, max);
Our function is going to take two parameters – min and max. From these two parameters, we can calculate the offset and the set size and generate the proper random number.
function rand(min, max) { var offset = min; var range = (max - min) + 1; var randomNumber = Math.floor( Math.random() * range) + offset; return randomNumber; }
All done.
Add that function to a utility file, and you’ve got a handy random number generator at your disposal. It even uses the same format as PHP’s rand() function, to help increase consistency and readability in your code.
Tags: function, Game Design, javascript, math, random, snippet
javascript random number generator » position:relative - a Web and Now blog said this on February 27th, 2008 at 7:19 pm
[...] could use in any project where random numbers are necessary. If you need a random number, read Javascript Function: Random Number Generator, I would recommend you use it in your next [...]
How to Randomize AdSense Ads with Javascript | Web Cash said this on February 29th, 2008 at 6:54 pm
[...] we built a function to get a useful random number out of Math.random(). This is actually a situation where we can use the value from Math.random() just the way it [...]