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:

- 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.
- 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.

- public static class RandomExtender
- {
- public static int NormalNext(this Random rnd, int Steps, int MaxValue)
- {
- int count = 0;
- int val = 0;
- if (Steps < 1) return 0;
- while (++count * Steps <= MaxValue) val += rnd.Next(Steps);
- return val;
- }
- }

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

## No comments:

Post a Comment