Reputation: 113
While i'm trying to code basic lottery app for myself ( note that i'm really beginner on programming especially c#), a guy on StackOverflow said to me
rnd.Next(1, 50 * 7) % 50 // Randoming like that will be increase to chance of getting 1 and 49
rnd.Next(1, 50 ) // instead of this
I am really wondering how can we test it ? Can we rely on this tests ? Please enlight me
Upvotes: 0
Views: 120
Reputation: 69260
The last example will get a uniform distribution between 1 and 49 (inclusive). That is, the same chance for any number between (and including) 1 and 49.
The first example is much more tricky. It will first create any number between 1 and 349. The modulo 50 maps the number onto the interval 0-49 (including 0 and 49).
We now introduce the possibility to get 0 - if the random number is 50, 100, 150, 200, 250 or 300. We can also get number 1-49 through N+0, N+50, N+100, N+150, N+200, N+250, N+300
That is, 6 chances to get 0 and 7 to get any other number.
The conclusion is that the first example will give a random number betwen 0-49 (inclusive) with slightly less chance of 0 than for the other numbers.
Upvotes: 5