我正在尝试实现此处找到的代码和算法:
矩阵的行列式 和这里: 如何计算矩阵行列式?n*n 或 5*5
但我坚持下去。
我的第一个问题是这个算法实际上使用了什么规则(因为在数学中显然有几个规则可以用来计算行列式) - 所以我想首先检查算法是否正确应用。
我的第二个问题是我做错了什么(我的意思是实现)或算法本身有什么问题,因为它看起来对于 3x3 和 4x4 它工作正常,但对于 5x5 它给出了 NaN。使用几个在线矩阵行列式计算器检查结果,除了 5x5 之外,它们都很好。
这是我的代码:
using System;
public class Matrix
{
private int row_matrix; //number of rows for matrix
private int column_matrix; //number of colums for matrix
private double[,] matrix; //holds values of matrix itself
//create r*c matrix and fill it with data passed to this constructor
public Matrix(double[,] double_array)
{
matrix = double_array;
row_matrix = matrix.GetLength(0);
column_matrix = matrix.GetLength(1);
Console.WriteLine("Contructor which sets matrix size {0}*{1} and fill it with initial data executed.", row_matrix, column_matrix);
}
//returns total number of rows
public int countRows()
{
return row_matrix;
}
//returns total number of columns
public int countColumns()
{
return column_matrix;
}
//returns value of an element for a given row and column of matrix
public double readElement(int row, int column)
{
return matrix[row, column];
}
//sets value of an element for a given row and column of matrix
public void setElement(double value, int row, int column)
{
matrix[row, column] = value;
}
public double deterMatrix()
{
double det = 0;
double value = 0;
int i, j, k;
i = row_matrix;
j = column_matrix;
int n = i;
if (i != j)
{
Console.WriteLine("determinant can be calculated only for sqaure matrix!");
return det;
}
for (i = 0; i < n - 1; i++)
{
for (j = i + 1; j < n; j++)
{
det = (this.readElement(j, i) / this.readElement(i, i));
//Console.WriteLine("readElement(j, i): " + this.readElement(j, i));
//Console.WriteLine("readElement(i, i): " + this.readElement(i, i));
//Console.WriteLine("det is" + det);
for (k = i; k < n; k++)
{
value = this.readElement(j, k) - det * this.readElement(i, k);
//Console.WriteLine("Set value is:" + value);
this.setElement(value, j, k);
}
}
}
det = 1;
for (i = 0; i < n; i++)
det = det * this.readElement(i, i);
return det;
}
}
internal class Program
{
private static void Main(string[] args)
{
Matrix mat03 = new Matrix(new[,]
{
{1.0, 2.0, -1.0},
{-2.0, -5.0, -1.0},
{1.0, -1.0, -2.0},
});
Matrix mat04 = new Matrix(new[,]
{
{1.0, 2.0, 1.0, 3.0},
{-2.0, -5.0, -2.0, 1.0},
{1.0, -1.0, -3.0, 2.0},
{4.0, -1.0, -3.0, 1.0},
});
Matrix mat05 = new Matrix(new[,]
{
{1.0, 2.0, 1.0, 2.0, 3.0},
{2.0, 1.0, 2.0, 2.0, 1.0},
{3.0, 1.0, 3.0, 1.0, 2.0},
{1.0, 2.0, 4.0, 3.0, 2.0},
{2.0, 2.0, 1.0, 2.0, 1.0},
});
double determinant = mat03.deterMatrix();
Console.WriteLine("determinant is: {0}", determinant);
determinant = mat04.deterMatrix();
Console.WriteLine("determinant is: {0}", determinant);
determinant = mat05.deterMatrix();
Console.WriteLine("determinant is: {0}", determinant);
}
}