Last active
December 24, 2020 18:22
-
-
Save pedrolemoz/5a88b3fdb594a691ccde784aa1f55ec4 to your computer and use it in GitHub Desktop.
Gauss-Seidel Method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void main() { | |
final i = IterativeMethods(); | |
i.gaussSeidel( | |
precision: 4, | |
initialAproximation: [0, 0, 0], | |
maxIterations: 10, | |
matrix: [ | |
[5, 2, 1, 0], | |
[2, 4, 1, 2], | |
[0, -2, 3, -1] | |
], | |
); | |
} | |
class IterativeMethods { | |
void gaussSeidel({ | |
List<List<num>> matrix, | |
List<num> initialAproximation, | |
maxIterations = 10, | |
precision = 3, | |
}) { | |
if (_isDiagonallyDominant(matrix)) { | |
print('Gauss-Seidel method\n'); | |
var variables = List.generate(matrix.length, (_) => 0.0); | |
var identityMatrix = List.generate(matrix.length, (_) => 0.0); | |
var aproximation = | |
initialAproximation ?? List.generate(matrix.length, (_) => 0.0); | |
for (var i = 0; i < matrix.length; i++) { | |
identityMatrix[i] = matrix[i][i]; | |
} | |
for (var k = 0; k < maxIterations; k++) { | |
for (var i = 0; i < matrix.length; i++) { | |
var multiplication = 0.0; | |
for (var j = 0; j < matrix[i].length - 1; j++) { | |
if (i != j) { | |
multiplication += matrix[i][j] * aproximation[j]; | |
} | |
} | |
final total = matrix[i].last - multiplication; | |
variables[i] = total / identityMatrix[i]; | |
aproximation = variables; | |
} | |
_printValues( | |
index: k, | |
aproximation: aproximation, | |
precision: precision, | |
); | |
} | |
} else { | |
print('Error'); | |
} | |
} | |
bool _isDiagonallyDominant(List<List<num>> matrix) { | |
var isDiagonallyDominant = true; | |
for (var i = 0; i < matrix.length; i++) { | |
var sum = 0; | |
for (var k = 0; k < matrix[i].length - 1; k++) { | |
if (i != k) { | |
sum += matrix[i][k].abs(); | |
} | |
} | |
if (matrix[i][i].abs() < sum) { | |
isDiagonallyDominant = false; | |
break; | |
} | |
} | |
return isDiagonallyDominant; | |
} | |
void _printValues({List<num> aproximation, int precision = 3, int index}) { | |
var truncated = <String>[]; | |
aproximation | |
.forEach((value) => truncated.add(value.toStringAsFixed(precision))); | |
print(index != null ? '$index - $truncated' : '$truncated'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment