📄 linearequation.java
字号:
/*
*@(#)LinearEquation.java 2.0 2005/04/30
*
*清华大学 精密仪器与机械学系
*范灿升 fancansheng@163.com
*/
package algorithm;
import lib.Library;
/**
*这个类是线性方程组类,用于对方程组进行一定的变形和处理,包含求解方程组的方法。
*<p>所求解的方程组必须是方程数目和未知数数目相等的方程组,且系数矩阵不为零。
*<p>求解算法为高斯消元法。
*@version 2.0, 2005/04/30
*@author 范灿升
*@see Modeling
*@see input.EquationInput
*/
public class LinearEquation
{
private double[][] coefficients;
private double[] constants;
private int count=0;
//标记所做交换的次数,以便处理行列式的正负号
//由下面算法可知,count在对解方程没什么用,因为这个类解方程用的是高斯消元法,当计算行列式时才有用。
private double[] solution;
/**
*标记行列式的值是否为0。
*<p>当zeroDeterminant为true时,由{@link #diagonalize}方法返回的矩阵不一定是对角阵。
*/
public boolean zeroDeterminant=false;
/**
*方程组中未知数的个数,也就是方程组中方程的数目。
*/
public int n;
/**
*将相应的构造函数参数复制到类中相应的成员域。
*@param coefficient 系数矩阵
*@param constant 常数项向量
*/
public LinearEquation(double[][] coefficient,double[] constant)
{
coefficients=(double[][])coefficient.clone();
constants=(double[])constant.clone();
n=constants.length;
}
/**
*将系数矩阵对角化。
*<p>对角化后的系数矩阵成为上三角阵。
*<p>程序同时会对常数项向量进行相应处理。
*@return 已经化为上三角阵的系数矩阵
*/
public double[][] diagonalize()
{
int i;
int column;
int nextRow;
double coef;//化0所需要用到的系数
int swap;//标记矩阵行的交换情况
for(i=0;i<n;i++)////
{
swap=swapRows(i);
if(swap==1)
count++;
else if(swap==0)
{
zeroDeterminant=true;
return coefficients;
}
for(nextRow=i+1;nextRow<n;nextRow++)
{
coef=coefficients[nextRow][i]/coefficients[i][i];
for(column=i;column<n;column++)
coefficients[nextRow][column]-=coef*coefficients[i][column];
constants[nextRow]-=coef*constants[i];
}
}
return coefficients;
}
/**
*交换系数矩阵中的某两行,使得可以把一般的矩阵转换成上三角矩阵。
*<p>常数项向量同时会做相应的交换。
*@param currentRow 当前所在行
*@return -1表示不用交换,0表示没有交换,可直接得行列式的值为0,1表示做了交换
*/
public int swapRows(int currentRow)
{
int nextRow;
int j;
double temp;
if(Math.abs(coefficients[currentRow][currentRow])<=Library.NUMBER_LIMIT)
//判断coefficients[currentRow][currentRow]是否为零
//为零则执行下面的语句
{
for(nextRow=currentRow+1;nextRow<n;nextRow++)
{
if(Math.abs(coefficients[nextRow][currentRow])>Library.NUMBER_LIMIT)
{
for(j=0;j<n;j++)
{
temp=coefficients[currentRow][j];
coefficients[currentRow][j]=coefficients[nextRow][j];
coefficients[nextRow][j]=temp;
}
temp=constants[currentRow];
constants[currentRow]=constants[nextRow];
constants[nextRow]=temp;
return 1;
}
}
return 0;
}
return -1;
}
/**
*解方程组。
*@return 方程组的解向量,当zeroDeterminant为true时返回null。
*/
public double[] solve()
{
int i,j;
diagonalize();
if(zeroDeterminant==true)
return null;
solution=(double[])constants.clone();
for(i=n-1;i>=0;i--)
{
for(j=n-1;j>i;j--)
solution[i]-=(coefficients[i][j]*solution[j]);
solution[i]/=coefficients[i][i];
}
return solution;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -