简体   繁体   中英

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?

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

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM