2014-10-10 43 views
0

嗯,這給我一個真正的頭痛。我正在構建一個矩陣行列式函數來計算NxN行列式,並使用遞歸。 邏輯工作正常,但我無法獲得正確計算的最終值。NxN遞歸計算數組行列式C#

這裏是我的矩陣行列式代碼:

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; 
     } 

約fillNewArr方法,它只是一個方法修剪數組,方法如下: p

ublic 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; 

     } 

的方法工作因爲它應該是「我假設」,但最終的結果不是以正確的方式計算的,爲什麼這是?!

4×4陣列實施例:

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

最終結果應當是-168,而礦是104!

+0

什麼是最終結果他們應該是什麼? – deathismyfriend 2014-10-10 18:34:37

+0

@deathismyfriend更新了代碼,請檢查 – WT86 2014-10-10 19:43:33

回答

0

該位

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]); 

使用可變total是永遠不會再使用。它可能應該是這樣的

double subdet = determinant(fillNewArr(array, i, j)); 
if (j % 2 != 0) subdet *= -1; 
det += array[i, j] * subdet;