化学方程式配平程序

其实这是一个Java小作业。

其实这应该有无数bug。

参考了foreverbell神牛告诉我的高斯消元法, 参见这里

SolveChemistry

先解压, 然后Windows双击.bat, Linux双击.sh

JRE1.6 Required.

如下是这个算法的实现。

Fraction没有给出, 这个方法的第二个参数用二维的原因是, 一维的话, 如果修改了它的值, 值不会在这个方法外面有效。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package net.twd2.chemical.algorithm;
 
import net.twd2.chemical.data.Fraction;
 
public class GaussJordanElimination {
    /*
     *     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 条评论。

发表评论

注意 - 你可以用以下 HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

:wink: :twisted: :roll: :oops: :mrgreen: :lol: :idea: :evil: :cry: :arrow: :?: :-| :-x :-o :-P :-D :-? :) :( :!: 8-O 8)

Trackbacks and Pingbacks:

本文链接:https://twd2.me/archives/3015QrCode