在c中计算欧氏距离的函数

Function to calculate Euclidean distance in c

我编写了计算欧氏距离的函数。 Return 函数值不符合要求的精度范围。我将所有变量设为 double,这是最准确的类型,并使用了用于 double 而不是 sqrtfsqrt() 函数,但返回值仍然不正确。这是我的功能:


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;
}

提示为:函数distance()返回的值367.106262不在要求的精度范围内。

并测试:

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);

去掉透明项

OP 正在寻找 "distance" 颜色。

int 除最后一步外其他所有数学都很好

dist2 的最大值为 255*255*3 = 195,075,正好在 float 可编码范围内。

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);
}