Anna
Anna

Reputation: 83

sqrt function in C++

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.

Upvotes: 0

Views: 1496

Answers (5)

Mark Ransom
Mark Ransom

Reputation: 308111

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.

Upvotes: 0

bibbsey
bibbsey

Reputation: 1029

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

Upvotes: 0

tmpearce
tmpearce

Reputation: 12683

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"

Upvotes: 0

parkovski
parkovski

Reputation: 1513

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?

Upvotes: 2

Ry-
Ry-

Reputation: 224859

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;

Upvotes: 0

Related Questions