Skip to content

Instantly share code, notes, and snippets.

@vladislav805
Forked from ddrone/Gauss.java
Last active April 8, 2017 16:34
Show Gist options
  • Save vladislav805/73dc2af8f8bb588d6c95e4853d43dc26 to your computer and use it in GitHub Desktop.
Save vladislav805/73dc2af8f8bb588d6c95e4853d43dc26 to your computer and use it in GitHub Desktop.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Scanner;
public class Gauss {
public static void swapRows(double[][] a, double[] b, int i, int j) {
double[] row = a[i];
a[i] = a[j];
a[j] = row;
double tmp = b[i];
b[i] = b[j];
b[j] = tmp;
}
// a[j] -= a[i] * multiplier;
private static void subtractRow(double[][] a, double[] b, int i, int j, double multiplier) {
for (int k = 0; k < a.length; k++) {
a[j][k] -= a[i][k] * multiplier;
}
b[j] -= b[i] * multiplier;
}
public static double[] solveLinearSystem(double[][] a, double[] b) {
// sanity check
int n = a.length;
for (double[] row : a) {
if (row.length != n)
throw new IllegalArgumentException();
}
if (b.length != n)
throw new IllegalArgumentException();
// Gaussian elimination
for (int i = 0; i < n; i++) {
int maxRow = i;
for (int j = i + 1; j < n; j++) {
if (Math.abs(a[j][i]) > Math.abs(a[maxRow][i]))
maxRow = j;
}
swapRows(a, b, i, maxRow);
for (int j = i + 1; j < n; j++) {
subtractRow(a, b, i, j, a[j][i] / a[i][i]);
}
}
for (int i = n - 1; i > 0; i--) {
for (int j = i - 1; j >= 0; j--) {
subtractRow(a, b, i, j, a[j][i] / a[i][i]);
}
}
// constructing result
double[] result = new double[n];
for (int i = 0; i < n; i++) {
result[i] = b[i] / a[i][i];
}
return result;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
double[][] a = new double[n][n];
double[] b = new double[n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = sc.nextDouble();
}
b[i] = sc.nextDouble();
}
double[] result = solveLinearSystem(a, b);
for (int i = 0; i < result.length; i++) {
if (i > 0)
out.print(' ');
out.print(result[i]);
}
out.println();
out.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment