Python all points on circle given radius and center

aze45sq6d picture aze45sq6d · Mar 29, 2018 · Viewed 11.1k times · Source

I wrote this function:

def get_x_y_co(circles):
    xc = circles[0] #x-co of circle (center)
    yc = circles[1] #y-co of circle (center)
    r = circles[2] #radius of circle
    arr=[]
    for i in range(360):
        y = yc + r*math.cos(i)
        x = xc+ r*math.cos(i)
        x=int(x)
        y=int(y)
        #Create array with all the x-co and y-co of the circle
        arr.append([x,y])
    return arr

With 'circles' being an array with [X-center, Y-center, Radius]

I would like to extract all the points with integer resolution present in the circle. Right now, I realised I am creating an array of points who are on the BORDER of the circle, but I don't have access to the points INSIDE the circle.

I thought of just reducing the radius, and iterate this for all values of the radius, until the radius is 0

But I feelthere is a much more efficient way. Any help is welcome

Answer

Maarten Fabré picture Maarten Fabré · Mar 30, 2018
from itertools import product
def points_in_circle(radius):
    for x, y in product(range(int(radius) + 1), repeat=2):
        if x**2 + y**2 <= radius**2:
            yield from set(((x, y), (x, -y), (-x, y), (-x, -y),))
list(points_in_circle(2))
[(0, 0), (0, 1), (0, -1), (0, -2), (0, 2), (1, 0), (-1, 0), (-1, 1), (1, -1), (1, 1), (-1, -1), (2, 0), (-2, 0)]

with numpy

def points_in_circle_np(radius):
    a = np.arange(radius + 1)
    for x, y in zip(*np.where(a[:,np.newaxis]**2 + a**2 <= radius**2)):
        yield from set(((x, y), (x, -y), (-x, y), (-x, -y),))

with arbitrary center

def points_in_circle_np(radius, x0=0, y0=0, ):
    x_ = np.arange(x0 - radius - 1, x0 + radius + 1, dtype=int)
    y_ = np.arange(y0 - radius - 1, y0 + radius + 1, dtype=int)
    x, y = np.where((x_[:,np.newaxis] - x0)**2 + (y_ - y0)**2 <= radius**2)
    # x, y = np.where((np.hypot((x_-x0)[:,np.newaxis], y_-y0)<= radius)) # alternative implementation
    for x, y in zip(x_[x], y_[y]):
        yield x, y