Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Random.Next() always returns same values in for loop

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading