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
They are not truly random because the computer uses an algorithm based on a distribution, and are not secure because they rely on deterministic, predictable algorithms. Since a seed number can be set to replicate the “random” numbers generated, it is possible to predict the numbers if the seed is known.
What that means is that, technically speaking, the numbers that Excel's RAND functions generate aren't truly random. Some companies want to get as random numbers as possible and get creative as to where their random data comes from (like CloudFlare's wall of Lava Lamps).
In the C programming language, the rand() function is a library function that generates the random number in the range [0, RAND_MAX].
The RAND function in stand-alone applications generates the same numbers each time you run your application because the uniform random number generator that RAND uses is initialized to same state when the application is loaded.
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.
random = new Random();
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.
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