Efficiently find all points within sorted 2D Numpy Array

Viewed 64

How do I efficiently find the set of points within a circle of a given radius and centre from a sorted numpy array of equally spaced points?

For example, this is my code and how I currently extract those points within the radius.

import numpy as np
n_points = 10000
x_lim = [0, 100]
y_lim = [0, 100]
x, y = np.meshgrid(np.linspace(*x_lim, n_points), np.linspace(*y_lim, n_points))
xy = np.vstack((x.flatten(), y.flatten())).T 
# Current approach
radius = 5
point = np.array([50, 35], dtype=float) 
# Indexes of those points within a circle of radius centered at point
idxs = np.linalg.norm(point - xy, axis=-1) < radius
points_within_circle = xy[idxs]

How do I do I calculate these indexes more efficiently? I imagine because the array is structured and has a set distance between each point I should be able to exploit this to eliminate most of the checks.

1 Answers

One of the most important tricks that people forget is that it is a lot faster to calculate distance**2 and compare it to radius**2, than to calculate if distance < radius. So given that it looks like you're using a center of 0, calculate x**2 + y**2, and compare to 25.

Related