C#使用加邊法計算行列式的值
更新時間:2015年08月13日 09:24:43 作者:北風(fēng)其涼
這篇文章主要介紹了C#使用加邊法計算行列式的值,實例分析了C#加邊法計算行列式的原理與實現(xiàn)技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了C#使用加邊法計算行列式的值。分享給大家供大家參考。具體如下:
1.函數(shù)
行列式的值等于其第一行各元素乘以各自對應(yīng)的代數(shù)余子式之積的和。
(注:本代碼僅提供一種思路,并不代表最優(yōu)解)
/// <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函數(shù)調(diào)用
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.運行結(jié)果
希望本文所述對大家的C#程序設(shè)計有所幫助。
您可能感興趣的文章:
相關(guān)文章
C#連接SQL?Sever數(shù)據(jù)庫與數(shù)據(jù)查詢實例之?dāng)?shù)據(jù)倉庫詳解
最近的工作遇到了連接查詢,特在此記錄,以免日后以往,下面這篇文章主要給大家介紹了關(guān)于C#連接SQL?Sever數(shù)據(jù)庫與數(shù)據(jù)查詢實例之?dāng)?shù)據(jù)倉庫的相關(guān)資料,文中通過圖文介紹的非常詳細,需要的朋友可以參考下2022-06-06C#分析URL參數(shù)并獲取參數(shù)和值對應(yīng)列表的方法
這篇文章主要介紹了C#分析URL參數(shù)獲取參數(shù)和值對應(yīng)列表的方法,涉及C#進行URL分析及正則表達式的使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-03-03