其实这是一个Java小作业。
其实这应该有无数bug。
参考了foreverbell神牛告诉我的高斯消元法, 参见这里。
先解压, 然后Windows双击.bat, Linux双击.sh
JRE1.6 Required.
如下是这个算法的实现。
Fraction没有给出, 这个方法的第二个参数用二维的原因是, 一维的话, 如果修改了它的值, 值不会在这个方法外面有效。
package net.twd2.chemical.algorithm;
import net.twd2.chemical.data.Fraction;
public class GaussJordanElimination {
/*
* Reference: http://foreverbell.0ginr.com/svn/HelloChemistry/HelloChemistry/algorithm/
* Reference: http://www.artofproblemsolving.com/blog/13009
* Original author: zkw
*/
public static boolean gjElimination(Fraction[][] matrix, Fraction[][] solve) throws Exception {
int n=matrix.length,
m=matrix[0].length;
int maxIndex;
Fraction maxValue, temp;
int[] solvePoint = new int[m];
solve[0] = new Fraction[m-1];
for(int i=0;i<n;++i) {
maxIndex=0;
maxValue=matrix[i][maxIndex].abs();
for(int j=0;j<m-1;++j) {
temp=matrix[i][j].abs();
if(temp.comp(maxValue)>0) {
maxValue=temp;
maxIndex=j;
}
}
if(maxValue.equals(Fraction.ZERO)) {
if(matrix[i][m-1].equals(Fraction.ZERO)) {
continue;
}
else {
return false;
}
}
solvePoint[maxIndex]=i+1;
temp=matrix[i][maxIndex];
for(int j=0;j<m;++j) {
matrix[i][j]=matrix[i][j].divide(temp);
}
for(int j=0;j<n;++j) {
if(i!=j) {
temp=matrix[j][maxIndex];
for(int k=0;k<m;++k) {
matrix[j][k]=matrix[j][k].subtract(matrix[i][k].multiply(temp));
}
}
}
}
for(int i=0;i<m-1;++i) {
if(solvePoint[i]==0) {
return false;
}
solve[0][i]=matrix[solvePoint[i]-1][m-1];
}
return true;
}
}

1 条评论。