Table of Contents

Mersenne Twister (PRNG)

versions0095+
contributorswatz
started on2006-05-16 10:16

I've been using a replacement for Java's built-in Random class for many years now. java.util.Random is less than mathematically perfect, and is useless when one wants to generate a series of pseudo-random numbers that will be consistent on different computers and VMs.

Looking at Paul Houle's RngPack library, I found an implementation of the Mersenne Twister generator. The Mersenne Twister is considered research-grade, has a very long (2^19937-1) period and produces consistent numbers on different computers. It even computes faster than Math.random(). See Wikipedia: Mersenne Twister for a breakdown of other bonuses, such as “a very high order of dimensional equidistribution”.

I figured it might be useful to other people as well, so I have packaged it as a JAR file for use as a library with Processing. It's very easy to use, as you can see in the code example below.

Source code

/**
mersennetwister taken from http://processinghacks.com/hacks:mersennetwister
@author Marius Watz
*/
 
import mw.randomMT;
 
randomMT rnd=new randomMT(); // Use default seed
rnd=new randomMT(System.currentTimeMillis()); // Use system clock to set seed
 
float val=rnd.random(100);
val=rnd.random(20,50);
println("val "+val);
 
int intval=rnd.randomInt(30);
println("intval "+intval);
 
if(rnd.probGt(60)) println("Probability greater than 60.");
else println("Probability lesser than 60.");
 
println("randomBool returned "+rnd.randomBool());

Downloads

mw_randomMT.zip

Related Links

Paul Houle's RngPack library, which includes other number generators.
Mersenne Twister homepage
Wikipedia: Mersenne Twister
Wikipedia: Pseudorandom number generator