randomdistribution

Generate random numbers according to distributions


I want to generate random numbers according some distributions. How can I do this?


Solution

  • The standard random number generator you've got (rand() in C after a simple transformation, equivalents in many languages) is a fairly good approximation to a uniform distribution over the range [0,1]. If that's what you need, you're done. It's also trivial to convert that to a random number generated over a somewhat larger integer range.

    Conversion of a Uniform distribution to a Normal distribution has already been covered on SO, as has going to the Exponential distribution.

    [EDIT]: For the triangular distribution, converting a uniform variable is relatively simple (in something C-like):

    double triangular(double a,double b,double c) {
       double U = rand() / (double) RAND_MAX;
       double F = (c - a) / (b - a);
       if (U <= F)
          return a + sqrt(U * (b - a) * (c - a));
       else
          return b - sqrt((1 - U) * (b - a) * (b - c));
    }
    

    That's just converting the formula given on the Wikipedia page. If you want others, that's the place to start looking; in general, you use the uniform variable to pick a point on the vertical axis of the cumulative density function of the distribution you want (assuming it's continuous), and invert the CDF to get the random value with the desired distribution.