分数类的应用:C# 中的矩阵类






4.33/5 (13投票s)
一篇关于开发由分数组成的矩阵类的文章。
引言
本文演示了如何使用分数类来创建矩阵类。我们高中都学习过数学,也学习过矩阵。因此,计算机中需要矩阵程序。但问题是,所有矩阵程序/类(据我所知)都以浮点型变量数组的形式表示矩阵。在学校里,我们学习的是整数和分数形式的矩阵,因此需要一个高效的矩阵程序/类,以分数的形式呈现矩阵。我编写了我的分数类,因为我需要一个由分数组成的矩阵类。
背景
我假设读者具备高中数学的基础知识。
实现
矩阵是由分数组成的二维数组。该类使用简单的中学数学公式进行内部运算,一些函数包括
MultiplyRow()
用于将整行乘以整数/分数/双精度数。AddRow()
用于将一行乘以倍数加到另一行。InterchangeRow()
用于交换两行。Concatenate()
用于按列连接两个矩阵(当我们想要创建增广矩阵来求解方程时,此函数很有用)。Adjoint()
用于求矩阵的伴随矩阵。Transpose()
用于返回矩阵的转置。Determinent()
有两个函数,一个使用普通余子式法求行列式,另一个是一个非常快速的算法,利用简化行阶梯形来求行列式。Inverse()
有两个函数,一个使用普通伴随矩阵法求逆矩阵,另一个使用简化行阶梯形法求逆矩阵。显然,第二个函数比第一个函数效率高得多,第一个函数主要由于递归而变慢。EchelonForm()
可用于通过高斯消元法求解方程。ReducedEchelonForm()
可用于通过高斯-约旦法求解方程。
使用代码
该类非常易于使用,它包含各种情况下的各种构造函数。
int[,] intarr={{1,2,3},{1,4,9},{4,5,6}}; // initializes a 2D integer array
Matrix matrix=new Matrix( intarr ); // initializes the matrix with the 2D array,
// note that the array has been converted to fractions
Console.WriteLine(matrix); //display the matrix
下面的代码块演示了一些函数,看看它们有多么易于使用
Console.WriteLine( matrix.Transpose() );
// displays transpose
Console.WriteLine( matrix.Inverse() ); // displays inverse of the matrix
Console.WriteLine( matrix.Inverse()*matrix );
// obviously this will display an identity matrix
// (recall your school mathematics)
Console.WriteLine( matrix.EchelonForm() ); // displays Echelon form
Console.WriteLine( matrix+matrix.Transpose() );
// forgotten high school maths? this will display a
// symmetric matrix (still forgotten what is symmetric matrix,
// buy some book of mathematics :) )
应用:使用此类求解方程
考虑以下方程组
X + 2Y - 3Z = 10
4X - 2Y - Z = 6
X - Y - 2Z = -3
使用高斯-约旦法,让我们使用矩阵类来求解它。
int[,] arrA={{1,2,-3},{4,-2,-1},{1,-1,-2}}; //array of coefficients int[,] arrB={ {2},{5},{-3}}; // array of constants Matrix matrixA=new Matrix( arrA ); // convert array to matrix Matrix matrixB=new Matrix( arrB ); // convert array to matrix // get augmented matrix by concatenation Matrix augmentedMatrix=Matrix.Concatenate( matrixA, matrixB ); Console.WriteLine("Augmented matrix for the given system of equation is" + augmentedMatrix); // evaluate reduced echelon form Matrix reducedEchForm=augmentedMatrix.ReducedEchelonForm(); Console.WriteLine("Reduced Echelon form for the given augmented matrix is" + reducedEchForm); // the last column of augmented matrix gives the answer values Console.WriteLine("Value for X is " + reducedEchForm[0,3] ); Console.WriteLine("Value for Y is " + reducedEchForm[1,3] ); Console.WriteLine("Value for Z is " + reducedEchForm[2,3] );
上述代码得出X=65/23,Y=52/23,Z=41/23。
其他应用程序
是的,这里没有矩阵。类似地,该类可用于线性规划问题。(我希望您也熟悉经济学。顺便说一句,我实现这个类是因为我想验证我在线性规划问题中的结果。)该类还可用于各种变换(解析几何的一个主题)、特征值/特征空间问题以及其他与向量空间相关的其他问题等。
历史
1.1 版的新增功能
- 添加了
DeterminentFast()
方法 - 添加了
InverseFast()
方法 - 将
ConvertToString
重命名为(重写)ToString()
- 修复了一些小错误