Eigen 求解线性方程组

来源:互联网 发布:淘宝买车分期付款 编辑:程序博客网 时间:2024/06/07 06:26
#include <iostream>  #include <Eigen/Dense>#include <Eigen/Cholesky>  #include <Eigen/LU>  #include <Eigen/QR>  #include <Eigen/SVD>  using namespace std;using namespace Eigen;  int main()  {          //线性方程求解 Ax =B;      //求解四元一次方程组,Matrix4d 为double类型4*4矩阵,Vectpr4d 为double类型4*1向量,Answer=[1;2;3;4]    Matrix4d A;          A <<  1    , 2   ,  3   ,  4,        1    , 4   ,  3    , 2,        1   ,  3  ,   2    , 4,        4   ,  1   ,  1   ,  3;          Vector4d B(30,26,29,21);          Vector4d x1 = A.colPivHouseholderQr().solve(B); //                                      right Answer         Vector4d x2 = A.llt().solve(B);          Vector4d x3 = A.ldlt().solve(B);    Vector4d x4 = A.ldlt().solve(B);// A sym. p.s.d.    #include <Eigen/Cholesky>           wrong Answer    Vector4d x5 = A.llt() .solve(B);  // A sym. p.d.      #include <Eigen/Cholesky>         wrong Answer    Vector4d x6 = A.lu()  .solve(B);  // Stable and fast. #include <Eigen/LU>               right Answer    //Vector4d x7 = A.qr()  .solve(B);  // No pivoting.     #include <Eigen/QR>             wrong Answer    //Vector4d x8 = A.svd() .solve(B);  // Stable, slowest. #include <Eigen/SVD>            wrong Answer    std::cout <<A<<std::endl;    std::cout << "The solution is:\n" << x1 <<"\n\n"<<x2<<"\n\n"<<x3 <<"\n\n"<<x4 <<"\n\n"<<x5 <<"\n\n"<<x6 <<std::endl;      //求解三元一次方程组,Matrix3d 为double类型3*3矩阵,Vectpr3d 为double类型3*1向量, Answer=[1;2;3]    Matrix3d A2;          A2 <<  1,2,3,            3,1,2,            1,2,0;          Vector3d B2(14,11,5);          Vector3d x12 = A2.colPivHouseholderQr().solve(B2); //right Answer        Vector3d x62 = A2.lu().solve(B2);                  // right Answer    std::cout <<A2<<std::endl;    std::cout << "The solution is:\n" << x12 <<"\n\n"<<x62 <<std::endl;  }
原创粉丝点击