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;
}
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);
}