且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

计算NxN递归C#的阵列行列式

更新时间:2022-10-15 15:50:24

这是应该修改的部分:)

  for  int  j =  0 ; j <  array.GetLength( 1 ); j ++)
{
tempArr = fillNewArr(array, 0 ,j);
det = determinant(tempArr)*(Math.Pow(-1,j)* array [ 0 ,j]);
总计+ = det; ;
}


Well, this is giving me a real headache. I'm building a matrix determinant function to compute NxN determinant, and I'm using recursion. The logic is working right but I'm not able to get the final value computed correctly.

Here is my code for Matrix Determinant:

public static double determinant(double[,]array){
           double det=0;
           double total = 0;
           double[,] tempArr = new double[array.GetLength(0) - 1, array.GetLength(1) - 1];

           if(array.GetLength(0)==2)
           {
               det = array[0, 0] * array[1, 1] - array[0, 1] * array[1, 0];
           }

           else {

               for (int i = 0; i <1; i++)
               {
                   for (int j = 0; j < array.GetLength(1); j++)
                   {
                       if (j % 2 != 0) array[i, j] = array[i, j] * -1;
                      tempArr= fillNewArr(array, i, j);
                      det+=determinant(tempArr);
                      total =total + (det * array[i, j]);
                   }
               }
                }
           return det;
       }


and about fillNewArr method it's just a method to trim the array, method is as follow:

public static double[,] fillNewArr(double[,] originalArr, int row, int col)
        {
            double[,] tempArray = new double[originalArr.GetLength(0) - 1, originalArr.GetLength(1) - 1];

            for (int i = 0, newRow = 0; i < originalArr.GetLength(0); i++)
            {
                if (i == row)
                    continue;
                for (int j = 0, newCol=0; j < originalArr.GetLength(1); j++)
                {
                    if ( j == col) continue;
                    tempArray[newRow, newCol] = originalArr[i, j];

                    newCol++;
                }
                newRow++;
            }
            return tempArray;

        }


The method is working as it supposed to "I assume" but the final result is not computed in the right way, why would that be?!

4x4 Array Example:

{2 6 6 2}
{2 7 3 6}
{1 5 0 1}
{3 7 0 7}


Final result should be -168, while mine is 104!

This is the part where should be modified :)
for (int j = 0; j < array.GetLength(1); j++)
               {
               tempArr= fillNewArr(array, 0, j);
               det=determinant(tempArr) *( Math.Pow(-1,j)* array[0,j]);
               total += det; ;
               }