Manually calculating norm

345 Views Asked by At

I have this code shown below which is supposed to manually calculate the norm of a randomlly generated vector. However, I keep getting the output being printed to the terminal as 0. Why is the case?

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

There are 3 best solutions below

0
IlCapitano On BEST ANSWER
        double result = result + a*a;

This declares a new variable inside the loop, so the other result variable doesn't change, which is why 0 is returned.
To fix it just do result = result + a*a or result += a*a:

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

In the for loop in your ComputeNorm function, you have been redeclaring result in every iteration, while the result outside of you loop was never changed.

Instead, you might want result = result + a*a there.

0
Aleix Rius On

I can't comment because I don't have enough reputation, but what I want to comment is that you are declaring the local variable resulttwice inside the function `ComputeNorm.

That may be the root of your problem.