如果你有一个圆心(center_x, center_y)和半径为半径的圆,如何测试一个坐标为(x, y)的给定点是否在圆内?


当前回答

求圆心到所给点之间的距离。如果它们之间的距离小于半径,则该点在圆内。 如果它们之间的距离等于圆的半径,那么这个点就在圆的周长上。 如果距离大于半径,则该点在圆外。

int d = r^2 - ((center_x-x)^2 + (center_y-y)^2);

if(d>0)
  print("inside");
else if(d==0)
  print("on the circumference");
else
  print("outside");

其他回答

这与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是点的坐标。

iOS 15,接受的答案写在Swift 5.5

func isInRectangle(center: CGPoint, radius: Double, point: CGPoint) -> Bool
{
    return point.x >= center.x - radius && point.x <= center.x + radius &&
    point.y >= center.y - radius && point.y <= center.y + radius
}

//test if coordinate (x, y) is within a radius from coordinate (center_x, center_y)
func isPointInCircle(center: CGPoint,
                     radius:Double, point: CGPoint) -> Bool
{
    if(isInRectangle(center: center, radius: radius, point: point))
    {
        var dx:Double = center.x - point.x
        var dy:Double = center.y - point.y
        dx *= dx
        dy *= dy
        let distanceSquared:Double = dx + dy
        let radiusSquared:Double = radius * radius
        return distanceSquared <= radiusSquared
    }
    return false
}

如上所述,使用欧几里得距离。

from math import hypot

def in_radius(c_x, c_y, r, x, y):
    return math.hypot(c_x-x, c_y-y) <= r

你可以用毕达哥拉斯来测量你的点到中心之间的距离,看看它是否低于半径:

def in_circle(center_x, center_y, radius, x, y):
    dist = math.sqrt((center_x - x) ** 2 + (center_y - y) ** 2)
    return dist <= radius

编辑(向保罗致敬)

实际上,取平方根通常比取平方根便宜得多,因为我们只对排序感兴趣,我们当然可以放弃取平方根:

def in_circle(center_x, center_y, radius, x, y):
    square_dist = (center_x - x) ** 2 + (center_y - y) ** 2
    return square_dist <= radius ** 2

此外,Jason注意到<=应该被<取代,根据用法,这实际上可能是有意义的,尽管我认为这在严格的数学意义上是不正确的。我接受纠正。

我使用下面的代码为初学者像我一样:)。

公共类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");
    } 
}



    }
}}