diff options
author | Elizabeth Hunt <elizabeth.hunt@simponic.xyz> | 2023-11-15 14:16:15 -0700 |
---|---|---|
committer | Elizabeth Hunt <elizabeth.hunt@simponic.xyz> | 2023-11-15 14:16:15 -0700 |
commit | 1a6b95273628d898226eb448c8b671dc33f3c495 (patch) | |
tree | 08ebde756da3214142acaaa15ef45a1eea7e9970 /src | |
parent | 3f1f18b149788fe69180dc2a348fd32425bb9a3f (diff) | |
download | cmath-1a6b95273628d898226eb448c8b671dc33f3c495.tar.gz cmath-1a6b95273628d898226eb448c8b671dc33f3c495.zip |
compute dominant eigenvalue
Diffstat (limited to 'src')
-rw-r--r-- | src/eigen.c | 31 | ||||
-rw-r--r-- | src/matrix.c | 10 |
2 files changed, 41 insertions, 0 deletions
diff --git a/src/eigen.c b/src/eigen.c new file mode 100644 index 0000000..aaacedc --- /dev/null +++ b/src/eigen.c @@ -0,0 +1,31 @@ +#include "lizfcm.h" +#include <assert.h> +#include <math.h> +#include <stdio.h> +#include <string.h> + +double dominant_eigenvalue(Matrix_double *m, Array_double *v, double tolerance, + size_t max_iterations) { + assert(m->rows == m->cols); + assert(m->rows == v->size); + + double error = tolerance; + size_t iter = max_iterations; + double lambda = 0.0; + Array_double *eigenvector_1 = copy_vector(v); + + while (error >= tolerance && (--iter) > 0) { + Array_double *eigenvector_2 = m_dot_v(m, eigenvector_1); + + Array_double *mx = m_dot_v(m, eigenvector_2); + double new_lambda = + v_dot_v(mx, eigenvector_2) / v_dot_v(eigenvector_2, eigenvector_2); + error = fabs(new_lambda - lambda); + lambda = new_lambda; + + free_vector(eigenvector_1); + eigenvector_1 = eigenvector_2; + } + + return lambda; +} diff --git a/src/matrix.c b/src/matrix.c index 0891734..04c5adc 100644 --- a/src/matrix.c +++ b/src/matrix.c @@ -42,6 +42,16 @@ Matrix_double *m_dot_m(Matrix_double *a, Matrix_double *b) { return prod; } +Matrix_double *transpose(Matrix_double *m) { + Matrix_double *transposed = InitMatrixWithSize(double, m->cols, m->rows, 0.0); + + for (size_t x = 0; x < m->rows; x++) + for (size_t y = 0; y < m->cols; y++) + transposed->data[y]->data[x] = m->data[x]->data[y]; + + return transposed; +} + Matrix_double *put_identity_diagonal(Matrix_double *m) { assert(m->rows == m->cols); Matrix_double *copy = copy_matrix(m); |