含有Rayleigh商加速的幂法求矩阵的特征值及特征向量代码c++
时间: 2023-06-21 08:15:07 浏览: 130
以下是C++代码,实现含有Rayleigh商加速的幂法求矩阵的特征值及特征向量:
```cpp
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
const int maxn = 100;
const double eps = 1e-8;
int n;
double A[maxn][maxn];
double x[maxn], y[maxn];
double dot(double x[], double y[]) {
double res = 0;
for (int i = 0; i < n; ++i) {
res += x[i] * y[i];
}
return res;
}
void mul(double A[][maxn], double x[], double y[]) {
for (int i = 0; i < n; ++i) {
y[i] = 0;
for (int j = 0; j < n; ++j) {
y[i] += A[i][j] * x[j];
}
}
}
void rayleigh(double A[][maxn], double x[], double &lambda) {
double a = dot(x, mul(A, x, y));
double b = dot(x, y);
lambda = a / b;
for (int i = 0; i < n; ++i) {
x[i] = y[i] / b;
}
}
void powerIteration(double A[][maxn], double &lambda, vector<double> &v) {
double norm = 0;
for (int i = 0; i < n; ++i) {
v[i] = 1;
}
while (true) {
mul(A, v.data(), x);
double maxv = fabs(x[0]);
for (int i = 1; i < n; ++i) {
if (fabs(x[i]) > maxv) {
maxv = fabs(x[i]);
}
}
for (int i = 0; i < n; ++i) {
v[i] = x[i] / maxv;
}
double lambda0 = lambda;
rayleigh(A, v.data(), lambda);
if (fabs(lambda - lambda0) < eps) {
break;
}
}
norm = 0;
for (int i = 0; i < n; ++i) {
norm += v[i] * v[i];
}
norm = sqrt(norm);
for (int i = 0; i < n; ++i) {
v[i] /= norm;
}
}
int main() {
cin >> n;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
cin >> A[i][j];
}
}
double lambda;
vector<double> v(n);
powerIteration(A, lambda, v);
cout << "Eigenvalue: " << lambda << endl;
cout << "Eigenvector: ";
for (int i = 0; i < n; ++i) {
cout << v[i] << " ";
}
cout << endl;
return 0;
}
```
其中,函数`mul`和`dot`分别实现了矩阵向量乘法和向量点积。函数`rayleigh`实现了Rayleigh商加速。函数`powerIteration`实现了幂法求矩阵的特征值及特征向量。在主函数中,首先读入矩阵的大小和元素,然后调用`powerIteration`函数求解特征值和特征向量,最后输出结果。
阅读全文