Wednesday, February 10, 2010

Mersenne Twister to the Rescue

For Art Evolver I'd like to add a Perlin noise function. The problem with doing this in javascript is the noise is unstable from generation to generation because you can't specify a seed value for Math.random().

Luckily there was an existing implementation of a pseudorandom number generator in javascript here (it's an implementation of Mersenne Twister. The problem with this code is that its functions and state variables are all in the global namespace. Meaning you can only have one generator. I need an arbitrary number of them at any given time, so I wrapped Makoto Matsumoto and Takuji Nishimura's code in a namespace.

Now I can use it like so:
var m = new MersenneTwister(123);

// now calling m.random() four times should return
// the following sequence:
// 2991312382
// 3062119789
// 1228959102
// 1840268610

The namespaced Mersenne Twister code is here.