Weighted Random Distribution

W

This is genius; I could have used this a couple of years ago. I’m posting it here for safe keeping. Note that I am NOT using the random class. The random class is not truly random. It’s based on time. Time is predictable.

RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

byte[] result = new byte[8];
rng.GetBytes(result);
double rand = (double)BitConverter.ToUInt64(result, 0) / ulong.MaxValue;

//40 percent chance of being selected.
if (rand > 0.40d )
{
 ...
}

About the author

Chuck Conway

Add comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

By Chuck Conway

About

Chuck is an experienced software consultant creating technical solutions using ASP.Net Core, Angular 2+, React, the cloud (AWS and Azure), Docker, application architecture, agile (SCRUM, Lean), and performance tuning. Chuck lives in Folsom, California with his lovely wife Erin and their tabby, Mango.