Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Gauss Jordan Emlination Algorithm

$
0
0
Have to create this for class and having a hard time doing so. Been debugging it for a few hours and cant figure it out. 95% sure its something in the subtraction part of the method. It comes up with the identity matrix but not the correct solution. You guys see anything?

public class Matrice {
	// test methods
	public static void main(String args[]) {
		double[][] test1 = new double[][] { 
				{ 1,-1, 0, 2},
				{ -2, 2,-1, -1},
				{0, 1, -2, 6}
				};
		double[][] equals = new double[3][4];


		try {
			 equals = GaussJordan(test1);
		} catch (Exception e) {
			System.out.println(e);
		}

		for (int i = 0; i < equals.length; i++) {
			for (int j = 0; j < equals[1].length; j++) {
				System.out.print("[ " + equals[i][j] + " ]");
			}
			System.out.println();
		}
	}

	static double[][] GaussJordan(double[][] array) throws Exception {
		double[][] a = array;
		int e = 1;
		int n = a.length;
		for (int j = 0; j < n; j++) {
			int p = j;
		    double max = Math.abs(a[p][0]);
			// find pivot index p
			for (int i = j + 1; i < n; i++) {
				if (Math.abs(a[i][0]) > max) {
					p = i;
					
				}
				
			}
			System.out.println(p);

////			 check for no unique solution
//			if (a[p][j] == 0.0) {
//				e = 0;
//				throw new Exception("No unique solution");
//			}

			// interchange rows
			if (p > j) {
				double temp = 0;
				for (int i = 0; i < a[1].length; i++) {
					// put row j value in temp
					temp = a[j][i];
					// move p into j
					a[j][i] = a[p][i];
					// put temp back into p
					a[p][i] = temp;
				}
			}

			// Divide row j by A[j][j]
			double divisor = a[j][j];
		for ( int i = 0; i < a[j].length; i ++){
			
			a[j][i] = a[j][i]/divisor;
		}

//			 Subtract
			for (int i = 0; i < a.length; i++) {
				if (i != j) {
					double multiple = a[i][j];
					for (int x = 0; x < a[1].length; x++) {
						a[i][x] = (a[i][x] - a[i][j] * a[j][x]);

					}
				}
			}

		}
		return a;
	}

}








Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>