Thursday, April 7, 2011

Random Numbers on a Bell Curve in C#

Have you ever wanted to generate some random numbers but with a distribution pattern other than the normal even pattern?

Well in a recent project I did.  I wanted a weighted distribution pattern that looked like a bell curve. 

I looked around yes there were some answers, but most got a lot deeper into math than I wanted or needed.  I simply wanted to generate a number with the probability that it was in the center of the range be greater than the probability that it was on the edges – in other words, it fit on a Bell Curve.

I cannot credit what post where gave me the simple solution, or I would post a link.  Here is a simple Extension Method to the Random class. 

It takes two parameters:

  1. Steps: How many numbers in each “Chunk” do you want.  If you want a number between 0 & 600 and set the Steps equal to 50, then the midpoint value (300) will be much more likely than 0 or 300.
  2. MaxValue: The possible range for the random number will be 0 to MaxValue - 1.

Now keep in mind that this is not mathematically perfect.  If you do not choose a step value that is a divisor of your MaxValue then you will not get the full range.  But, having said that, this is a great “Quick & Dirty” way to get a good approximation of a random bell curve.

Code Snippet
  1. public static class RandomExtender
  2. {
  3.     public static int NormalNext(this Random rnd, int Steps, int MaxValue)
  4.     {
  5.         int count = 0;
  6.         int val = 0;
  7.  
  8.         if (Steps < 1) return 0;
  9.  
  10.         while (++count * Steps <= MaxValue) val += rnd.Next(Steps);
  11.  
  12.         return val;
  13.     }
  14. }

Here is a picture of 20,000 random numbers with Steps = 50 & MaxValue = 600.

BellCurve

No comments: