Skip to content

Commit 38988bf

Browse files
Add files via upload
1 parent 5f424ce commit 38988bf

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

Maths/Gaussian.java

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/**
2+
* \file
3+
* \brief [Gaussian elimination
4+
* method](https://en.wikipedia.org/wiki/Gaussian_elimination)
5+
*/
6+
import java.util.*;
7+
8+
/** Main function */
9+
public class Gaussian {
10+
11+
public static void main(String[] args) {
12+
13+
14+
int mat_size, i, j, step;
15+
Scanner sc = new Scanner(System.in);
16+
17+
System.out.println("Matrix Size : ");
18+
mat_size = sc.nextInt();
19+
20+
double [][] mat = new double[mat_size+1][mat_size+1];
21+
double [][] x = new double[mat_size][mat_size+1];
22+
23+
System.out.println("Enter value of the matrix");
24+
System.out.println(' ');
25+
for (i = 0; i < mat_size; i++) {
26+
for (j = 0; j <= mat_size; j++) {
27+
mat[i][j] = sc.nextInt();
28+
}
29+
}
30+
31+
// perform Gaussian elimination
32+
for (step = 0; step < mat_size - 1; step++) {
33+
for (i = step; i < mat_size - 1; i++) {
34+
double a = (mat[i + 1][step] / mat[step][step]);
35+
36+
for (j = step; j <= mat_size; j++)
37+
mat[i + 1][j] = mat[i + 1][j] - (a * mat[step][j]);
38+
}
39+
}
40+
41+
System.out.println("Matrix using Gaussian Elimination method: ");
42+
System.out.println(" ");
43+
for (i = 0; i < mat_size; i++) {
44+
for (j = 0; j <= mat_size; j++) {
45+
x[i][j] = mat[i][j];
46+
System.out.print(mat[i][j] + " ");
47+
}
48+
System.out.println();
49+
}
50+
System.out.println( "Value of the Gaussian Elimination method: ");
51+
System.out.println(" ");
52+
53+
for (i = mat_size - 1; i >= 0; i--) {
54+
double sum = 0;
55+
for (j = mat_size - 1; j > i; j--) {
56+
x[i][j] = x[j][j] * x[i][j];
57+
sum = x[i][j] + sum;
58+
}
59+
if (x[i][i] == 0){
60+
x[i][i] = 0;
61+
}
62+
else{
63+
x[i][i] = (x[i][mat_size] - sum) / (x[i][i]);
64+
}
65+
System.out.print("x" + i + "=" + x[i][i]);
66+
System.out.println(" ");
67+
}
68+
69+
}
70+
}

0 commit comments

Comments
 (0)