I am trying to randomly choose from e.g. 4 numbers. I need to compare the probability of these 2 algorithms.
1#
int a = random.Next(0, 4);
if (a = 0)
statement1
if (a = 1)
statement2
if (a = 2)
statement3
if (a = 3)
statement4
2#
int a = random.Next(0, 1000)
if (a < 250)
statement1
if (a >= 250 && a < 500)
statement2
if (a >= 500 && a < 750)
statement3
if (a >= 750)
statement4
Am I right if I think that it is the same ? The probability of statement1 in the first code is 1/4 and in the second code it is 250/1000 so it’s 1/4 too. But someone has told me when I use bigger range of random numbers like in code 2# it’s statistically more accurate. I’ve made project which repeats many times those codes, but I’m not sure it shows me some results.
They are exactly equivalent (except for the fact that the first one won't compile due to using =
instead of ==
in the if-clauses).
To prove this, look at the implementation of Random.Next(int, int)
. With your values, Random.Next(0, 4)
is
(int) (Random.Sample() * 4)
and
Random.Next(0, 1000)
is
(int) (Random.Sample() * 1000)
, where Random.Sample()
is a private method that returns a random double.
It should now be easy to see that Random.Next(0, 4)
will return 0 exactly when Random.Next(0, 1000)
will return a number between 0 and 250.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With