Linear Equations

From programming_contest
Revision as of 03:51, 16 February 2015 by imported>Kmk21 (Created page with "=gauss-jordan elimination= Credit Siyang Chen <syntaxhighlight line lang="java"> /** * solves A*X=b * @param A coefficients * @param b constants * @return values of th...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

gauss-jordan elimination

Credit Siyang Chen

/**
 * solves A*X=b
 * @param A coefficients
 * @param b constants
 * @return values of the variables
 */
public double[] linearEquationSolve( double[][] A, double[] b ){
	double EPS=.000001;//or whatever you need it to be
	int n = A.length;
	double a[][] = new double[n][n+1], temp[], scale;
	for( int i = 0; i < n; i++ ) for( int j = 0; j < n; j++ ) a[i][j] = A[i][j];
	for( int i = 0; i < n; i++ ) a[i][n] = b[i];
	for( int i = 0; i < n; i++ ){
		for( int j = i; j < n; j++ )if( Math.abs(a[j][i])>EPS ){
				temp = a[j];
				a[j] = a[i];
				a[i] = temp;
				break;
		}
		scale = 1/a[i][i];
		for( int j = i; j <= n; j++ ) a[i][j] *= scale;
		for( int j = 0; j < n; j++ )if( i != j && Math.abs(a[j][i])>EPS ){
			scale = -a[j][i];
			for( int k = i; k <= n; k++ ) a[j][k] += scale*a[i][k];
		}
	}
	double[] x = new double[n];
	for( int i = 0; i < n; i++ ) x[i] = a[i][n];
	return x;
}