乘幂法求主特征值和特征向量(C++)

代码来源

链接

做法

默认为 有唯一的特征值的情况下,求出主特征值和特征向量

代码中是迭代3次(cnt)

初始向量x,不断左乘矩阵A,不断更新该向量x即可。

主特征值就是 新的x1 除以 旧的x1

代码

#include<bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
#define ll long long
#define _for(i, x, n) for(int i = x; i <= n; i++)

void LOOP(float a[20][20], float u[20], int);
float MAX(float u[20], int);

int main()
{
    float a[20][20], u[20], x[20],y,z;
    int i,j,n;
    printf("阶数:");
    scanf("%d", &n);
    printf("元素值:");
    for(i = 0; i < n; i++)
    {
        for(j = 0; j < n; j++)
        {
            scanf("%f", &a[i][j]);
        }
    }
    printf("迭代向量:");
    for(i = 0; i < n; i++)
        scanf("%f", &u[i]);

    y = MAX(u, n);
    for(int cnt = 1; cnt <= 3; cnt++)
    {
        z = y;
        LOOP(a, u, n);
        y = MAX(u, n);
        for(i = 0; i < n; i++)
        {
            x[i] = u[i] / y;
            u[i] = x[i];
        }
        cout << "过程的特征值" << y << endl;
    }
    printf("矩阵的特征值:%f\n", y);
    printf("矩阵的特征向量:");
    for(int i = 0; i < n; i++)
    {
        printf("%f ", x[i]);
    }
    return 0;
}

void LOOP(float a[20][20], float u[20], int n)
{
    float S, U[20];
    int i, j;
    for(int i = 0; i < n; i++)
    {
        U[i] = u[i];
    }
    for(int i = 0; i < n; i++)
    {
        S = 0.0;
        for(int j = 0; j < n; j++)
        {
            S = S + a[i][j] * U[j];
        }
        u[i] = S;
    }
}
float MAX(float u[20], int n)
{
    float maxi;
    int i;
    maxi = u[0];
    for(i = 0; i < n; i++)
    {
        if(u[i] > maxi)
        {
            maxi = u[i];
        }
    }
    return maxi;
}
/*
3
1 -1 0
-2 4 -2
0 -1 1
1 0 0
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值