1.函数
行列式的值等于其第一行各元素乘以各自对应的代数余子式之积的和。
(注:本代码仅提供一种思路,并不代表最优解)
/// <summary>
/// 递归计算行列式的值
/// </summary>
/// <param name="matrix">矩阵</param>
/// <returns></returns>
public static double Determinant(double[][] matrix)
{
//二阶及以下行列式直接计算
if (matrix.Length == 0) return 0;
else if (matrix.Length == 1) return matrix[0][0];
else if (matrix.Length == 2)
{
return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
}
//对第一行使用“加边法”递归计算行列式的值
double dSum = 0, dSign = 1;
for (int i = 0; i < matrix.Length; i++)
{
double[][] matrixTemp = new double[matrix.Length - 1][];
for (int count = 0; count < matrix.Length - 1; count++)
{
matrixTemp[count] = new double[matrix.Length - 1];
}
for (int j = 0; j < matrixTemp.Length; j++)
{
for (int k = 0; k < matrixTemp.Length; k++)
{
matrixTemp[j][k] = matrix[j + 1][k >= i ? k + 1 : k];
}
}
dSum += (matrix[0][i] * dSign * Determinant(matrixTemp));
dSign = dSign * -1;
}
return dSum;
}
2.Main函数调用
static void Main(string[] args)
{
//二阶行列式 -2
double[][] matrix1 = new double[][]
{
new double[] { 1, 2 },
new double[] { 3, 4 }
};
Console.WriteLine(Determinant(matrix1));
//三阶行列式 -4
double[][] matrix2 = new double[][]
{
new double[] { 2, 0, 1 },
new double[] { 1, -4, -1 },
new double[] { -1, 8, 3 }
};
Console.WriteLine(Determinant(matrix2));
//四阶行列式 -21
double[][] matrix3 = new double[][]
{
new double[] { 1, 2, 0, 1 },
new double[] { 1, 3, 5, 0 },
new double[] { 0, 1, 5, 6 },
new double[] { 1, 2, 3, 4 }
};
Console.WriteLine(Determinant(matrix3));
Console.ReadLine();
}
3.运行结果