/// <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;
}
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();
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有