Search code examples
c++functionalgebra

Calculation issue in C++


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

Solution

  • 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.