Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random numbers probability

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.

like image 646
cozzy Avatar asked Oct 14 '22 00:10

cozzy


1 Answers

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.

like image 139
Rasmus Faber Avatar answered Nov 03 '22 09:11

Rasmus Faber