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


当前回答

下面的方程是一个表达式,测试一个点是否在一个给定的圆内,其中xP和yP是点的坐标,xC和yC是圆心的坐标,R是给定圆的半径。

如果上述表达式为真,则该点在圆内。

下面是一个c#实现的示例:

    public static bool IsWithinCircle(PointF pC, Point pP, Single fRadius){
        return Distance(pC, pP) <= fRadius;
    }

    public static Single Distance(PointF p1, PointF p2){
        Single dX = p1.X - p2.X;
        Single dY = p1.Y - p2.Y;
        Single multi = dX * dX + dY * dY;
        Single dist = (Single)Math.Round((Single)Math.Sqrt(multi), 3);

        return (Single)dist;
    }

其他回答

如前所述,为了显示点是否在圆中,我们可以使用下面的方法

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)

一般来说,x和y必须满足(x - center_x)²+ (y - center_y)²< radius²。

请注意,满足上式<的点被==替换为圆上的点,满足上式<的点被>替换为圆外的点。

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
}

计算距离

D = Math.Sqrt(Math.Pow(center_x - x, 2) + Math.Pow(center_y - y, 2))
return D <= radius

这是用c#写的……转换为python中使用…

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

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