Skip to content

Instantly share code, notes, and snippets.

@ddrone
Created March 28, 2013 20:45
Show Gist options
  • Save ddrone/5266645 to your computer and use it in GitHub Desktop.
Save ddrone/5266645 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 (a.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