简体   繁体   English

比较c ++中的双打

[英]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? 但我的坐标是double ,我想我应该用epsilon做,所以是fabs ((x - center_x)^2 + (y - center_y)^2 - radius^2 ) < EPS更好?

You don't need the epsilon when you're comparing using < or > , those are perfectly fine. 当您使用<>进行比较时,您不需要epsilon,这些都非常好。 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) . 另请注意, ^pow(a, b)

You cannot use '^' in C++ for this purpose. 你不能在C ++中使用'^'来达到这个目的。 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 . 代替(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. Naiive有序不等式比较通常最适合测试浮点值是否在阈值的一侧。

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. 请注意,当输入值的大小不同时,基于恒定epsilon的误差补偿无效。

No. As others mentioned, the operator ^ in C is bitwise exclusive or, not power. 不。正如其他人所提到的,C中的运算符^是按位排他,或者不是幂。 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. 意味着(x,y) 位于的圆周上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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