#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define SIZE 4
#define EPSILON 1e-9   // 収束判定条件
#define MAX_ITER 1000  // 最大反復回数

// ベクトルのノルム（ユークリッド長）を計算
double vector_norm(double *v, int n) {
    double sum = 0.0;
    for (int i = 0; i < n; i++) {
        sum += v[i] * v[i];
    }
    return sqrt(sum);
}

// 行列とベクトルの積 y = A * x
void mat_vec_mul(double A[SIZE][SIZE], double *x, double *y, int n) {
    for (int i = 0; i < n; i++) {
        y[i] = 0.0;
        for (int j = 0; j < n; j++) {
            y[i] += A[i][j] * x[j];
        }
    }
}

int main() {
    // 自身で設定した行列A
    double A[SIZE][SIZE] = {
        {1.0,  2.0, 3.0,  5.0},
        {3.0, -5.0, 1.0,  4.0},
        {5.0,  9.0, 2.0, -6.0},
        {1.0,  7.0, 4.0,  1.0}
    };

    double x[SIZE], y[SIZE], Ax[SIZE];
    double lambda_old = 0.0, lambda_new = 0.0;

    // 1. 初期値の設定 [1, 1, 1, 1]^T
    for (int i = 0; i < SIZE; i++) {
        x[i] = 1.0;
    }

    printf("=== べき乗法による収束状況の確認 ===\n");
    printf("初期ベクトル x(0): [%.1f, %.1f, %.1f, %.1f]\n\n", x[0], x[1], x[2], x[3]);
    printf("%-5s | %-12s | %-12s | %-30s\n", "Iter", "固有値(新)", "差分値", "固有ベクトルx(k)");
    printf("----------------------------------------------------------------------------\n");

    // べき乗法の反復ループ
    int actual_iters = 0;
    for (int iter = 1; iter <= MAX_ITER; iter++) {
        actual_iters = iter;
        
        // y = A * x
        mat_vec_mul(A, x, y, SIZE);

        // ノルムで正規化
        double norm_y = vector_norm(y, SIZE);
        if (norm_y < 1e-12) break;
        for (int i = 0; i < SIZE; i++) {
            y[i] /= norm_y;
        }

        // レイリー商を用いて固有値を高精度に推定
        mat_vec_mul(A, y, Ax, SIZE);
        double num = 0.0, den = 0.0;
        for (int i = 0; i < SIZE; i++) {
            num += y[i] * Ax[i];
            den += y[i] * y[i];
        }
        lambda_new = num / den;

        // 前のステップとの変化量を追跡
        double diff = fabs(lambda_new - lambda_old);

        // 収束状況の出力表示 (10回ごと、および最終ステップ)
        if (iter <= 5 || iter % 5 == 0) {
            printf("%-5d | %-12.8f | %-12.4e | [%.5f, %.5f, %.5f, %.5f]\n", 
                   iter, lambda_new, diff, y[0], y[1], y[2], y[3]);
        }

        // 収束判定条件のチェック
        if (diff < EPSILON) {
            if (iter % 5 != 0 && iter > 5) { // 最終ステップを確実に表示させる
                printf("%-5d | %-12.8f | %-12.4e | [%.5f, %.5f, %.5f, %.5f]\n", 
                       iter, lambda_new, diff, y[0], y[1], y[2], y[3]);
            }
            break;
        }

        // 次のステップに向けて x を更新
        for (int i = 0; i < SIZE; i++) {
            x[i] = y[i];
        }
        lambda_old = lambda_new;
    }

    printf("----------------------------------------------------------------------------\n");
    printf("反復回数 %d 回で収束しました。\n", actual_iters);

    // === 計算結果の表示 ===
    printf("\n=== 計算結果 ===\n");
    printf("最大固有値 (λ1)          : %.10f\n", lambda_new);
    printf("対応する固有ベクトル (x1) : [");
    for (int i = 0; i < SIZE; i++) {
        printf("%.10f%s", y[i], (i == SIZE - 1) ? "]\n" : ", ");
    }

    // === 確かに固有値・固有ベクトルであることの検証 (Ax = λx) ===
    printf("\n=== 検証: Ax と λx の比較 ===\n");
    mat_vec_mul(A, y, Ax, SIZE); // Axを再計算
    printf("Ax    : [");
    for (int i = 0; i < SIZE; i++) {
        printf("%.6f%s", Ax[i], (i == SIZE - 1) ? "]\n" : ", ");
    }
    printf("λ * x : [");
    for (int i = 0; i < SIZE; i++) {
        printf("%.6f%s", lambda_new * y[i], (i == SIZE - 1) ? "]\n" : ", ");
    }

    return 0;
}
