4

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?

decPL
  • 5,384
  • 1
  • 26
  • 36
J Fabian Meier
  • 33,516
  • 10
  • 64
  • 142
  • 2
    Don't have time to really dig into it but this might answer your question: [link](http://mathnetnumerics.codeplex.com/discussions/529797) – TylerReid May 07 '14 at 12:11
  • can you show the implementation of Sample function? – Muneeb Zulfiqar May 07 '14 at 12:14
  • Thank you for pointing me to the bug. The new version is apparently not yet on nuGet. Maybe, I just add a minus sign ... – J Fabian Meier May 07 '14 at 12:38
  • 1
    This was fixed in v3.0.0-alpha8 and is also included in the (as of today newest) v3.0.0-beta01 package on NuGet. Until v3.0 final, NuGet only lists them if you enabled pre-release packages though. – Christoph Rüegg May 07 '14 at 13:10
  • For a more general approach to the problem see http://ericlippert.com/2012/02/21/generating-random-non-uniform-data/ – Eric Lippert May 09 '14 at 14:27

1 Answers1

5

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.

pjs
  • 18,696
  • 4
  • 27
  • 56