Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does it appear that my random number generator isn't random in C#?

Tags:

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

like image 515
adeena Avatar asked May 31 '09 17:05

adeena


People also ask

Why are random number generator not random?

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.

Is rand () truly random?

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).

Can you generate random numbers in C?

In the C programming language, the rand() function is a library function that generates the random number in the range [0, RAND_MAX].

Why is rand generating the same number?

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.


2 Answers

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.

like image 198
Annath Avatar answered Sep 19 '22 17:09

Annath


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.

like image 32
mateusza Avatar answered Sep 20 '22 17:09

mateusza