C# random number generation code

This weekend Code Project posted an updated version of my article Simple Random Number Generation. The article comes with C# source code for generating random samples from the following distributions.

  • Cauchy
  • Chi square
  • Exponential
  • Inverse gamma
  • Laplace (double exponential)
  • Normal
  • Student t
  • Uniform
  • Weibull

After I submitted the revised article I realized I could have easily included a beta distribution generator. To generate a sample from a beta(a, b) distribution, generate a sample u from gamma(a, 1) and a sample v from gamma(b, 1) and return u/(u+v). (See why this works here.)

This isn’t the most efficient beta generator possible, especially for some parameters. But it’s not grossly inefficient either. Also, it’s very simple, and the code in that article emphasizes simplicity over efficiency.

The code doesn’t use advanced C# features; it could easily be translated to other languages.

Related links:

How to test a random number generator
Pitfalls in random number generation
Random number generation in C++
Probability distribution relationship chart

Tagged with: , ,
Posted in Math, Software development
2 comments on “C# random number generation code
  1. Jason Adams says:

    Wanted to drop a quick note that I ported this to Ruby. My tests are less sophisticated, it’s on my TODO to do it up right, but the random number generation appears to be working correctly. And I added the beta distribution per your comment above.


    or view the gem at:


3 Pings/Trackbacks for "C# random number generation code"
  1. [...] This post was mentioned on Twitter by John D. Cook and Probability Fact, Sean Kearney. Sean Kearney said: RT @JohnDCook: New post: C# random number generation code http://bit.ly/9tYsU1 [...]

  2. [...] C# random number generation code [...]

  3. [...] statistics 0 I just published the simple-random ruby gem, which is ported from C# code by John D. Cook.  You can view the source on github or install the gem via [...]