比较函数中的双精度数

时间:2016-11-09 03:24:58

标签: c floating-point compare floating-accuracy

这是我的计划的一部分:

int calculation ( double f_a, double f_b, double s_a, double s_b, double seam) {
    int x, y, r1, r2;
    double waste_x, waste_y, c;

    x = (int)floor( s_a/f_a);
    if ( equality(s_a-(f_a*x), 0) != 1) { //overlapping is better than missing though if there's no overlap, no need to add another piece of fabric
        x++;
    }
    waste_x = x*f_a - s_a; //how much is wasted
    if ( (greater((x-1)*seam,waste_x) == 1) ) { //seamed part of fabric has to be within the waste, greater and not eq
        x++;
    }
        y = (int)floor( s_b/f_b);
    if ( equality(s_b-(f_b*y),0) != 1) {
        y++;
    }
    waste_y = y*f_b - s_b;
    if ( greater((y-1)*seam,waste_y) == 1 ) {
        y++;
    }
    r1 = x*y;

    c = s_a;
    s_a = s_b;
    s_b = c; //swapping dimensions of sail
    //repeat the process
    x = (int)floor( s_a/f_a);
    if ( equality(s_a-(f_a*x),0) != 1) {
        x++;
    }
    waste_x = x*f_a - s_a;
    if ( greater((x-1)*seam,waste_x) == 1 ) {
        x++;
    }
    y = (int)floor( s_b/f_b);
    if ( equality(s_b-(f_b*y),0) != 1) {
        y++;
    }
    waste_y = y*f_b - s_b;
    if ( greater((y-1)*seam,waste_y) == 1 ) {
        y++;
    }
    r2 = x*y;

    if ( r1 >= r2)
        return r2;
    else
        return r1;
}

int equality (double a, double b) {
    if ( fabs(a-b) <= a*DBL_EPSILON ) {
        return 1;
    }
    else
        return 0;
}
int greater (double a, double b) {
    if ( (a-b) > DBL_EPSILON) {
        printf("%f is greater than %f, returning 1.\n", a, b);
        return 1;
    }
    else {
        printf("%f is not greater than %f, returning 0.\n", a, b);
        return 0;
    }
}

我到目前为止遇到的问题是输入:

f_a = 0.71
f_b = 1
s_a = 4.91
s_b = 1.7
seam = 0.01

我会将(x-1)*seam 0.06waste_x 0.0599999进行比较,换句话说,(x-1)*seamwaste_x应该相等

我的函数greater()应返回0,因为它们之间的差异应小于EPSILON - a不大于b但小于或等于。

我最好的猜测是我的greater()功能没有正确实现,我不太了解机器精度。

那么如何让这段代码工作呢?

0 个答案:

没有答案