发生了System.IndexOutOfRangeException

时间:2016-11-19 19:16:01

标签: c# numerical-methods

我的系统索引超出范围异常错误,我无法找到我在哪里有错误。可能是索引失败了。你能帮我么?谢谢你的好意。我先得到错误:

 x1 = x1 - (hess_universe[1, 1] * grad[1] + hess_universe[1, 2] * grad[2] + hess_universe[1, 3] * grad[3])

这里是我的代码:

        double x1 = 1, x2 = 1, x3 = 1;
        double eps = Math.Pow(10, -5);
        double[] grad = new double[3];
        double [,] hess_universe=new double [3,3]{ { -1.25,-0.5,0.75},{ -0.5,-0.34,-0.5},{ -0.75,-0.5,-1.25} };
        while(Math.Abs(funcderiv1(x1,x2,x3))>eps || Math.Abs(funcderiv2(x1, x2,x3))> eps)
        {
            grad[0] = funcderiv1(x1, x2, x3);
            grad[1] = funcderiv2(x1, x2, x3);
            grad[2] = funcderiv3(x1, x2, x3);

           x1 = x1 - (hess_universe[1, 1] * grad[1] + hess_universe[1, 2] * grad[2] + hess_universe[1, 3] * grad[3]);//i get error in here
            x2 = x2 - (hess_universe[2, 1] * grad[1] + hess_universe[2, 2] * grad[2] + hess_universe[2, 3] * grad[3]);
            x3 = x3 - (hess_universe[3, 1] * grad[1] + hess_universe[3, 2] * grad[2] + hess_universe[3, 3] * grad[3]);

        }
        Console.WriteLine("Optimal solution found at: (" + x1 + ',' + x2 + ',' + x3 + ")");
        Console.ReadLine();
    }
    static double funcderiv1(double x1,double x2, double x3)
    {
        return 3 * x2 - 2 * x1;
    }
    static double funcderiv2(double x1, double x2, double x3)
    {
        return 3*x1+3*x3-12*x2;
    }
    static double funcderiv3(double x1, double x2,double x3)
    {
        return 3 * x2 - 2 * x3;
    }

1 个答案:

答案 0 :(得分:0)

这可能是因为您在尺寸为3x3的二维数组上使用索引3。您需要使用索引0到2,例如

x1 = x1 - (hess_universe[0, 0] * grad[0] + hess_universe[0, 1] * grad[1] + hess_universe[0, 2] * grad[2])

同样适用于一维数组。