Question

I need a random number generator using a geometric distribution

http://en.wikipedia.org/wiki/Geometric_Distribution.

I tried MathNet.Numerics.Distributions:

public void GeometricTest()
{
    var geometric = new Geometric(0.1);
    int back = geometric.Sample();
    Assert.Greater(back, -1);
}

But the test gives just negative numbers. Does somebody spot my mistake or give me advice for other ways of sampling a geometric distribution?

Was it helpful?

Solution

To generate a geometric with probability p of success on each trial, given a function rand which returns a uniform(0,1) result, pseudocode is:

define geometric(p)
  return ceiling(ln(1-rand) / ln(1-p))

This yields how many trials until the first success. If you want the alternate definition of a geometric (how many failures prior to the first success) subtract 1 or use floor instead of ceiling.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top