jeudi 26 novembre 2020

C#: Random.NextDouble method stalling out application

I'm receiving some inconsistent behavior from the Random.NextDouble().

Regularly, the console would freeze and the cpu usage would increase dramatically until I closed it down. I ran the debugger and found that the cause of the freezing was Random.NextDouble(). I added some lines for debugging purposes, but the code is as follows:

        double generateCatenationRate()
        {
            double catenation = 999.999; //random value to see if it pops up down there
            double uniformValue;
            double int_covalence = covalence.original;
            double dist = int_covalence - 4;


            int counter = 0;
            while (true)
            {
                counter++;
                uniformValue = utils.getRandomDouble(); //goes bad here!
                if (uniformValue <= 0.15)
                {
                    catenation = Math.Abs(utils.normalize(dist, 0, 4)) + uniformValue;

                    if (catenation < 0 || catenation > 1)
                    {
                        if (counter > 10000)
                        {
                            Console.WriteLine("Went nuclear!");
                            break; //break so console doesn't stall out
                        }
                        continue;
                    }
                    else
                    {
                        break;
                    }
                }

            }
            Console.WriteLine("Took "+counter+" iterations.");
                return 1 - catenation;
        }

And:

        public static double getRandomDouble()
        {
            Init();
            return random.NextDouble();
        }

Lastly:

        private static void Init()
        {
            if (random == null) random = new Random();
        }

It typically does not stall out, but running it several times successively produces output such as:

Took 4 iterations.
Took 3 iterations
Took 3 iterations.
Took 23 iterations.
Took 12 iterations.
Took 4 iterations.
Went nuclear!
Took 10007 iterations.

Can anyone explain why Random.NextDouble() occasionally seems to create an infinite loop? Looking around, I suspect it has something to do with how the values are seeded, but any insight would be appreciated; would love to fix this issue.

Thank you!




Aucun commentaire:

Enregistrer un commentaire