I have a process in my client program that iterates through a custom vector, and performs some calculations to calculate standard deviation. It converts a wind speed from m/s to km/h, so its *3.6 to convert. For my sigma value, and of course my standard deviation which requires the sigma value, my output is NaN and I can't understand why this is the case.
Main.cpp:
float sum;
float convertedspeed[windlog.size()];
float sigma;
float averagespeed;
//float conversion;
float sd;
int nrofel;
ofstream ofile("testoutput.csv");
ofile << "WAST, S, \n";
for(int i = 0; i < windlog.size(); i++){
nrofel = windlog.size();
convertedspeed[i] = (windlog[i].speed*3.6);
sum += convertedspeed[i];
averagespeed = (sum/nrofel);
sigma += (convertedspeed[i] - averagespeed)*(convertedspeed[i] - averagespeed);
sd = sqrt(sigma/(nrofel - 1));
All my values are okay except when it gets to sigma so I expect its going wrong there. What could be the issue?
You must initialize variables before using.
Strictly speaking, in this case, you don't have to initialize nrofel
, averagespeed
, and sd
because they are assigned some values in the loop without being read before assignment.
On the other hand, you must initialize sum
and sigma
because their values are read before assignment.