· Chuck Conway · Programming  · 1 min read

Code: Weighted Random Distribution

This blog post presents a method for generating random numbers, with the pitfall of the predictable nature of time-based random number generators.

This blog post presents a method for generating random numbers, with the pitfall of the predictable nature of time-based random number generators.

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 )
{
 ...
}

Share:
Back to Blog

Related Posts

View All Posts »
NVarchar Vs Varchar

NVarchar Vs Varchar

Each engineer defining a new string column decides: Do I use nvarchar or do I use varchar?

C# 8 - Nullable Reference Types

C# 8 - Nullable Reference Types

Microsoft is adding a new feature to C# 8 called Nullable Reference Types. Which at first, is confusing because all reference types are nullable… so how this different? Going forward, if the feature is enabled, references types are non-nullable, unless you explicitly notate them as nullable.