手动计算范数

Manually calculating norm

我有下面显示的代码,它应该手动计算随机生成的向量的范数。但是,我一直将输出作为 0 打印到终端。为什么会这样?

#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <ctime>
using namespace std;

double ComputeNorm(const vector<double>& x) {
    double result = 0.0;
    for (auto a : x) {
        double result = result + a*a;
    }
    return sqrt(result);
}


int main() {
    // Declare variables
#if 0
    int n;
    cin >> n
#else
    int n = 1000;
#endif

    if (n == 0) {
        cout << "N must be > 0" << endl;
    }

    vector<double> x(n, 0.0);

    // Seed the random number generate with the current epoch time
    srand(time(0));

    // Generate random numbers and print them to the screen
    generate(x.begin(), x.end(), [] { return (double)rand()/RAND_MAX; });

    // Print out the values computed by BLAS and manually
//    cout << "BLAS Norm:   " << cblas_dnrm2(n, &x[0], 1) << endl;
    cout << "Manual norm: " << ComputeNorm(x) << endl;
//    cout << "x(n): " << x[n] << endl;
    return 0;
}
        double result = result + a*a;

这在循环内声明了一个新变量,因此另一个 result 变量不会改变,这就是返回 0 的原因。
要修复它,只需执行 result = result + a*aresult += a*a:

double ComputeNorm(const vector<double>& x) {
    double result = 0.0;
    for (auto a : x) {
        result = result + a*a;
    }
    return sqrt(result);
}

在您的 ComputeNorm 函数的 for 循环中,您在每次迭代中都重新声明了 result,而您循环之外的 result 从未更改过。

相反,您可能需要 result = result + a*a

我无法评论,因为我没有足够的声誉,但我想评论的是,您在函数`ComputeNorm.

中声明了两次局部变量result

这可能是您问题的根源。