【问题标题】:Computing Array Determinant for NxN Recursive C#计算 NxN 递归 C# 的数组行列式
【发布时间】:2014-10-10 18:30:53
【问题描述】:

嗯,这让我很头疼。我正在构建一个矩阵行列式函数来计算 NxN 行列式,并且我正在使用递归。 逻辑工作正常,但我无法正确计算出最终值。

这是我的矩阵行列式代码:

 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;

        }

该方法按“我假设”的方式工作,但最终结果的计算方式不正确,为什么会这样?!

4x4 数组示例:

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

最终结果应该是 -168,而我的是 104!

【问题讨论】:

  • 最终结果是什么,应该是什么?
  • @deathismyfriend 更新了代码,请检查

标签: c# recursion matrix multidimensional-array determinants


【解决方案1】:

这一点

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;   

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 2011-02-24
    • 1970-01-01
    • 2020-03-11
    • 2019-03-25
    • 1970-01-01
    • 2022-07-06
    相关资源
    最近更新 更多