I stumbled upon a mathematical curiosity on Twitter:
Pick random numbers between 0 and 1, until the sum is greater than 1. Repeat forever. The average number of numbers picked will be Euler’s number (e=2.718281828…)
Here is the proof: twitter.com/fermatslibrary/status/961238636418293763
The kids wanted to try, so we coded it in C#:
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
using System; | |
namespace EulerNumberGenerator | |
{ | |
class Program | |
{ | |
static Random rand = new Random(); | |
static void Main(string[] args) | |
{ | |
double sum = 0; | |
int amount = int.MaxValue; | |
for (int i = 0; i < amount; i++) | |
{ | |
int picks = DoRandomPicks(); | |
sum = sum + picks; | |
double avg = sum / (i + 1); | |
Console.WriteLine("Avg:" + avg + " Error: " + (avg – Math.E)); | |
} | |
} | |
static int DoRandomPicks() | |
{ | |
int pickCounter = 0; | |
double sum = 0; | |
while (sum < 1) | |
{ | |
double r = rand.NextDouble(); | |
sum = sum + r; | |
pickCounter++; | |
} | |
return pickCounter; | |
} | |
} | |
} |
Here is a snippet of output:
Avg:2.70660032651792 Error:-0.0116815019411254
Avg:2.70662313432836 Error:-0.0116586941306869
Avg:2.70664593859308 Error:-0.0116358898659632
Avg:2.70666873931292 Error:-0.0116130891461275
Avg:2.70669153648869 Error:-0.0115902919703532
After a few thousand iterations the error went down to around 0.0001
It then occurred to me that this function might be an easy way to test the randomness of a Random Number Generator.
What do you think?