1

我有这段代码假设对两个向量进行 daxpy 操作并输出结果,但是当我运行它时它给了我 3 个 4(我认为它假设给了我 3 个 6)。

我觉得好像我错过了关于 daxpy 的一些重要的东西,但我不知道它是什么。

这是代码:

#include <iostream>
using namespace std;



extern "C"
{

    double daxpy_(double *A, double *B, int *n, double *a);
//The daxpy fortran function shown above multiplies a first matrix 'A' by a constant 'a'
//and adds the result to a second matrix 'B.' Both matrices are of size 'n.'
}

void daxpy(double *A, double *B, int n, double a);
//The function above is declared in order to utilize c-notation to perform the fortran
//daxpy function which takes a first matrix 'A' and multiplies the matrix by a costant 'a'
//and then adds the result to a second matrix 'B.'

int main(int argc, char *argv[])
{
    double A[3], B[3];
    int n=3;
    double a=1.0;
    for (int i=0;i<3;i++)
    {
        A[i]=2;
        B[i]=4;
    }
    daxpy(A, B, n, a);
    for (int i=0;i<3;i++)
    {
        cout << B[i] << endl;
    }
}

void daxpy(double *A, double *B, int n, double a)
{
  for (int i=0;i<n;i++)
  {
    B[i]=daxpy_(A, B, &n, &a);
  }
}
4

2 回答 2

2

你不打算这样做:

for (int i=0;i<3;i++)
{
    A[i]=2;
    B[i]=4;
}

那就是您正在访问数组边界之外的索引。对于大小为 3 的数组,最大索引为 A[2]。

于 2013-05-17T19:19:51.760 回答
1

这是关于daxpy的信息!最后!我已经对代码进行了评论,以使其更易于理解。我称 daxpy 完全错误。不过这会奏效!!!

答案是 6 6 6!

#include <iostream>
using namespace std;


extern "C" //This is important to get the function from the -lblas library you will use when compiling
{
    double daxpy_(int *n, double *a, double *A, int *incA, double *B, int *incB);
//The daxpy fortran function shown above multiplies a first matrix 'A' by a constant 'a'
//and adds the result to a second matrix 'B.' Both matrices are of size 'n.'
}

void daxpy(int n, double a, double *A, int incA, double *B, int incB);
//The function above is declared in order to utilize c-notation to perform the fortran
//daxpy function which takes a first matrix 'A' and multiplies the matrix by a costant 'a'
//and then adds the result to a second matrix 'B.'

int main(int argc, char *argv[])
{
    double A[3], B[3]; //Just initializing and filling up some matrices here
    int n=3, incA=1, incB=1;
    double a=1.0;
    for (int i=0;i<3;i++)
    {
        A[i]=2;
        B[i]=4;
    }
    daxpy(n, a, A, incA, B, incB); //This is the important part! Note the call notation
    for (int i=0;i<3;i++)
    {
        cout << B[i] << endl;
    }
}

void daxpy(int n, double a, double *A, int incA, double *B, int incB)
{
    daxpy_(&n, &a, A, &incA, B, &incB); //Once again, note the call notation. Important!
}

如何编译:g++ (program name) -lblas //Note the -lblas is calling the blas stuff

于 2013-05-17T20:19:40.830 回答