通过LAPACK在线性方程的解决方案中缺少一个元素

时间:2014-12-17 17:12:56

标签: c++ blas armadillo

我对从线性方程组得到的解决方案感到困惑。我的目标是通过lapack中的函数求解线性方程:A*x = e。这是我的代码:

#include <iostream>
#include "/usr/include/armadillo"
#include "/usr/local/include/lapacke.h"

using namespace std;

int main()
{
    int n = 3;
    arma::fvec alpha( n );//define a vetor alpha with a size 3
    arma::fvec beta( n );//define a vector beta with a size 2
    alpha << 1 << 2 << 3 << arma::endr;//assign 1,2,3 to alpha;
    beta << 0.3 << 0.6 << arma::endr;//assign 0.3, 0.6 to beta;
    float a = 0.1;
    arma::fvec e = arma::zeros<arma::fvec>( n );//define a vector e with all element equal to 0;
    e( n - 1 ) = beta( n - 2 ) * beta( n - 2 ); //the last element of e equals to the square of the last element of vector beta;
    arma::fvec tri_alpha = alpha - a;
    LAPACKE_sgtsv(LAPACK_COL_MAJOR, n, 1, &( beta[ 0 ] ), &( tri_alpha[ 0 ] ), &( beta[ 0 ] ), &( e[ 0 ] ), n );
    cout << e.t() << endl;
    return 0;
}

矢量alpha在对角线上,矢量β在子对角线和超对角线上构造三对角矩阵,假设它是T.以下是函数sgtsv的解释。 / p>

LAPACKE_sgtsv( int matrix_order, int n, int nrhs, float *dl, float *d, float *du, float *b, int ldb)

B is REAL array, dimension (LDB,NRHS),On exit, if INFO = 0, the N by NRHS solution matrix X

在我的情况下,B = e,我最后输出e,它是(0, -0.0444, 0.1333),显然,正确答案应该是(0.0148, -0.0444, 0.1333),那么第一个元素是错误的或者可能缺乏,任何人都可以帮我一个忙?谢谢。顺便说一句,我使用的图书馆是犰狳。

1 个答案:

答案 0 :(得分:0)

根据sgtsv()的{​​{3}},三对角矩阵DU的上方(DL)和下方(A)对角线将被覆盖为线性方程得以解决。

  

在退出时,DL被L的LU因子分解,上三角矩阵U的第二超对角线的(n-2)个元素覆盖,DL(1),...,DL(n- 2)&#34;

并且:

  

退出时,DU被U的第一个超对角线的(n-1)个元素覆盖。

问题出现是因为beta应该同时是上对角DU和下对角DL

解决方案是复制beta

#include <iostream>

#include "/usr/include/armadillo"
#include "/usr/local/include/lapacke.h"

//#include "/usr/local/include/armadillo"
//#include "lapacke.h"

using namespace std;

int main()
{
    int n = 3;
    arma::fvec alpha( n );//define a vetor alpha with a size 3
    arma::fvec beta( n );//define a vector beta with a size 2
    alpha << 1 << 2 << 3 << arma::endr;//assign 1,2,3 to alpha;
    beta << 0.3 << 0.6 << arma::endr;//assign 0.3, 0.6 to beta;
    float a = 0.1;
    arma::fvec e = arma::zeros<arma::fvec>( n );//define a vector e with all element equal to 0;
    e( n - 1 ) = beta( n - 2 ) * beta( n - 2 ); //the last element of e equals to the square of the last element of vector beta;
    arma::fvec tri_alpha = alpha - a;

    arma::fvec betabis( n );//define a vector betabis with a size 2...copy of beta
    betabis=beta;
    LAPACKE_sgtsv(LAPACK_COL_MAJOR, n, 1, &( beta[ 0 ] ), &( tri_alpha[ 0 ] ), &( betabis[ 0 ] ), &( e[ 0 ] ), n );
    cout << e.t() << endl;
    return 0;
}