Question

I'm running this code to calculate square root of x[i][j] - y[j] but it gives me nonsense!

     bool X[I][J]={};   //nodes
     bool Y[J]={};      //medians

    double denominator=0;
    double miu=0;
    outFile<< "denominator= " << denominator << endl;
    for(i=0;i<I;i++)
        for(j=0;j<J;j++)
        {
            denominator+=sqrt(double (X[i][j]-Y[j]));
        }
    outFile<< "denominator= " << denominator << endl;

The first outFile prints 0 which is the original value but the second one prints -1.#IND.

Was it helpful?

Solution

That probably means that at some point X[i][j] - Y[j] was negative, and you're getting a NaN (not a number) back from sqrt.

See this wikipedia page for an explanation of NaNs.

Also, X and Y are arrays of booleans, so X[i][j] - Y[j] will always be 1, 0, or -1, and you really don't need the sqrt. Is this what you want?

OTHER TIPS

The problem is that you can't take the square root of a negative number - you get an imaginary number. Just use abs to retrieve the absolute value of the difference first:

bool X[I][J] = {};   // nodes
bool Y[J] = {};      // medians

double denominator = 0;
double miu = 0;
outFile << "denominator= " << denominator << endl;
for(i = 0; i < I; i++)
    for(j = 0; j < J; j++)
    {
        denominator += sqrt(double (abs(X[i][j]-Y[j])));
    }
outFile << "denominator= " << denominator << endl;

Looks like you may be taking the square root of a negative number - leads to the value you see which essentially means "not a number"

Since both X and Y are bool, there are chances for the argument that is passed to sqrt() to be negative.

I don't get the same results you do, I get zero for both.

http://ideone.com/25ZPf

The initializers for both arrays should set all values to zero, so the square root of the subtraction should be zero as well. The fact that they're boolean arrays shouldn't matter since the values will be upcasted to 0.0.

Something tells me the code you posted isn't the actual code that's causing the error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top