mardi 7 novembre 2023

Why does Random.NextInt64 create duplicates and not distribute the values across the whole range

I have written a small C# console application to generate a million random longs

I have already included ThreadLocal to avoid creating duplicates

here if the code I am running:

var random = new ThreadLocal<Random>(() => new Random());
var numbers = new List<long>();

for (int i = 0; i < 1000000; i++)
{
    numbers.Add(random.Value.NextInt64(1, 999999999999));
}

var metrics = numbers.Select(x => x.ToString().Length).GroupBy(x => x).Select(group => new {
    NumberLength = group.Key,
    Count = group.Count()
}).OrderBy(x => x.NumberLength);

var hashSet = new HashSet<long>();
var duplicates = new List<long>();
foreach (var item in numbers)
{
    if (!hashSet.Add(item))
    {
        duplicates.Add(item);
    }
}

this code above is creating:

  • 2 duplicates
  • The numbers generated all seem to be weighted towards the higher end

enter image description here

Why has this out of the box C# method generated duplicate "random" numbers and also not distributed the longs across the whole range?




Aucun commentaire:

Enregistrer un commentaire