Search code examples
cfloating-accuracyeuclidean-distance

Function to calculate Euclidean distance in c


I wrote function which calculates Euclidean distance. Return value of function doesn't fit in required accuracy range. I made all the variables double which is the most accurate type and used sqrt() function which is for double not sqrtf and still the returned value is not proper. Here is my function:


float distance(const struct color_t* p1, const struct color_t* p2, int* err_code) {
        if (p1 == NULL || p2 == NULL) {
            return -1;
        }
     double r1 = 1, r2 = 1, r3 = 1, r4=1;
    double p11 = (double)p1->r - (double)p2->r;
    double p22 = (double)p1->g - (double)p2->g;
    double p33 = (double)p1->b - (double)p2->b;
    double p44 = (double)p1->a - (double)p2->a;
    for (int exponent = 2; exponent > 0; exponent--)
    {
        r1 = r1 * p11;
        r2 = r2 * p22;
        r3 = r3 * p33;
        r4 = r4 * p44;
    }
    double b = r1 + r2 + r3 + r4;
    double a = sqrt(b);
    if (a < 0) {
        return -1;
    }   
    return a;
}

Prompt is: Value 367.106262 returned by function distance() doesn't fit in required accuracy range.

and test:

struct color_t c1 = {.r = 14, .g = 253, .b = 23, .a = 76}, c2 = {.r = 253, .g = 14, .b = 148, .a = 6};

            printf("#####START#####");
            float dist = distance(&c1, &c2, NULL);
            printf("#####END#####\n");

            test_error(360.4206425334894 > dist && 360.3206425334894 < dist, "Value %f returned by function distance() doesn't fit in required accuracy range", dist);

Solution

  • Drop the transparent term

    @abelenky

    OP is looking for the "distance" in color.

    int math fine for all but last step

    Largest value for dist2 is 255*255*3 = 195,075, well within float exactly encodable range.

    float distance(const struct color_t *p1, const struct color_t *p2, int *err_code /* unused */ ) {
      if (p1 == NULL || p2 == NULL) {
        return -1;
      }
      int p11 = p1->r - p2->r;
      int p22 = p1->g - p2->g;
      int p33 = p1->b - p2->b;
      int dist2 = p11*p11 + p22*p22 + p33*p33;
      return sqrtf(dist2);
    }