Skip to content

Generate Random Numbers from a Distribution

David Wright edited this page Mar 30, 2018 · 2 revisions

Every distributions in the Meta.Numerics.Statistics.Distributions namespace has a GetRandomValue method that generates deviates distributed according to the distribution. Here is example code that generates 100 normal deviates:

using System;
using Meta.Numerics.Statistics.Distributions;

Distribution distribution = new NormalDistribution(-1.0, 2.0);
Random rng = new Random(1);
List<double> sample = new List<double>();
for (int i = 0; i < 100; i++) {
    double value = distribution.GetRandomValue(rng);
    sample.Add(value);
}

Most of the generators use optimized implementations that are extremely fast.

Why do I need the Random class?

The basis of all non-uniform random number generators is a uniform random number generator (RNG) that generates random numbers between 0 and 1. The .NET Framework's built-in RNG is Random. If you don't want to use built-in RNG, for example because you prefer to an RNG based on the Mersene Twister algorithm, just put your implementation in a class that inherits from Random and override its methods. You can then use Meta.Numerics non-uniform generators on top of your custom Random replacement.

Why do I need a seed?

Notice that the constructor of Random takes an integer, called the seed. Given the same seed, the same sequence of deviates will be generated. This is extremely useful in scientific programming, because if you ever run in to a problem you will want to be able to reproduce the inputs that led to it. If your application requires a new sequence each time, use Random's default constructor, which will generate a seed based on the system clock.

Is deviate generation thread-safe?

No. The Random class itself is not thread-safe, so it doesn't make sense to put a lot of effort into making code built on top of it thread-safe. You could make the whole system thread-safe using locks, but since lock overhead is much greater than the computational effort to generate a random deviate, you are not likely to get the performance boost you wanted from multi-threading with this approach. A better approach is to just give each thread its own instance of Random and the distribution class. Be sure to use a different seed for each Random, or they will all generate the same sequence.

Home

Clone this wiki locally