Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a program gives me different results from debugging mode

I've provided a simple code which will output 10 random digits that are in between 0 and 100. When I run this in visual studio (C#) using F5, I get the same number 10 times. However, if I run it through debugging mode, line by line using F10 or F11, I get 10 different numbers (may not be all different but they are randomized).

public static void rand() {
    for (int j = 0; j < 10; j++) {
        Random r = new Random();
        Console.WriteLine( r.Next(100));
    }   
}

I know how to fix the issue, which is by instantiating Random r outside of the loop and copy by reference, but I would like to understand why this is happening. I'm thinking that this has something to do with the seed but the program does work while running under debugging mode which confuses me.

Also, now I'm questioning if I'll always need to test whether or not debugging mode is giving me the right results.

like image 832
Charles Han Avatar asked Jun 07 '13 05:06

Charles Han


1 Answers

You should create Random instance ones and before the loop.

public static void rand() {
    Random r = new Random();
    for (int j = 0; j < 10; j++) {        
        Console.WriteLine(r.Next(100));
    }   
}

And here's the explanation:

... The default seed value is derived from the system clock and has finite resolution. As a result, different Random objects that are created in close succession by a call to the default constructor will have identical default seed values and, therefore, will produce identical sets of random numbers. This problem can be avoided by using a single Random object to generate all random numbers. ...

If You want to use different Random instances You should use different seed values. For example j variable:

public static void rand()
{
     for(int j = 0; j < 10; j++)
     {
          Random r = new Random(j);
          Console.WriteLine(r.Next(100));
     }
}

Answering your question: ... if I'll always need to test whether or not debugging mode is giving me the right results.

No, you don't need to doubt in debugging mode results. They are right. Wrong can be your understanding of them.

like image 163
Dmytro Avatar answered Nov 02 '22 23:11

Dmytro