Gigata
Gigata

Reputation: 71

Compare doubles in c++

I want to determine whether a point is inside a circle or not. So I do this :

(x - center_x)^2 + (y - center_y)^2 < radius^2

But my coordinates are double and I think I should do it with epsilon, so is fabs ((x - center_x)^2 + (y - center_y)^2 - radius^2 ) < EPS better?

Upvotes: 3

Views: 810

Answers (4)

eerorika
eerorika

Reputation: 238461

It depends.

Naiive ordered inequality comparison is usually most appropriate for testing whether a floating point value is on one side of a threshold.

Due to floating point errors, a result that should be on one side of the threshold may end up on the other side. If it is important to guarantee no false negatives, while increasing the chance of false positives, then your suggested alternative may be appropriate.

Note that constant epsilon based error compensation is not effective when the input values vary in magnitude.

Upvotes: 4

user31264
user31264

Reputation: 6737

No. As others mentioned, the operator ^ in C is bitwise exclusive or, not power. But you could use an inline function:

inline double Sqr(double x) {return x*x;}
// ...
if (Sqr(x - center_x) + Sqr(y - center_y) < Sqr(radius)) // ...

As for your question,

fabs (Sqr(x - center_x) + Sqr(y - center_y) - Sqr(radius) ) < EPS

means that (x,y) is at the circumference of the circle.

Upvotes: 4

lorro
lorro

Reputation: 10880

You don't need the epsilon when you're comparing using < or >, those are perfectly fine. You need it instead of ==. In your case, you've just added a small amount to radius, which is probably undesirable. Also note that ^ is not the same as pow(a, b).

Upvotes: 5

user6499716
user6499716

Reputation:

You cannot use '^' in C++ for this purpose. Instead of (x - center_x)^2 + (y - center_y)^2 < radius^2 do (x - center_x)*(x - center_x) + (y - center_y)*(y - center_y) < radius*radius. It is no problem for the coordinates to be double.

Upvotes: 4

Related Questions