Gilfoyle
Gilfoyle

Reputation: 3616

Smallest EPSILON to comparing double variables in C?

In my program I put specific coordinates into a list. However, the algorithm sometimes puts the same coordinates into the list twice. In order to avoid that, I do the standard approach by comparing the EPSILON value to the absolute difference of both x and y values off all positions in the list:

bool doubleEqual(double x1, double y1, double x2, double y2){
    if( (fabs(x1-x2) < EPSILON) && (fabs(y1-y2) < EPSILON) ){
        return TRUE; // particle is already in list
    }
    return FALSE; // particle is not in the list
}

I have several questions:

1) Is this implementation to compare the position of two particles even correct?

2) How small can I choose EPSILON? (The particles can come really close to each other)

3) Is there any faster / or more robust implementation to compare the position of particles?

Upvotes: 0

Views: 877

Answers (1)

chux
chux

Reputation: 153456

However, the algorithm sometimes puts the same coordinates into the list twice. In order to avoid that ...

yes, I mean the same coordinates (same particles = same position). Not just two double variables which are very close to each other.

To avoid to XY elements that are the same, a simple compare is sufficient

bool doubleEqual(double x1, double y1, double x2, double y2){
    return (x1 == x2) && (y1 == y2);
}

1) Is this implementation to compare the position of two particles even correct?

Using a fixed difference (epsilon) only makes sense over a narrow range of FP values. 1e100 and 2e100 as similarly different than 1e-100 and 2e-100 from a floating point point-of-view.

2) How small can I choose EPSILON? (The particles can come really close to each other)

To compare same-ness, use ==

3) Is there any faster / or more robust implementation to compare the position of particles?

Simply use ==


Code can compare doubles with ==, that is very useful for comparing equality, not closeness. If equality prevention is all that is needed, then if (x1 == x2 && y1 == y2) is sufficient.

The deeper issue is why "same coordinates into the list twice" a problem? IMO, that restriction is the problem. Use an algorithm that does not require that restriction.

Upvotes: 2

Related Questions