求SVD算法的C++实现代码

来源:百度知道 编辑:UC知道 时间:2024/05/22 03:11:01
RT

/** C++ function for SVD
函数原型:
bool svd(vector<vector<double> > A, int K, std::vector<std::vector<double> > &U, std::vector<double> &S, std::vector<std::vector<double> > &V);
其中
A是输入矩阵,假设A的维数是m*n,那么本函数将A分解为U diag(S) V'
其中U是m*K的列正交的矩阵. V是n*K的列正交矩阵,S是K维向量。K由第二个参数指定。
U的第i列是A的第i大奇异值对应的左歧义向量,S[i]=A的第 i大奇异值,V的第i列是A的第i大奇异值对应的右歧义响亮.
K是需要分解的rank,0<K<=min(m,n)

本程序采用的是最基本幂迭代算法,在linux g++下编译通过
**/


#include <cmath>
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <vector>
using namespace std;
const int MAX_ITER=100000;
const double eps=0.0000001;

double get_norm(double *x, int n){
    double r=0;
    for(int i=0;i<n;i++)
        r+=x