Home > Software engineering >  Random.Next() always returns same values in for loop
Random.Next() always returns same values in for loop

Time:03-14

I am currently writing a Program where I want all values of an array to be randomized, although the output of Random.Next() is random, it is not random inside of the for-loop.

My code:

 for (int i = 0; i < simsToRun; i  )
            {
                Simulations[i, 0] = Simulations[i, 0]   (rand.Next(0, 3) / 100) - 0.01f; 
                Simulations[i, 1] = Simulations[i, 1]   (rand.Next(0, 3) / 100) - 0.01f; 
                Simulations[i, 2] = Simulations[i, 2]   (rand.Next(0, 3) / 10) - 0.1f; 
            }

An example of the values after randomization:

Simulations[0, 0] = 0.9

Simulations[0, 1] = 1.1

Simulations[0, 2] = 45

This is as expected, however, this exact pattern repeats itself throughout the loop:

Simulations[1, 0] = 0.9

Simulations[1, 1] = 1.1

Simulations[1, 2] = 45

And so on... Is there any way to fix this?

If you need any extra information, let me know

CodePudding user response:

rand.Next(0, 3) / 100 is always 0. You get an integer thats either 0,1 or 2. Then divide by 100, this gets rounded down to 0.

You want

rand.NextDouble() and the adjust the range of the result to match what yout need. (It returns a number from 0.0 to < 1.0)

  • Related