0

I've written a function for calculating the standard deviation and the result is always '1.#QNAN0', I've tried formatting it in different ways but I can't find a solution. It was working on a different computer yesterday, is there anything I can do?

void CalcStandardDeviation(int count, int* nums, double mean, FILE* output){
    int k;
    double std=0,a;
    for (k=0; k<count; k++){
        a=nums[k]-mean;
        std=std+(a*a);
    }
    std/=(count);
    std=sqrt(std);
    fprintf(output,"Standard deviation: %f\r\n",std);
    fprintf(output,"\r\n");
   }
Matt Pashby
  • 33
  • 1
  • 2
  • 8
  • did you include `` and link with `-lm`? – Sourav Ghosh Mar 23 '15 at 13:22
  • possible duplicate of [1.#QNAN error C++](http://stackoverflow.com/questions/4617796/1-qnan-error-c) – phuclv Mar 23 '15 at 13:40
  • http://stackoverflow.com/questions/5939573/what-float-value-makes-sprintf-s-produce-1-qo http://stackoverflow.com/questions/7476177/why-the-return-value-of-double-is-1-ind?lq=1 http://stackoverflow.com/questions/347920/what-do-1-inf00-1-ind00-and-1-ind-mean – phuclv Mar 23 '15 at 13:41

2 Answers2

3

A NaN can only have three origins in your code:

  • mean is a NaN.
  • In std/=(count); if count is 0.
  • In std=sqrt(std); if std at this point is a negative number (seems impossible in your case).

You should debug your code and watch count and mean values (or print/export it) to find the why.

Orace
  • 7,822
  • 30
  • 45
  • Thanks, mean was NaN. In my CalculateMean function I printed it but didn't return it. Silly – Matt Pashby Mar 23 '15 at 13:31
  • (Technically, another possibility is that an `int` in `nums` is too large for `double`, so converting it to `double` (for the subtraction with `mean`) is not defined by the C standard. Or it converts to ∞, and `mean` is already ∞, so the subtraction yields NaN. Of course, this does not happen with ordinary ranges for `int` and `double`.) – Eric Postpischil Nov 14 '21 at 14:18
-1

This can occur when you declare a variable as a one type and, while printing, you give the variable in a different format.

For example, if you declare x as integer and then while printing x, you specify x with %f, then you may get it. I got this in the same way. View the image I posted

ouflak
  • 2,458
  • 10
  • 44
  • 49
jathin
  • 1
  • 1