Function giving wrong values

Asked

Viewed 394 times

2

For some reason, my function of calculating distances is sometimes giving wrong values. Not only that, but the values seem to be from memory addresses (because they are very large), but I’m not sure that’s it. The function:

float distancia(int ax, int ay, int bx, int by) // Calcula a distancia entre dois pontos, onde eh respectivamente (X1 Y1), (X2 Y2)
{
    return(sqrt((pow((ax - bx), 2)) + (pow((ay - by), 2))));  
}

One of the functions calling the function above. It writes in a txt document and the printed values there come out wrong:

void arquivoDistancia(float matrizDistancia[][30])
{
    FILE *aquivoDeSaida;
    int cont = 0, cont2 = 0;

    aquivoDeSaida = fopen("distancia.txt", "w");
    while( cont < 30 ) //loop para gravar os dados no arquivo.
    {
        while( cont2 < 30 ) //loop para gravar os dados no arquivo.
        {   
           fprintf(aquivoDeSaida, "%.2f ", matrizDistancia[cont][cont2]); //grava garacter a caracter no arquivo apontado por custo.
           cont2++;      
        }
        fprintf(aquivoDeSaida, "\n");
        cont++;
        cont2 = 0;      
    }
    fclose(aquivoDeSaida); 


} 

And this is the function that makes the matrix Istancia[][30]. Note that I even put a printf to see the values. The problem starts here by the way. It prints all right at first but then starts to appear strange numbers

void mDistancia(char cidadeXY[][150], int coordenadasX[], int coordenadasY[], float matrizDistancia[][30])
{
    int c, i, contadorC, contadorI;
    float dij; 

    for(i = 0, contadorI = 0; i < 30; i++, contadorI += 2)
    {
        for(c = 0, contadorC = 0; c < 30; c++, contadorC += 2)
        {
            dij = distancia(coordenadasX[contadorI], coordenadasY[contadorI], coordenadasX[contadorC], coordenadasY[contadorC]);
            printf("%.2f ", dij);
            matrizDistancia[i][c] = dij;
        }
    }

}
  • 1

    You need to learn to debug the code yourself. Print the value returned by distancia() on the screen, as well as its parameters, and see if they make sense. After making sure this part is OK, you worry about writing the data into the file.

  • I printed the figures. I even mentioned it in the question.

  • I saw it. "Strange" numbers are results of the calculation you make. Print as well the parameters that are being passed on to distancia(), and when you find a "strange" result you will be able to use your calculator to manually check if the result makes sense (or not). I suspect the problem is the values stored by coordenadasX and coordenadasY.

  • Beauty. I’ll do that. I printed the values of the x and y coordinates and it’s not them.

  • When manually calculating with these values, you detected that the result of distancia() is correct when they are used or at this point the result no longer makes sense?

  • The distance() result is not correct. It is only at the beginning that he does it right. Then very large wrong values start to appear.

  • Could you exemplify with example values? What numbers are passed to distancia() and what value it returns in this case?

  • @I don’t program in C, but I think your problem is with accuracy. You should be careful with numerical types because they are different and can give you a lot of headache. The answer from karlphillip will certainly suit you.

Show 3 more comments

2 answers

4

It is good to keep in mind that the signature of sqrt() informs that he returns a double. When trying to save your result to a variable float you may end up losing information, which would justify the problem you observed.

On the other hand, sqrtf() returns a float, which would be more appropriate in your case.

1

for(i = 0, contadorI = 0; i < 30; i++, contadorI += 2)
//                                     ^^^^^^^^^^^^^^
{
    for(c = 0, contadorC = 0; c < 30; c++, contadorC += 2)
    //                                     ^^^^^^^^^^^^^^
    {
        dij = distancia(coordenadasX[contadorI], coordenadasY[contadorI], coordenadasX[contadorC], coordenadasY[contadorC]);

Why are the variables contadorI and contadorC Advance 2 by 2?

This way you will never calculate the distances between points with odd indices; besides you will be accessing elements (probably) missing from the arrays.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.