Reputation: 357
I have a question about working of Random in C#. Say I want to call some function if variable i == 0. I have the following code:
Random rnd = new Random();
int i = rnd.Next(5);
if (i == 0){
myFunction();
}
So, I would call myFunction() one time per 5 launches of the program. And what if I had another code:
Random rnd = new Random();
for (int j = 0; j < 10; j++){
int i = rnd.Next(50);
if (i == 0){
myFunction();
}
}
Would I have the same result in the final? (calling of myFunction() one time per 5 launches of the program)
Upvotes: 0
Views: 135
Reputation: 346
If you give it a try, running this several times :
class Program
{
static int _caseOneCount = 0;
static int _caseTwoCount = 0;
static Random _rnd = new Random();
static void Main( string[] args )
{
var max = 100000;
for ( var i = 0 ; i < max ; i++ )
{
CaseOne();
CaseTwo();
Console.WriteLine( _caseOneCount.ToString() + "/" + _caseTwoCount.ToString() );
}
}
static void CaseOne()
{
if ( _rnd.Next( 5 ) == 0 )
_caseOneCount++;
}
static void CaseTwo()
{
for ( var i = 0 ; i < 10 ; i++ )
if ( _rnd.Next( 50 ) == 0 )
_caseTwoCount++;
}
}
You will see that the results are nearly equivalent and close to 20% as expected.
Edit : Now if you run CaseOne and CaseTwo only once, you can have :
Edit 2 : following the comments of @Jean-ClaudeColette. The second case corresponds to a binomial distribution (https://en.wikipedia.org/wiki/Binomial_distribution).
So as results, the probability to have :
But the average value stays 20%.
Which means indeed that applying the second case only once will lead to a different result compared to the first case.
Random and its details are in the documentation : https://msdn.microsoft.com/fr-fr/library/system.random(v=vs.110).aspx
And the description of the inner algorithm (Knuth subtractive random generator) is described here (with a C# implementation which is not the .Net implementation but a way to see how it works) : https://rosettacode.org/wiki/Subtractive_generator
Upvotes: 3
Reputation: 752
Actually both your above statements were wrong.
For your first loop, there is no guarantee that your function will get called one time per 5 launches - but if you run it enough times the probability of your function got called is 1/5.
For your second code sample, the probability is 1/50 instead. And your outer (j) loop just controls how many "launches" you are going to run using your words - it doesn't change the probability.
Upvotes: 0