forked from Arunvijay28/Java-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gausselimination.java
68 lines (58 loc) · 2.13 KB
/
gausselimination.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
public class gausselimination {
private static final double EPSILON = 1e-10;
// The following is a program for Gaussian elimination using the partial pivoting method
public static double[] solution(double[][] A, double[] b) {
// Inputting the coefficient matrix and the column vector of solutions
int n = b.length;
for (int p = 0; p < n - 1; p++) {
// Finding the pivot row and swapping
int max = p;
for (int i = p + 1; i < n; i++) {
if (Math.abs(A[i][p]) > Math.abs(A[max][p])) {
max = i;
}
}
// Swap rows in matrix A
double[] temp = A[p];
A[p] = A[max];
A[max] = temp;
// Swap corresponding values in vector b
double t = b[p];
b[p] = b[max];
b[max] = t;
// If the matrix is singular or near-singular
if (Math.abs(A[p][p]) <= EPSILON) {
throw new ArithmeticException("Matrix is partially or completely singular");
}
// Perform row elimination
for (int i = p + 1; i < n; i++) {
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];
}
}
}
// Code for back substitution
double[] x = new double[n];
for (int i = n - 1; i >= 0; i--) {
double sum = 0.0;
for (int j = i + 1; j < n; j++) {
sum += A[i][j] * x[j];
}
x[i] = (b[i] - sum) / A[i][i];
}
return x;
}
// Sample input for the method
public static void main(String[] args) {
int n = 3; // Corrected matrix size
double[][] A = { {0, 1, 1}, {2, 4, -2}, {0,3,15 }};
double[] b = {4,2,36};
// Printing results
double[] x = solution(A, b);
for (int i = 0; i < n; i++) {
System.out.println(x[i]);
}
}
}