In python, if you create a circle with: newcircle = circle(center_x, center_y, radius)
How do you test if a given set of x/y coordinates are inside the circle?
In python, if you create a circle with: newcircle = circle(center_x, center_y, radius)
How do you test if a given set of x/y coordinates are inside the circle?
In general, x
and y
must satisfy (x-center_x)^2 + (y - center_y)^2 < radius^2
.
Please note that points that satisfy the above equation with <
replaced by ==
are considered the points on the circle, and the points that satisfy the above equation with <
replaced by >
are consider the exterior of the circle.
Calculate the Distance
D = Math.Sqrt(Math.Pow(center_x - x, 2) + Math.Pow(center_y - y, 2))
return D <= radius
that's in C#...convert for use in python...
You can use Pythagoras to measure the distance between your point and the centre and see if it's lower than the radius:
def in_circle(center_x, center_y, radius, x, y):
dist = math.sqrt((center_x - x) ** 2 + (center_y - y) ** 2)
return dist <= radius
EDIT (hat tip to Paul)
In practice, squaring is often much cheaper than taking the square root and since we're only interested in an ordering, we can of course forego taking the square root:
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
Also, Jason noted that <=
should be replaced by <
and depending on usage this may actually make sense even though I believe that it's not true in the strict mathematical sense. I stand corrected.
You should check whether the distance from the center of the circle to the point is smaller than the radius, i.e.
if (x-center_x)**2 + (y-center_y)**2 <= radius**2:
# inside circle
Does anyone also have a formula determining weither a x/y point is inside a pie chart part ? I'm trying to make a piechart on HTML5 canvas with mouseover/mouseclick actions.
Thank you !
Björn