Created
May 28, 2020 04:17
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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