Many simulations ask one question thousands of times per step: which objects are close to this one? Testing every pair costs n² distance checks, which is fine for a hundred boids and hopeless for fifty thousand particles. This lesson pairs with 11 - Finding collisions among thousands of objects blazing fast by Ten Minute Physics, linked under Watch & read. The video covers the problem, a simple solution, the idea, the data structure and an implementation. You build the lookup in NumPy: cells, buckets, a counting-sorted table, a radius query and a list of every close pair.
Cut space into square cells (cubes in 3D) whose side h is the largest distance you ask about. A point's cell is floor(x / h) on every axis. If q is within h of p, then q differs from p by at most h on each axis, which is at most one cell width. So q sits in p's own cell or one of the cells touching it: 9 cells in 2D, 27 in 3D. That is the whole idea. Everything else is bookkeeping.
Cell coordinates are unbounded integers, so you cannot index an array with them. Hash them. Multiply each coordinate by a fixed large prime, one prime per axis (73856093, 19349663, 83492791), combine the products with XOR, and take the remainder by the table size. The result is a bucket in [0, table_size). Two different cells may land in the same bucket. That is called a collision, and it is harmless as long as you always check the true distance before you report a neighbor.
To store the points, skip lists of lists. Count the points in each bucket, take a running total of the counts to get start (one entry more than there are buckets), then give each point the next free slot of its bucket in an array order. This is a counting sort. The points of bucket b are order[start[b]:start[b + 1]]: two flat arrays, no per-bucket allocation.
Take those six points. Their cells are A (0, 0), B (1, 0), C (-1, 0), D (2, 2), E (-1, -2) and F (1, 0). With 7 buckets they hash to 0, 3, 4, 5, 0 and 3. A and E share bucket 0 although their cells are two rows apart. Counting sort gives start = [0, 2, 2, 2, 4, 5, 6, 6] and order = [0, 4, 1, 5, 2, 3], where the points are numbered A = 0 up to F = 5.
import math
for x in (2.5, 0.5, -0.5, -2.5):
print(x, math.floor(x), int(x))import numpy as np
pts = np.array([[0.3, 0.4], [1.2, 0.5], [-0.4, 0.2], [2.6, 2.7], [-0.6, -1.3], [1.9, 0.9]])
cells = np.floor(pts).astype(int)
bucket = (cells[:, 0] * 73856093 ^ cells[:, 1] * 19349663) % 7
start = np.concatenate([[0], np.cumsum(np.bincount(bucket, minlength=7))])
print(bucket.tolist(), start.tolist(), np.argsort(bucket, kind="stable").tolist())Now query around A with radius 1. The nine cells around A hash to buckets 6, 4, 6, 3, 0, 4, 6, 3 and 6, which is only four different buckets: 0, 3, 4 and 6. Bucket 0 holds A and E, bucket 3 holds B and F, bucket 4 holds C, bucket 6 is empty. Five candidates, then the real distances: A is 0 away, B 0.91, C 0.73, F 1.68 and E 1.93. The answer is the sorted indices [0, 1, 2].
Four mistakes cover most broken versions of this code.
- Turning a float into an integer with
intorastypeinstead offloor. Both cut toward zero, so -0.5 becomes cell 0 and the cells around the origin merge into one double-width cell. Neighbor answers stay correct, because merging only adds candidates, so a test that looks only at results never notices. Check the cell numbers of negative points directly. - Visiting the same bucket twice. When two of the nine cells hash to one bucket, scanning both returns every point of that bucket twice. With a large table this is rare, so it hides until a small table or an unlucky layout shows it. Take the distinct buckets first.
- Treating the cells as the answer. Points in neighboring cells can be almost 2h away on one axis. The cells only choose candidates; the squared-distance test decides.
- Asking for a radius larger than h. The nine cells no longer cover the circle, and points are silently missed, so raise ValueError instead.
The tests compare every query with a brute-force distance check over all points, in 2D and 3D, with negative coordinates and tables of 1, 2, 5 and 16 buckets, where collisions are constant. They also check that start and order form a valid, stable counting sort, and that all_pairs matches a double loop.
That is evidence of correctness, not of speed. With 2000 random points in a 40 by 40 square and h = 1, a run of the reference averaged 17.4 candidates per query instead of 2000. The tests use tiny inputs, so they say nothing about how this behaves when many points crowd into a few cells, or when h is far from the distance you care about.