Eigen 求解线性方程组

#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;  


}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值