import java.util.Scanner; public class Gauss1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); double[][] A; double[] b; double pivot, factor; int n; // Number of variables int i, j, k; System.out.print("Number of unknows: "); n = in.nextInt(); // Read in problem size A = new double[n][n]; // Reserve space for coefficient matrix b = new double[n]; // Reserve space for RHS vector // Read in the rows, one row at a time for (i = 0; i < n; i++) { // Read in row i's coefficients for (j = 0; j < n; j++) { System.out.print("A["+i+"]["+j+"] = "); A[i][j] = in.nextDouble(); } // Read in row i's RHS System.out.print("b["+i+"] = "); b[i] = in.nextDouble(); } Print(A, b); /* ----------------------------- Gaussian elimination method ----------------------------- */ for (i = 0; i < n; i++) { // Process row i /* --------------------- (A) Select pivot --------------------- */ pivot = A[i][i]; /* --------------------- (B) Normalize row i --------------------- */ for (j = 0; j < n; j++) A[i][j] = A[i][j]/pivot; b[i] = b[i]/pivot; // ******* Show result System.out.println("After normalizing row " + (i+1) + ":"); Print(A, b); /* --------------------- (C) Sweep using row i --------------------- */ for (k = 0; k < n; k++) { if ( k != i ) { factor = A[k][i]; for (j = 0; j < n; j++) A[k][j] = A[k][j] - factor*A[i][j]; b[k] = b[k] - factor*b[i]; } } // ******* Show result System.out.println("After sweeping other rows using row " + (i+1) + ":"); Print(A, b); } System.out.println("======================"); System.out.println("Solution:"); for (i = 0; i < n; i++) System.out.println("x" + (i+1) + " = " + b[i]); } public static void Print(double[][] A, double b[]) { int i, j; // Print the equations for (i = 0; i < b.length; i++) { // Print row i for (j = 0; j < b.length; j++) { if ( j != 0 ) System.out.print(" + "); System.out.print(A[i][j] + " x" + (j+1)); } System.out.println(" = " + b[i]); } System.out.println(); } }