-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgaussElim.js
106 lines (93 loc) · 2.33 KB
/
gaussElim.js
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// This code was obtained from the website https://gist.github.com/codecontemplator/6b3db07a29e435940ffc
// Credits to codecontemplator
function print(M, msg) {
console.log("======" + msg + "=========")
for(var k=0; k<M.length; ++k) {
console.log(M[k]);
}
console.log("==========================")
}
function diagonalize(M) {
var m = M.length;
var n = M[0].length;
var i_max;
for(var k=0; k<Math.min(m,n); ++k) {
i_max = findPivot(M, k);
if (A[i_max, k] == 0)
throw "matrix is singular";
swap_rows(M, k, i_max);
for(var i=k+1; i<m; ++i) {
var c = A[i][k] / A[k][k];
for(var j=k+1; j<n; ++j) {
A[i][j] = A[i][j] - A[k][j] * c;
}
A[i][k] = 0;
}
}
}
function findPivot(M, k) {
var i_max = k;
for(var i=k+1; i<M.length; ++i) {
if (Math.abs(M[i][k]) > Math.abs(M[i_max][k])) {
i_max = i;
}
}
return i_max;
}
function swap_rows(M, i_max, k) {
if (i_max != k) {
var temp = A[i_max];
A[i_max] = A[k];
A[k] = temp;
}
}
function makeM(A, b) {
for(var i=0; i<A.length; ++i) {
A[i].push(b[i]);
}
}
function substitute(M) {
var m = M.length;
for(var i=m-1; i>=0; --i) {
var x = M[i][m] / M[i][i];
for(var j=i-1; j>=0; --j) {
M[j][m] -= x * M[j][i];
M[j][i] = 0;
}
M[i][m] = x;
M[i][i] = 1;
}
}
function extractX(M) {
var x = [];
var m = A.length;
var n = A[0].length;
for(var i=0; i<m; ++i){
x.push(A[i][n-1]);
}
return x;
}
function solve(A, b) {
makeM(A,b);
diagonalize(A);
substitute(A);
var x = extractX(A);
return x;
}
A = [
[1,0,0,1/Math.sqrt(2),1,0,0,0,0,0],
[0,1,0,1/Math.sqrt(2),0,0,0,0,0,0],
[0,0,0,-1/Math.sqrt(2),0,1/Math.sqrt(2),1,0,0,0],
[0,0,0,-1/Math.sqrt(2),0,-1/Math.sqrt(2),0,0,0,0],
[0,0,0,0,-1,-1/Math.sqrt(2),0,1/Math.sqrt(2),1,0],
[0,0,0,0,0,1/Math.sqrt(2),0,1/Math.sqrt(2),0,0],
[0,0,0,0,0,0,-1,-1/Math.sqrt(2),0,1/Math.sqrt(2)],
[0,0,0,0,0,0,0,-1/Math.sqrt(2),0,-1/Math.sqrt(2)],
[0,0,0,0,0,0,0,0,-1,-1/Math.sqrt(2)],
[0,0,1,0,0,0,0,0,0,1/Math.sqrt(2)]
];
b = [0,0,0,0,0,20,0,0,0,0];
print(A, " A ");
print(b, " b ");
var x = solve(A, b);
console.log(x);