-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGaussSolver.js
More file actions
64 lines (63 loc) · 1.9 KB
/
GaussSolver.js
File metadata and controls
64 lines (63 loc) · 1.9 KB
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
//GitHub: HenriqueIni
//www.blogcyberini.com
/*
Algoritmo para resolução de sistemas lineares via eliminação de Gauss
Complexidade no tempo: O(n^3)
A é a matriz dos coeficientes do sistema
b é a matriz dos coeficientes dos termos independentes
Forma do sistema (matricial): Ax = b
*/
function gaussSolver(A, b){
var i, j, k, l, m;
//ETAPA DE ESCALONAMENTO
for(k = 0; k < A.length - 1; k++){
//procura o maior k-ésimo coeficiente em módulo
var max = Math.abs(A[k][k]);
var maxIndex = k;
for(i = k + 1; i < A.length; i++){
if(max < Math.abs(A[i][k])){
max = Math.abs(A[i][k]);
maxIndex = i;
}
}
if(maxIndex != k){
/*
troca a equação k pela equação com o
maior k-ésimo coeficiente em módulo
*/
for(j = 0; j < A.length; j++){
var temp = A[k][j];
A[k][j] = A[maxIndex][j];
A[maxIndex][j] = temp;
}
var temp = b[k];
b[k] = b[maxIndex];
b[maxIndex] = temp;
}
//Se A[k][k] é zero, então a matriz dos coeficiente é singular
//det A = 0
if(A[k][k] == 0){
return null;
}else{
//realiza o escalonamento
for(m = k + 1; m < A.length; m++){
var F = -A[m][k] / A[k][k];
A[m][k] = 0; //evita uma iteração
b[m] = b[m] + F * b[k];
for(l = k + 1; l < A.length; l++){
A[m][l] = A[m][l] + F * A[k][l];
}
}
}
}
//ETAPA DE RESOLUÇÃO DO SISTEMA
var X = [];
for(i = A.length - 1; i >= 0; i--){
X[i] = b[i];
for(j = i + 1; j < A.length; j++){
X[i] = X[i] - X[j] * A[i][j];
}
X[i] = X[i] / A[i][i];
}
return X;
}