C# 随机法求解线性规划问题 蒙特卡洛

线性规划问题:
max=3x1+2x2
x1+2x2<=5
2
x1+x2<=4
4x1+3x2<=9
x1>=0
x2>=0
正确的结果:x1=1.5; x2=1, max z=6.5

            Random random1  = new Random(DateTime.Now.Millisecond);
            Random random2 = new Random(DateTime.Now.Millisecond*DateTime.Now.Millisecond);
            double max=-9999,x1=0,x2=0,resultX1=0,resultX2=0;
            for (int i = 0; i < 654321; i++)
            {
                if (random1.Next(0, 100) % 2 == 0)
                {
                    x1 = resultX1 + random1.NextDouble();
                }
                else
                {
                    x1 = resultX1 - random1.NextDouble();
                }
                if (random2.Next(0, 100) % 2 == 0)
                {
                    x2 = resultX2 + random2.NextDouble();
                }
                else
                {
                    x2 = resultX2 - random2.NextDouble();
                }
                if (x1 + 2 * x2 <= 5 && 2 * x1 + x2 <= 4 && 4 * x1 + 3 * x2 <= 9)
                {
                    if (3 * x1 + 2 * x2>max)
                    {
                        resultX1 = x1;
                        resultX2 = x2;
                        max = 3 * x1 + 2 * x2;
                    }
                }
            }
            textBox1.Text = resultX1.ToString();
            textBox2.Text = resultX2.ToString();
            textBox3.Text = max.ToString();

C# 随机法求解线性规划问题 蒙特卡洛_第1张图片

你可能感兴趣的:(c#,算法,开发语言)