Ever since programming BASIC on the Spectrum I’d wondered why it was possible to seed a “random” number generator. But then I found I wanted to do something that would produce repeatable results, but look like a random sequence. Strangely, although JavaScript alongs you to specify a seed for Math.random() the numbers that follow aren’t a repeated sequence. I’m guessing the system clock comes into it.
So after some Googling for an equation to generate numbers I put together the following function. It works on a sequence of 2^32 numbers, in “random” order. (I believed the equation I found – I didn’t test the completeness of it, but it looks pretty random to me.) So, just call Random.next() to get a decimal between 0 and 1, or pass in a range (lower,upper) and you get a random number between the two.
var Random = { seed : 12345, //Returns a random number between 0 and 1 next : function(lower,upper) { var maxi = Math.pow(2,32); this.seed = (134775813 * (this.seed + 1)) % maxi; var num = (this.seed) / maxi; if(typeof lower!='undefined') { var range = upper - lower; num *= range; num += lower; } return num; } }
Set “Random.seed” to taste.