4

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?

Gigata
  • 81
  • 1
  • 6
  • 2
    related: http://stackoverflow.com/questions/17333/most-effective-way-for-float-and-double-comparison – NathanOliver Jun 28 '16 at 14:20
  • 2
    You seem to be under the impression that `^2` raises something to the second power. That's not the case. In C++ `^` is "bitwise XOR" - http://en.cppreference.com/w/cpp/language/operator_arithmetic#Bitwise_logic_operators – Jesper Juhl Jun 28 '16 at 14:36

4 Answers4

5

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

lorro
  • 10,687
  • 23
  • 36
  • Thank you, I knew that I should use `EPS` with `==` but always been wondering about `<` and `>`. This made it clear to me! P.S I know I can't use `^` as pow :P – Gigata Jun 28 '16 at 14:26
  • either case is better to do `x*x + y*y` than `pow(x, 2) + pow(y, 2)`, which only does a multiplation avoiding complex logarithm calculations. – Luis Colorado Jun 30 '16 at 06:27
4

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.

Shiro
  • 2,610
  • 2
  • 20
  • 36
4

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326
4

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.

user31264
  • 6,557
  • 3
  • 26
  • 40