/
Matrix.java
65 lines (55 loc) · 1.57 KB
/
Matrix.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
import java.util.*;
class Matrix
{
public static double determinant(double[][] m)
{
double res = 1.0;
/* Row reduce. */
for (int i = 0; i < m.length; i++)
{
/* Find a row with a nonzero entry and swap. */
for (int j = i; j < m.length; j++)
{
if (Math.abs(m[j][i]) > 1e-9)
{
if (i != j)
{
swapRows(m,i,j);
res = -res;
}
break;
}
}
for (int j = i+1; j < m.length; j++)
addRow(m, i, j, -m[j][i] / m[i][i]);
}
/* Multiply the terms along the diagonal. */
for(int i = 0; i < m.length; i++)
res *= m[i][i];
return res;
}
/* Set r2 = r2 + scale*r1. */
public static void addRow(double[][] m, int r1, int r2, double scale)
{
for (int i = 0; i < m[0].length; i++)
m[r2][i] += scale*m[r1][i];
}
/* Swap rows r1 and r2 */
public static void swapRows(double[][] m, int r1, int r2)
{
for (int i = 0; i < m[0].length; i++)
{
double temp = m[r1][i];
m[r1][i] = m[r2][i];
m[r2][i] = temp;
}
}
/* Unit tests */
public static void main(String[] args)
{
double[][] matrix1 = {{5.0,3.0},
{2.0,1.0}};
assert Math.abs(determinant(matrix1) + 1) < 1e-9;
System.out.println("Tests passed!");
}
}