Skip to content

Instantly share code, notes, and snippets.

@Firsto
Created September 13, 2015 16:43
Show Gist options
  • Save Firsto/20d8510609e372730aef to your computer and use it in GitHub Desktop.
Save Firsto/20d8510609e372730aef to your computer and use it in GitHub Desktop.
gauss elimination
import java.util.Scanner;
public class Main{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
String mn = sc.nextLine();
int n = Integer.parseInt(mn.split(" ")[0]);
int m = Integer.parseInt(mn.split(" ")[1]);
double[][] A = new double[n][m];
double[] b = new double[n];
String[] xi;
for (int i = 0; i < n; i++) {
xi = sc.nextLine().split(" ");
for (int j = 0; j < m; j++) {
A[i][j] = Integer.parseInt(xi[j]);
}
b[i] = Integer.parseInt(xi[m]);
}
double[] solve = lsolve(A, b);
if (solve.length < m) {
System.out.println("INF");
} else {
System.out.println("YES");
for (int i = 0; i < solve.length; i++) {
System.out.print(solve[i]);
if (i-1 != solve.length) System.out.print(" ");
}
}
}
private static final double EPSILON = 1e-6;
// Gaussian elimination with partial pivoting
public static double[] lsolve(double[][] A, double[] b) {
int N = b.length;
for (int p = 0; p < N; p++) {
// find pivot row and swap
int max = p;
for (int i = p + 1; i < N; i++) {
try{
if (Math.abs(A[i][p]) > Math.abs(A[max][p])) {
max = i;
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.print("NO");
System.exit(0);
}
}
double[] temp = A[p]; A[p] = A[max]; A[max] = temp;
double t = b[p]; b[p] = b[max]; b[max] = t;
// singular or nearly singular
try{
if (Math.abs(A[p][p]) <= EPSILON) {
System.out.print("NO");
System.exit(0);
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.print("NO");
System.exit(0);
}
// pivot within A and b
for (int i = p + 1; i < N; i++) {
try{
double alpha = A[i][p] / A[p][p];
b[i] -= alpha * b[p];
for (int j = p; j < N; j++) {
A[i][j] -= alpha * A[p][j];
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.print("NO");
System.exit(0);
}
}
}
// back substitution
double[] x = new double[N];
for (int i = N - 1; i >= 0; i--) {
double sum = 0.0;
try{
for (int j = i + 1; j < N; j++) {
sum += A[i][j] * x[j];
}
x[i] = (b[i] - sum) / A[i][i];
} catch (ArrayIndexOutOfBoundsException e) {
System.out.print("NO");
System.exit(0);
}
}
return x;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment