This project has moved and is read-only. For the latest updates, please go here.

Random numbers not singleton

Jul 7, 2011 at 9:12 PM

Is there a reason behind the decision not to make the random number source for distributions globally configurable, say Control.RandomNumberSource, and a singleton? 

It seems very strange that:

var a = new Normal().Sample()
var b = new Normal().Sample()

will result in a==b because each normal has it's own seed and this seed does not change over very fine durations.

Jul 7, 2011 at 10:06 PM

Hi Tristan,

You're absolutely right that there's multiple ways of designing the random number source. I think our design was motivated mostly to have enough flexibility to give each distribution its own RNG while making sure there wouldn't be any concurrency issues when using lots of RNG's in one single program (and having to lock the global RNG all over the place).

As for your snippet above, I would suggest to not write code like the above. You don't want to be allocating a new Normal just for sampling from it. Much better to write

var n = new Normal()
var a = n.Sample()
var b = n.Sample()

or if you want to allocate even less memory perhaps

var rng = new System.Random()
var a = Normal.Sample(rng,0.0,1.0)
var b = Normal.Sample(rng,0.0,1.0)

Jul 7, 2011 at 10:17 PM

I see, it appears the best solution for my use case is just to use the static methods.

At least in most of my applications, using multiple random number generators in a single program is almost always a mistake, since you typically want randomness that is valid across all the sources.  

For instance sampling a Beta-Bernoulli model via Bernoulli(Beta(2,2).Sample()).Sample() will not be valid unless both Bernoulli and Beta using the same random number source.

I'd lean towards the default being a singleton and if you want to pass in a new random source to the constructor you can.  But I guess this can be done easily enough via the static methods.