Skip to content

Instantly share code, notes, and snippets.

@ociaw
Created May 28, 2020 04:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ociaw/79d15115f5fdd30522293067a89a8423 to your computer and use it in GitHub Desktop.
Save ociaw/79d15115f5fdd30522293067a89a8423 to your computer and use it in GitHub Desktop.
Demonstrates the high amount of bias in .NET's random number generator, System.Random.
var rng = new Random(42);
var sampleSize = 10_000_000;
var numbers = Enumerable.Repeat(0, sampleSize).Select(_ => rng.Next(0, Int32.MaxValue));
var heads = numbers.Count(x => x % 2 == 1);
Console.WriteLine($"Heads: {heads}, tails: {sampleSize - heads}");
// Output: Heads: 5,036,860, tails: 4,963,140
var popStdDev = Math.Sqrt(0.5 * 0.5);
var popMean = 0.5;
var sampleMean = (Double)heads / sampleSize;
var difference = popMean - sampleMean;
var z = difference * Math.Sqrt(sampleSize) / popStdDev;
Console.WriteLine($"Z score: {z}");
// Output: Z score: -23.3123109107611
// According to my calculator, the probably of this occurring is 0.
// Wolfram Alpha is a bit more precise, giving me 3.326*10^-120.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment