当前位置: 移动技术网 > IT编程>开发语言>c# > C#使用加边法计算行列式的值

C#使用加边法计算行列式的值

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文实例讲述了c#使用加边法计算行列式的值。分享给大家供大家参考。具体如下:

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.运行结果

希望本文所述对大家的c#程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网