-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathGaussianElimination.java
More file actions
45 lines (42 loc) · 1014 Bytes
/
GaussianElimination.java
File metadata and controls
45 lines (42 loc) · 1014 Bytes
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
class GaussianElimination {
static int n;
static double[][] mat;
static double[] ans;
public static void main(String[] args) {
mat = new double[n][n + 1];
ans = new double[n];
//set up equations in form coeff(x1) + coeff(x2) + coeff(x3) + ... = constant
}
static void solve(){
for(int j = 0; j < n - 1; ++j){
for(int i = n - 1; i > j; --i){
if(equals(mat[i - 1][j], 0)){
swap(i, i - 1);
continue;
}
double ratio = -(mat[i][j] / mat[i - 1][j]);
for(int k = 0; k < n + 1; ++k){
mat[i][k] += mat[i - 1][k] * ratio;
}
}
}
for(int i = n - 1; i >= 0; --i){
double add = 0;
for(int j = i + 1; j < n; ++j){
add += ans[j] * mat[i][j];
}
double curr = (mat[i][n] - add) / mat[i][i];
ans[i] = curr;
}
}
static void swap(int r1, int r2){
for(int j = 0; j < n + 1; ++j){
double temp = mat[r1][j];
mat[r1][j] = mat[r2][j];
mat[r2][j] = temp;
}
}
static boolean equals(double a, double b){
return Math.abs(a - b) <= 1e-6;
}
}