求二次方程的最小值和最大值

时间:2014-04-24 09:34:42

标签: c# max min equation quadratic

如何使用c#??

找到二次方程的最小值和最大值
f(x,y) = x^2 + y^2 + 25 * (sin(x)^2 + sin(y)^2) ,where (x,y) from (-2Pi, 2Pi) ??

在手动求解中我得到min是= 0,max = 8Pi ^ 2 = 78.957。

我尝试编写基于线性二次代码的代码,但有些事情是完全错误的 这段代码给出min = -4。??并且max = 96你能帮我知道我的错误在哪里吗?

我将代码上传到dropbox,如果有人可以查看:https://www.dropbox.com/s/p7y6krk2gk29i9e/Program.cs

    double[] X, Y, Result; // Range array and result array.

    private void BtnRun_Click(object sender, EventArgs e)
    {
        //Set any Range for the function
        X = setRange(-2 * Math.PI, 2 * Math.PI, 10000);
        Y = setRange(-2 * Math.PI, 2 * Math.PI, 10000);

        Result = getOutput_twoVariablesFunction(X, Y);

        int MaxIndex = getMaxIndex(Result);
        int MinIndex = getMinIndex(Result);

        TxtMin.Text = Result[MinIndex].ToString();
        TxtMax.Text = Result[MaxIndex].ToString();
    }

    private double twoVariablesFunction(double x,double y)
    {
        double f;
        //Set any two variables function
        f = Math.Pow(x, 2) + Math.Pow(y, 2) + 25 * (Math.Pow(Math.Sin(x), 2) + Math.Pow(Math.Sin(y), 2));
        return f;
    }

    private double[] setRange(double Start, double End, int Sample)
    {
        double Step = (End - Start) / Sample;
        double CurrentVaue = Start;
        double[] Array = new double[Sample];
        for (int Index = 0; Index < Sample; Index++)
        {
            Array[Index] = CurrentVaue;
            CurrentVaue += Step;
        }
        return Array;
    }

    private double[] getOutput_twoVariablesFunction(double[] X, double[] Y)
    {
        int Step = X.Length;
        double[] Array = new double[Step];
        for (int Index = 0; Index < X.Length ; Index++)
        {
            Array[Index] = twoVariablesFunction(X[Index], Y[Index]);
        }
        return Array;
    }

    private int getMaxIndex(double[] ValuesArray)
    {
        double M = ValuesArray.Max();
        int Index = ValuesArray.ToList().IndexOf(M);
        return Index;
    }

    private int getMinIndex(double[] ValuesArray)
    {
        double M = ValuesArray.Min();
        int Index = ValuesArray.ToList().IndexOf(M);
        return Index;
    }

1 个答案:

答案 0 :(得分:2)

你想计算(sin(x))^ 2还是sin(x ^ 2)?在你的f(x,y)公式中它看起来像(sin(x))^ 2,但在你的方法中,twoVariablesFunction就像sin(x ^ 2)。