Skip to content

Instantly share code, notes, and snippets.

@Erkaman
Last active December 10, 2023 01:14
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Erkaman/19b9916c6d00e9c54446bce6075769b5 to your computer and use it in GitHub Desktop.
Save Erkaman/19b9916c6d00e9c54446bce6075769b5 to your computer and use it in GitHub Desktop.
Accompanying source code for my article: https://erkaman.github.io/posts/jacobi_and_gauss_seidel.html
/*
This software is released under the MIT license:
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
// used to determine size of matrices and vectors in the program.
// change this value to increase the size of the linear system that is solved.
const int N = 300;
const float tolerance = 0.01f;
const int max_iterations = 100000000;
// vector of size N.
class Vec {
public:
float v[N];
Vec() {
for(int i = 0; i < N; ++i) {
v[i] = 0.0f;
}
}
void print(char* s) {
printf("%s ", s);
for(int i = 0; i < N; ++i) {
printf("%f, ", v[i]);
}
printf("\n");
}
};
// Matrrix of size NxN
class Mat {
public:
float m[N][N];
Mat() {
for(int i = 0; i < N; ++i) {
for(int j = 0; j < N; ++j) {
m[i][j] = 0.0f;
}
}
}
Vec mult(const Vec& v) {
Vec r;
for(int row = 0; row < N; ++row) {
for(int col = 0; col < N; ++col) {
r.v[row] += this->m[row][col] * v.v[col];
}
}
return r;
}
int gauss_seidel(Vec& x, const Vec& b, float tol, int max_iter) {
int iter = 0;
for(iter = 0; iter < max_iter; ++iter) {
for(int i = 0; i < N; ++i) {
float s = 0.0f;
for(int j = 0; j < N; ++j) {
if(j != i) {
s += this->m[i][j] * x.v[j];
}
}
// this is gauss-seidel, so we modify x in place!
x.v[i] = (1.0f / this->m[i][i]) * (b.v[i] - s);
}
/*
Calculuate residual.
*/
Vec mx = this->mult(x);
float res = 0.0f;
for(int i = 0; i < N; ++i) {
float a = mx.v[i] - b.v[i];
res += a*a;
}
res = sqrt(res);
// if residual smaller than tolerance, we are done.
if(res < tol) {
break;
}
}
return iter;
}
int jacobi(Vec& x, const Vec& b, float tol, int max_iter) {
int iter = 0;
for(iter = 0; iter < max_iter; ++iter) {
Vec temp;
for(int i = 0; i < N; ++i) {
float s = 0.0f;
for(int j = 0; j < N; ++j) {
if(j != i) {
s += this->m[i][j] * x.v[j];
}
}
// this is the jacobi-method, so we write to a temporary vector.
// Once the iteration is over, we update x.
temp.v[i] = (1.0f / this->m[i][i]) * (b.v[i] - s);
}
for(int i = 0; i < N; ++i) {
x.v[i] = temp.v[i];
}
/*
Calculuate residual
*/
Vec mx = this->mult(x);
float res = 0.0f;
for(int i = 0; i < N; ++i) {
float a = mx.v[i] - b.v[i];
res += a*a;
}
res = sqrt(res);
// If residual is within tolerance, we are done.
if(res < tol) {
break;
}
}
return iter;
}
};
/*
Jacobi and Gauss-seidel method converges only for a diagonally dominant matrix(or a symmetric positive definite matrix. boths works.)
https://en.wikipedia.org/wiki/Diagonally_dominant_matrix
So generate a random one here.
*/
Mat get_diagonally_dominant_matrix() {
Mat m;
/*
generate random matrix entries
*/
for(int i = 0; i < N; ++i) {
for(int j = 0; j < N; ++j) {
m.m[i][j] = 8.0f * float(rand() % 100)/100.0f - 3.0;
}
}
/*
Now we iterate over every row, and modify the matrix to make sure it's diagonally dominant.
*/
for(int i = 0; i < N; ++i) {
float diag = fabs(m.m[i][i]);
float row_sum = 0.0f;
for(int j = 0; j < N; ++j) {
if(i != j) {
row_sum += fabs(m.m[i][j]);
}
}
/*
Not diagonally dominant. So increase the diagonal value to fix that.
*/
if(!(diag >= row_sum)) {
m.m[i][i] += (row_sum - diag);
}
}
return m;
}
int main() {
srand(1); // random seed value.
for(int k = 0; k < 1; ++k) {
/*
First, we randomly generate a linear system that we will solve.
*/
Mat m = get_diagonally_dominant_matrix();
Vec expected_solution;
for(int i = 0; i < N; ++i) {
expected_solution.v[i] = 8.0f * float(rand() % 100) / 100.0f - 4.0f;
}
Vec b = m.mult(expected_solution);
/*
With that, we have generated a linear system
M*x = b.
Now let's solve it!
*/
Vec x;
for(int i = 0; i < N; ++i) {
x.v[i] = 1.0f;
}
printf("solving linear system where N = %d\n\n\n", N);
expected_solution.print("expected solution:");
printf("\n");
int iter;
iter = m.gauss_seidel(x, b, tolerance, max_iterations);
x.print("gauss-seidel method solution:");
printf("number of iterations: %d\n", iter);
printf("\n");
for(int i = 0; i < N; ++i) {
x.v[i] = 0.0f;
}
iter = m.jacobi(x, b, tolerance, max_iterations);
x.print("jacobi method solution:");
printf("number of iterations: %d\n", iter);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment