I'm working in Microsoft Visual C# 2008 Express.
I found this snippet of code:
public static int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
the problem is that I've run it more than 100 times, and it's ALWAYS giving me the same answer when my min = 0 and max = 1. I get 0 every single time. (I created a test function to run it - really - I'm getting 0 each time). I'm having a hard time believing that's a coincidence... is there something else I can do to examine or test this? (I did re-run the test with min = 0 and max = 10 and the first 50ish times, the result was always "5", the 2nd 50ish times, the result was always "9".
?? I need something a little more consistently random...
-Adeena
The min is inclusive, but the max is exclusive. Check out the API
Several posters have stated that Random() uses a seed based on the current second on the system clock and any other instance of Random created in the same second will have the same seed. This is incorrect. The seed for the parameterless constructor of Random is based on the tick count, or number of milliseconds since boot time. This value is updated on most systems approximately every 15 milliseconds but it can vary depending on hardware and system settings.
The problem with min = 0 and max = 1 is that min is inclusive and max is exclusive. So the only possible value for that combination is 0.
in VB i always start with the Randomize() function. Just call Randomize() then run your random function. I also do the following:
Hope this helps! :)
That overload of Next() returns:
0 is the only possible value for it to return. Perhaps you want random.NextDouble(), which will return a double between 0 and 1.
This initiates random number generator with current time (in sec). When you call your function many times before system clock changed, the random number generator is initiated with the same value so it returns same sequence of values.