我试着理解为什么Eigen :: SVD,LDLT和QR为同一个矩阵提供不同的解决方案?我的代码非常简单,我将非常感谢您的意见。 非常感谢你提前。
结果:
************************
Polynomial fit for power of 4 :
ldlt() solution:
-0.000267566
-0.000208661
0.118686
-1.06809
4.2021
SVD solution:
-0.00324908
0.0892368
-0.713157
1.46619
2.41319
QR solution:
-0.00152415
0.0374888
-0.2319
0
3.44815
hand-made solution:
0.00447083
-0.131592
1.51172
-5.22656
7.11719
************************
代码:
double basic_function_(double x)
{
return sin(x / 5) * exp(x / 10) + 5 * exp(-x / 2);
}
int main(){
vector<double> x, y;
int power = 4;
x = {1.0, 4.0, 10.0, 15.0};
for (int i = 0; i < power; ++i)
y.push_back(basic_function_(x[i]));
//matrix size after basic logic confirmation (skipped)
unsigned int matrix_size_ = power;
//initializing f(x) vector and Matrix of x's
Eigen::VectorXd temp_y_ = Eigen::VectorXd::Map(&y[0], y.size());
Eigen::MatrixXd X(matrix_size_, matrix_size_+1);
for (int i = 0; i < matrix_size_; ++i)
for (int j = 0; j <= matrix_size_; ++j)
X(i, j) = pow(x[i], (matrix_size_ - j) );
//different solutions
//solution 1
Eigen::VectorXd a = (X.transpose() * X).ldlt().solve(X.transpose() * temp_y_);
//solution 2 (SVD)
Eigen::VectorXd a1 = X.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(temp_y_);
//Solution 3
Eigen::VectorXd a2 = X.colPivHouseholderQr().solve(temp_y_);
//Solution 4 (actually, solution 1, but simply hand-made)
Eigen::MatrixXd LHS_temp_, RHS_temp_, a3;
LHS_temp_ = X.transpose() * X;
LHS_temp_ = LHS_temp_.inverse();
RHS_temp_ = X.transpose() * temp_y_;
a3 = LHS_temp_ * RHS_temp_;
cout << " ************************ " << endl;
cout << "Polynomial fit for power of " << matrix_size_<< " :" << endl;
cout << "ldlt() solution:\n" << a << endl;
cout << "SVD solution:\n" << a1 << endl;
cout << "QR solution:\n" << a2 << endl;
cout << "hand-made solution:\n" << a3 << endl;
cout << " ************************ " << endl << endl;
return 0;
}
答案 0 :(得分:3)
你有4个数据点并且用一个度数为4(即5个自由度)的polinoomial拟合它们。这意味着,剩下一个自由度,即解决方案不是唯一的。所有解决方案都完美地符合数据点。