C# random method to find the extreme value of bimodal function to avoid falling into the local optimal solution

To avoid falling into the local optimal solution, just make the step length long enough.
x1 = resultX1 + random1.NextDouble()*100; If it is not multiplied by 100 later, there is a high probability that it will fall into the maximum value of a negative number.
Insert image description here

            Random random1 = new Random(DateTime.Now.Millisecond);
            double x1 = 0, resultX1=0,max=-999999,maxTemp=0;
            for (int i = 0; i < 54321; i++)
            {
    
    
                if (random1.Next(0, 100) % 2 == 0)
                {
    
    
                    x1 = resultX1 + random1.NextDouble()*100;//加大后面的100,即可
                }
                else
                {
    
    
                    x1 = resultX1 - random1.NextDouble()*100;
                }
                maxTemp = Math.Pow(x1, 4) * (-1) + Math.Pow(x1, 3) + 6 * Math.Pow(x1, 2) + 5;
                if (maxTemp > max)
                {
    
    
                    resultX1 = x1;
                    max = maxTemp;
                }
            }
            textBox1.Text = resultX1.ToString();
            textBox2.Text = max.ToString();

Insert image description here

Guess you like

Origin blog.csdn.net/qq_34677276/article/details/132251007