如果你有一个圆心(center_x, center_y)和半径为半径的圆,如何测试一个坐标为(x, y)的给定点是否在圆内?
当前回答
下面是解决这个问题的简单java代码:
以及它背后的数学:https://math.stackexchange.com/questions/198764/how-to-know-if-a-point-is-inside-a-circle
boolean insideCircle(int[] point, int[] center, int radius) {
return (float)Math.sqrt((int)Math.pow(point[0]-center[0],2)+(int)Math.pow(point[1]-center[1],2)) <= radius;
}
其他回答
这与Jason Punyon提到的解决方案相同,但它包含伪代码示例和更多细节。写完这篇文章后,我看到了他的回答,但我不想删除我的。
我认为最容易理解的方法是先计算圆心到点的距离。我会用这个公式:
d = sqrt((circle_x - x)^2 + (circle_y - y)^2)
然后,简单地比较公式的结果,距离(d),与半径。如果距离(d)小于或等于半径(r),则该点在圆内(如果d和r相等,则在圆的边缘)。
下面是一个伪代码示例,可以很容易地转换为任何编程语言:
function is_in_circle(circle_x, circle_y, r, x, y)
{
d = sqrt((circle_x - x)^2 + (circle_y - y)^2);
return d <= r;
}
其中circle_x和circle_y是圆的中心坐标,r是圆的半径,x和y是点的坐标。
你应该检查圆心到点的距离是否小于半径
使用Python
if (x-center_x)**2 + (y-center_y)**2 <= radius**2:
# inside circle
boolean isInRectangle(double centerX, double centerY, double radius,
double x, double y)
{
return x >= centerX - radius && x <= centerX + radius &&
y >= centerY - radius && y <= centerY + radius;
}
//test if coordinate (x, y) is within a radius from coordinate (center_x, center_y)
public boolean isPointInCircle(double centerX, double centerY,
double radius, double x, double y)
{
if(isInRectangle(centerX, centerY, radius, x, y))
{
double dx = centerX - x;
double dy = centerY - y;
dx *= dx;
dy *= dy;
double distanceSquared = dx + dy;
double radiusSquared = radius * radius;
return distanceSquared <= radiusSquared;
}
return false;
}
这样效率更高,可读性更强。它避免了昂贵的平方根运算。我还添加了一个检查,以确定点是否在圆的边界矩形内。
矩形检查是不必要的,除非有许多点或许多圆。如果大多数点都在圆圈内,边框检查实际上会使事情变慢!
像往常一样,一定要考虑您的用例。
如前所述,为了显示点是否在圆中,我们可以使用下面的方法
if ((x-center_x)^2 + (y - center_y)^2 < radius^2) {
in.circle <- "True"
} else {
in.circle <- "False"
}
要用图形表示,我们可以使用:
plot(x, y, asp = 1, xlim = c(-1, 1), ylim = c(-1, 1), col = ifelse((x-center_x)^2 + (y - center_y)^2 < radius^2,'green','red'))
draw.circle(0, 0, 1, nv = 1000, border = NULL, col = NA, lty = 1, lwd = 1)
我使用下面的代码为初学者像我一样:)。
公共类incirkel {
public static void main(String[] args) {
int x;
int y;
int middelx;
int middely;
int straal; {
// Adjust the coordinates of x and y
x = -1;
y = -2;
// Adjust the coordinates of the circle
middelx = 9;
middely = 9;
straal = 10;
{
//When x,y is within the circle the message below will be printed
if ((((middelx - x) * (middelx - x))
+ ((middely - y) * (middely - y)))
< (straal * straal)) {
System.out.println("coordinaten x,y vallen binnen cirkel");
//When x,y is NOT within the circle the error message below will be printed
} else {
System.err.println("x,y coordinaten vallen helaas buiten de cirkel");
}
}
}
}}