سؤال

So in this program i am trying to print out the standard deviation of a set of numbers the user enters in. The formula to calculate standard deviation is correct (or as correct as it needs to be) so that is not the problem, but when i run the program everything goes well until the console prints out the results. It prints that totalStandardDeviation = nan

what exactly does than mean? is nan the same as nil? has it lost the value somehow and not been able to find it? thanks for any help you may provide.

#include <iostream>
#include <cmath>
using namespace std;

double returnStandardDeviation(double x, int counter);
double total;

int userInput = 1;
int counter = 0;
double x;
double x1;
double x2;

double standardDeviation;
double totalStandardDeviation;

int main(int argc, const char * argv[])
{
    cout << "Please enter a list of numbers. When done enter the number 0 \n";
    cin >> userInput;

    while (userInput != 0)                         // As long as the user does not enter 0, program accepts more data
    {
        counter++;
        x = userInput;
        returnStandardDeviation( x, counter);       // send perameters to function

        cout << "Please enter next number \n";
        cin >> userInput;
    }

    cout << "The standard deviation of your "
    << counter
    << " numbers is : "
    << returnStandardDeviation(x, counter);
    return 0;
}


double returnStandardDeviation(double x, int counter)
{
    x1 += pow(x,2);
    x2 += x;
    totalStandardDeviation = 0;
    totalStandardDeviation += (sqrt(counter * x1 - pow(x2,2))) / (counter * (counter - 1));
    return totalStandardDeviation;
}
هل كانت مفيدة؟

المحلول 4

Your formula is wrong. You are either dividing by zero or taking the square root of a negative number.

Check your formula!

Additional info:

NaN is "Not a number". It is an IEEE floating point value that signals an invalid results, like log(-1), or sqrt(-4).

Additionally, know that Positive Infinity and Negative Infinity are also floating point values.

نصائح أخرى

NaN stands for "Not a number".

NaN can e.g. be the result of:

- Dividing by zero
- Taking the square root of a negative number 

In your function, both of these could happen. Division by zero e.g. when counter is <= 1; and x1 and x2 are uninitialized (+= adds the value on the right to their current value - which was never set, and is therefore random gibberish), which can easily lead to your function trying to take the square root of some value < 0.

This expression

counter * x1 - pow(x2,2)

can very easily yield a negative number. You then proceed to take its square root. This would result in a nan.

Next, this one

counter * (counter - 1)

yields 0 when counter is 1. Dividing by zero gives nan.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top