Search code examples
creturn-valuenumerical

C function returns 0 when shouldn't


I'm making a set of functions in C for simulate a microcanonial ensamble (a periodic-bounded box with N particles with fixed Energy and Volume). The point is that one of my main functions is to get the distance between 2 particles, and sometimes it returns 0 even if the particles are not that close.

The function is

// Determinar la mínima distancia dadas dos coordenadasy una longitud de caja periodica
float pdist(float x1, float y1, float x2, float y2, float a) {
   float Dx = abs(x2-x1);
   float Dy = abs(y2-y1);
   if(Dx >a/2) Dx = a-Dx;
   if(Dy >a/2) Dy = a-Dy;
   return sqrt(pow(Dx,2)+pow(Dy,2));
}

If you want to see all the code, you can see it in https://gitlab.com/jarr.tecn/statistical_mechanics

in the file box.h and one example in ejemplo.h


Solution

  • The problem comes from abs function which will return an integer:

    #include <math.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    float pdist(float x1, float y1, float x2, float y2, float a) {
        float Dx = abs(x2-x1);
        float Dy = abs(y2-y1);
        if(Dx >a/2) Dx = a-Dx;
        if(Dy >a/2) Dy = a-Dy;
        return sqrt(pow(Dx,2)+pow(Dy,2));
    }
    
    float pdist2(float x1, float y1, float x2, float y2, float a) {
        float Dx = fabsf(x2-x1);
        float Dy = fabsf(y2-y1);
        if(Dx >a/2) Dx = a-Dx;
        if(Dy >a/2) Dy = a-Dy;
        return sqrt(pow(Dx,2)+pow(Dy,2));
     }
    
    int main(void)
    {
        printf("first form: %f\n", pdist(.1, .1, .2, .2, .5));
        printf("second form: %f\n", pdist2(.1, .1, .2, .2, .5));
    }
    

    Gives:

    first form: 0.000000
    second form: 0.141421