Почему эта программа LAPACK работает правильно, когда я предоставляю матрицу напрямую, а не когда я читаю ее из файла?

Ниже приведен код LAPACK для диагонализации матрицы A, который я предоставляю в виде массива a. Это всего лишь небольшая модификация официального примера, и, похоже, она дает правильные результаты. Это нецелесообразно, потому что я должен предоставить массив напрямую.

#include <stdlib.h>
#include <stdio.h>
#include <fstream>
#include <vector>/* DSYEV prototype */
extern "C"{
void dsyev( char* jobz, char* uplo, int* n, double* a, int* lda,
double* w, double* work, int* lwork, int* info );
}
/* Auxiliary routines prototypes */
extern "C"{
void print_matrix( char* desc, int m, int n, double* a, int lda );
}
/* Parameters */
#define N 5
#define LDA N

/* Main program */
int main() {
/* Locals */
int n = N, lda = LDA, info, lwork;
double wkopt;
double* work;
/* Local arrays */
double w[N];
double a[LDA*N] = {
1.96,  0.00,  0.00,  0.00,  0.00,
-6.49,  3.80,  0.00,  0.00,  0.00,
-0.47, -6.39,  4.17,  0.00,  0.00,
-7.20,  1.50, -1.51,  5.70,  0.00,
-0.65, -6.34,  2.67,  1.80, -7.10
};
/* Executable statements */
printf( " DSYEV Example Program Results\n" );
/* Query and allocate the optimal workspace */
lwork = -1;
dsyev( "Vectors", "Upper", &n, a, &lda, w, &wkopt, &lwork, &info );
lwork = (int)wkopt;
work = (double*)malloc( lwork*sizeof(double) );
/* Solve eigenproblem */
dsyev( "Vectors", "Upper", &n, a, &lda, w, work, &lwork, &info );
/* Check for convergence */
if( info > 0 ) {
printf( "The algorithm failed to compute eigenvalues.\n" );
exit( 1 );
}
/* Print eigenvalues */
print_matrix( "Eigenvalues", 1, n, w, 1 );
/* Print eigenvectors */
print_matrix( "Eigenvectors (stored columnwise)", n, n, a, lda );
/* Free workspace */
free( (void*)work );
exit( 0 );
} /* End of DSYEV Example */

/* Auxiliary routine: printing a matrix */
void print_matrix( char* desc, int m, int n, double* a, int lda ) {
int i, j;
printf( "\n %s\n", desc );
for( i = 0; i < m; i++ ) {
for( j = 0; j < n; j++ ) printf( " %6.2f", a[i+j*lda] );
printf( "\n" );
}
}

Я просто хочу изменить приведенный выше код, чтобы я мог читать массив из файла, а не предоставлять его напрямую. Для этого я написал функцию read_covariance который читает массив из файла peano_covariance.data. Содержимое последнего файла данных:

1.96 0.00 0.00 0.00  0.00
-6.49 3.80 0.00 0.00 0.00
-0.47 -6.39 4.17 0.00 0.00
-7.20 1.50 -1.51 5.70 0.00
-0.65 -6.34 2.67 1.80 -7.10

Ниже моя попытка, которая производит очень неправильные собственные значения и собственные векторы.

#include <stdlib.h>
#include <stdio.h>
#include <fstream>
#include <vector>int read_covariance (std::vector<double> data)
{
double tmp;

std::ifstream fin("peano_covariance.data");

while(fin >> tmp)
{
data.push_back(tmp);
}

return 0;
}

/* DSYEV prototype */
extern "C"{
void dsyev( char* jobz, char* uplo, int* n, double* a, int* lda,
double* w, double* work, int* lwork, int* info );
}
/* Auxiliary routines prototypes */
extern "C"{
void print_matrix( char* desc, int m, int n, double* a, int lda );
}
/* Parameters */
#define N 5
#define LDA N

/* Main program */
int main() {
/* Locals */
std::vector<double> data;
int n = N, lda = LDA, info, lwork;
double wkopt;
double* work;
/* Local arrays */
double w[N];
double a[LDA*N];
read_covariance(data);

std::copy(data.begin(), data.end(), a);
/* Executable statements */
printf( " DSYEV Example Program Results\n" );
/* Query and allocate the optimal workspace */
lwork = -1;
dsyev( "Vectors", "Upper", &n, a, &lda, w, &wkopt, &lwork, &info );
lwork = (int)wkopt;
work = (double*)malloc( lwork*sizeof(double) );
/* Solve eigenproblem */
dsyev( "Vectors", "Upper", &n, a, &lda, w, work, &lwork, &info );
/* Check for convergence */
if( info > 0 ) {
printf( "The algorithm failed to compute eigenvalues.\n" );
exit( 1 );
}
/* Print eigenvalues */
print_matrix( "Eigenvalues", 1, n, w, 1 );
/* Print eigenvectors */
print_matrix( "Eigenvectors (stored columnwise)", n, n, a, lda );
/* Free workspace */
free( (void*)work );
exit( 0 );
} /* End of DSYEV Example */

/* Auxiliary routine: printing a matrix */
void print_matrix( char* desc, int m, int n, double* a, int lda ) {
int i, j;
printf( "\n %s\n", desc );
for( i = 0; i < m; i++ ) {
for( j = 0; j < n; j++ ) printf( " %e", a[i+j*lda] );
printf( "\n" );
}
}

2

Решение

замещать

int read_covariance (std::vector<double> data)

с

int read_covariance (std::vector<double> & data)

Вы отправляете копию массива, а не ссылку на него. Это временная копия, которая заполняется значениями. Это то, на что ссылается bg2b в своем комментарии.

Лично я предпочел бы написать что-то вроде

int read_covariance (const std::string & fname)
{
std::ifstream in(fname.c_str());
double val;
std::vector<double> cov;
while(in >> val) cov.push_back(val);
return cov;
}

Еще лучше было бы использовать правильную библиотеку многомерных массивов, а не громоздкие 1d векторы. Существует множество таких библиотек, и я не уверен, что это лучший (отсутствие хорошего класса многомерного массива в стандартной библиотеке C ++ является одной из основных причин, почему я часто использую вместо этого fortran), но ndarray выглядит интересно — он стремится имитировать черты превосходного numpy модуль массива для питона.

4

Другие решения


По вопросам рекламы ammmcru@yandex.ru
Adblock
detector