#include <stdio.h>
#include <math.h>
#define N 4
#define EPSILON 1e-6
#define MAX_ITER 1000
void matrixVectorMultiply(double mat[N][N], double vec[N], double result[N]) {
for (int i = 0; i < N; i++) {
result[i] = 0;
for (int j = 0; j < N; j++) {
result[i] += mat[i][j] * vec[j];
}
}
}
double vectorNorm(double vec[N]) {
double sum = 0;
for (int i = 0; i < N; i++) {
sum += vec[i] * vec[i];
}
}
void normalizeVector(double vec[N]) {
double norm = vectorNorm(vec);
for (int i = 0; i < N; i++) {
vec[i] /= norm;
}
}
double powerMethod(double mat[N][N], double eigenvector[N]) {
double vec[N] = {1, 1, 1, 1}; // 初期ベクトル
double lambda = 0;
double lambda_old;
for (int iter = 0; iter < MAX_ITER; iter++) {
double temp[N];
matrixVectorMultiply(mat, vec, temp);
lambda_old = lambda;
lambda = vectorNorm(temp);
for (int i = 0; i < N; i++) {
vec[i] = temp[i];
}
normalizeVector(vec);
if (fabs(lambda
- lambda_old
) < EPSILON
) { break;
}
}
for (int i = 0; i < N; i++) {
eigenvector[i] = vec[i];
}
return lambda;
}
int main() {
double mat[N][N] = {
{16, -1, 1, 2},
{2, 12, 1, -1},
{1, 3, 24, 2},
{4, -2, 1, 20}
};
double eigenvector[N];
double eigenvalue = powerMethod(mat, eigenvector);
printf("最大固有値: %lf\n", eigenvalue
); for (int i = 0; i < N; i++) {
printf("%lf", eigenvector
[i
]); if (i < N - 1) {
}
}
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxtYXRoLmg+CgojZGVmaW5lIE4gNAojZGVmaW5lIEVQU0lMT04gMWUtNgojZGVmaW5lIE1BWF9JVEVSIDEwMDAKCnZvaWQgbWF0cml4VmVjdG9yTXVsdGlwbHkoZG91YmxlIG1hdFtOXVtOXSwgZG91YmxlIHZlY1tOXSwgZG91YmxlIHJlc3VsdFtOXSkgewogICAgZm9yIChpbnQgaSA9IDA7IGkgPCBOOyBpKyspIHsKICAgICAgICByZXN1bHRbaV0gPSAwOwog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JtYWxpemVWZWN0b3IodmVjKTsKCiAgICAgICAgaWYgKGZhYnMobGFtYmRhIC0gbGFtYmRhX29sZCkgPCBFUFNJTE9OKSB7CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgIH0KICAgIH0KCiAgICBmb3IgKGludCBpID0gMDsgaSA8IE47IGkrKykgewogICAgICAgIGVpZ2VudmVjdG9yW2ldID0gdmVjW2ldOwogICAgfQoKICAgIHJldHVybiBsYW1iZGE7Cn0KCmludCBtYWluKCkgewogICAgZG91YmxlIG1hdFtOXVtOXSA9IHsKICAgICAgICB7MTYsIC0xLCAxLCAyfSwKICAgICAgICB7MiwgMTIsIDEsIC0xfSwKICAgICAgICB7MSwgMywgMjQsIDJ9LAogICAgICAgIHs0LCAtMiwgMSwgMjB9CiAgICB9OwoKICAgIGRvdWJsZSBlaWdlbnZlY3RvcltOXTsKICAgIGRvdWJsZSBlaWdlbnZhbHVlID0gcG93ZXJNZXRob2QobWF0LCBlaWdlbnZlY3Rvcik7CgogICAgcHJpbnRmKCLmnIDlpKflm7rmnInlgKQ6ICVsZlxuIiwgZWlnZW52YWx1ZSk7CiAgICBwcmludGYoIuWvvuW/nOOBmeOCi+WbuuacieODmeOCr+ODiOODqzogWyIpOwogICAgZm9yIChpbnQgaSA9IDA7IGkgPCBOOyBpKyspIHsKICAgICAgICBwcmludGYoIiVsZiIsIGVpZ2VudmVjdG9yW2ldKTsKICAgICAgICBpZiAoaSA8IE4gLSAxKSB7CiAgICAgICAgICAgIHByaW50ZigiLCAiKTsKICAgICAgICB9CiAgICB9CiAgICBwcmludGYoIl1cbiIpOwoKICAgIHJldHVybiAwOwp9Cgo=