Python 与 SQLite 最近点对实战:精确距离平方、重复坐标与确定性平局
导读:用九段独立 Python 程序完成整数二维最近点对:从 SQLite 入库、精确平方距离与平局规则,到分治搜索、事务落库和独立暴力核验。
配图说明:本文配图为 AI 生成的最近点对与数据库概念插画,不是坐标比例准确的计算结果图。
一、先约定点的身份,再把整数安全地存进去
仓储货位、像素特征或离散传感器位置常常以二维整数点保存。问题看似只是找两点间最短的距离,真正影响线上结果的却是身份与边界:相同坐标能否代表不同记录?四条边一样长时选哪条?没有点时返回什么?本文把这些规则放在算法前面,并让 SQLite 负责数据保存,让 Python 负责精确几何计算。
一条记录固定为三元组(id、x、y),id 是唯一整数身份,两个不同 id 即使坐标相同也仍然构成合法点对。候选结果固定为(距离平方、较小 id、较大 id),按这个三元组的字典序取最小值。因而先比较距离,距离相同时比较较小 id,再比较较大 id。空集或单点返回 None,不能拿零距离冒充没有结果;输入重复 id 则直接报错。
本文全部九段程序都可以各自保存成一个 Python 文件独立运行,不要求预先执行其他段落。示例以 Python 3.12 及以上为目标,只使用标准库。实测环境为 Python 3.12.14。每段运行命令采用 python -X dev -W error 文件名.py;这会打开开发模式,并把一般警告提升为错误。代码中的 SQL 字符串必须保留普通半角引号,不要替换成排版引号。
SQLite 的 INTEGER 列有类型亲和性,列名写着整数并不等于拒绝一切其他输入。下面同时检查 Python 入参和数据库保存后的存储类型。数据库检查约束针对转换后的值,不能证明原始输入不是字符串或布尔值,所以入口校验仍有必要。这里限制三列均在有符号六十四位范围内,使用参数绑定,事务负责一次导入的完整性。相关行为见 SQLite 官方类型说明。
独立示例 1
import sqlite3
from contextlib import closing
rows = [(8, 0, 0), (3, 3, 0), (12, 3, 2), (5, 8, 8)]
limit = 1 << 63
if any(type(v) is not int or not -limit <= v < limit
for row in rows for v in row):
raise ValueError('all fields must be signed 64-bit integers')
if len({row[0] for row in rows}) != len(rows):
raise ValueError('duplicate id')
with closing(sqlite3.connect(':memory:', autocommit=True)) as con:
con.execute("""CREATE TABLE point (
id INTEGER PRIMARY KEY,
x INTEGER NOT NULL CHECK(typeof(x) = 'integer'),
y INTEGER NOT NULL CHECK(typeof(y) = 'integer')
)""")
con.execute('BEGIN')
try:
con.executemany('INSERT INTO point VALUES (?, ?, ?)', rows)
con.execute('COMMIT')
except BaseException:
con.execute('ROLLBACK')
raise
points = con.execute('SELECT id, x, y FROM point ORDER BY id').fetchall()
assert points == [(3, 3, 0), (5, 8, 8), (8, 0, 0), (12, 3, 2)]
print(points)运行输出:
[(3, 3, 0), (5, 8, 8), (8, 0, 0), (12, 3, 2)]
二、比较距离平方,避免把精确结果交给浮点数
欧氏距离的平方等于横坐标差的平方加纵坐标差的平方。对非负数而言,开平方不会改变大小关系,因此寻找最近点对时完全没必要调用平方根。这样既减少计算步骤,也使平局判断直接成为整数相等判断,不需要人为制定容差。
更关键的是运算发生在哪一层。两个坐标都能装进六十四位整数,并不意味着坐标差、乘积和总和也能装进去。取两个坐标轴的最小值和最大值,距离平方最多需要一百二十九个二进制位。Python 整数支持任意精度;SQLite 普通算术发生整数溢出时会采用浮点计算,因此不能把 SQL 自连接里的一条算式当作任意精度距离引擎。这个区别由 Python 数值类型文档和 SQLite 表达式文档说明。
下面故意构造极端坐标,并验证 SQL 乘积已经变成 REAL。Python 算出的完整平方距离则转换为十进制字符串,保存到 TEXT 列。读取后用 int 恢复,不通过 float 中转。这个编码约定也适合向前端发送结果,避免接收端把长整数当成普通双精度数后悄悄丢失低位。
独立示例 2
import sqlite3
from contextlib import closing
lo, hi = -(1 << 63), (1 << 63) - 1
exact = (hi - lo) ** 2 + (hi - lo) ** 2
assert exact.bit_length() == 129
with closing(sqlite3.connect(':memory:', autocommit=True)) as con:
kind, approximate = con.execute(
'SELECT typeof((? - ?) * (? - ?)), (? - ?) * (? - ?)',
(hi, lo, hi, lo, hi, lo, hi, lo)
).fetchone()
assert kind == 'real'
assert int(approximate) != (hi - lo) ** 2
con.execute('CREATE TABLE result (distance_squared TEXT NOT NULL)')
con.execute('INSERT INTO result VALUES (?)', (str(exact),))
stored = con.execute('SELECT distance_squared FROM result').fetchone()[0]
assert int(stored) == exact
print('SQL arithmetic type:', kind)
print('exact squared distance:', stored)运行输出:
SQL arithmetic type: real exact squared distance: 680564733841876926852962238568698216450
三、先写一个可信的小规模暴力参考实现
优化算法最需要的搭档,是一份结构足够简单、能独立验证结果的参考程序。这里枚举所有无序点对,分别计算距离,然后比较完整候选三元组。先按 id 排序,保证组合中的第一个 id 小于第二个 id;这条路径不复用后面分治函数的距离辅助函数或筛选逻辑,能减少两个实现一起写错的机会。
四个正方形顶点会产生多个距离为一的点对。示例故意把 id 顺序打乱,最终选择(2、30),而不是碰巧先读到的两个点。这同时说明数据库读取顺序不应该成为业务规则。参考实现假设输入已经经过契约校验,空集和单点则自然产生 None。它需要二次方数量的比较,适合小数据、单元测试与回归样本,不能因为代码短就用来处理任意规模的数据。
独立示例 3
from itertools import combinations def brute_force(points): rows = sorted(points, key=lambda p: p[0]) best = None for left, right in combinations(rows, 2): distance = sum((left[k] - right[k]) ** 2 for k in (1, 2)) candidate = (distance, left[0], right[0]) if best is None or candidate < best: best = candidate return best points = [(90, 0, 0), (7, 1, 0), (2, 0, 1), (30, 1, 1)] assert brute_force([]) is None assert brute_force([(4, 2, 8)]) is None assert brute_force(points) == (1, 2, 30) assert brute_force([(9, 4, 4), (2, 4, 4), (7, 4, 4)]) == (0, 2, 7) print(brute_force(points))
运行输出:
(1, 2, 30)
四、用分治缩小候选范围,并完整保留平局
正式实现先按横坐标、纵坐标、id 排序,然后按数组位置对半切分。使用位置切分非常重要:同一横坐标上的点可以很多,如果仅按横坐标小于某值来递归,可能出现一边没有点、另一边规模不缩小的问题。位置切分保证每次真正减半,递归基例只会收到二个或三个点。
在进入分治之前,算法先扫描相邻的相同坐标。排序已把每组的 id 排好,该组前两个 id 给出组内最小零距离点对;对所有重复组继续比较,才能选出全局 id 最小的零距离结果。不能发现第一组重复点就立刻返回,因为它只是坐标顺序最靠前,不一定是身份顺序最靠前。这一步也避免零距离造成条带里大量重复点的退化比较。
递归分别求出左右最优结果,较优者的距离平方就是当前上界。一个可能胜出的跨边界点对,两端到分界线的水平距离都不会超过这个上界对应的距离,所以只需要收集条带内的点。条带按纵坐标排序后,纵向距离已经超过上界的后续点可以全部停止检查。代码全程比较平方,不实际计算上界的平方根。
注意两个不同的比较符号:收集条带使用小于等于,纵向剪枝使用严格大于。恰好等距的候选可能有更小的 id,不能按大于等于提前排除。实现也没有机械地截取后面七个点,而是按实际纵向界限停止,这让包含边界的平局规则更容易审计。在没有重复坐标时,左右半区各自的最短距离提供了装箱约束,有限大小的条带窗口只能容纳常数数量的候选点。
这份教学实现每一层都重新排序条带,因此按固定大小整数运算计,最坏时间复杂度为 O(n log² n),不是经典优化版本的 O(n log n)。如果递归同步维护纵坐标有序列表,可以进一步省掉重复排序,但会增加合并逻辑。这里选择较易验证的版本,额外存储为 O(n),并且仍然要把整个输入装入内存。对超长任意精度整数还需额外计入大整数运算成本;来自六十四位坐标表的运算位数则有明确上界。
独立示例 4
def closest_pair(points):
"""Return (distance_squared, smaller_id, larger_id), or None."""
rows = [tuple(row) for row in points]
if any(len(row) != 3 for row in rows):
raise ValueError('each point must contain id, x, y')
if any(type(value) is not int for row in rows for value in row):
raise TypeError('id, x and y must be Python integers')
if len({row[0] for row in rows}) != len(rows):
raise ValueError('point ids must be unique')
if len(rows) < 2:
return None
ordered = sorted(rows, key=lambda p: (p[1], p[2], p[0]))
zero = None
for a, b in zip(ordered, ordered[1:]):
if a[1:] == b[1:]:
candidate = (0, min(a[0], b[0]), max(a[0], b[0]))
zero = candidate if zero is None else min(zero, candidate)
if zero is not None:
return zero
def score(a, b):
dx, dy = a[1] - b[1], a[2] - b[2]
return (dx * dx + dy * dy, min(a[0], b[0]), max(a[0], b[0]))
def solve(items):
size = len(items)
if size <= 3:
return min(score(items[i], items[j])
for i in range(size) for j in range(i + 1, size))
middle = size // 2
split_x = items[middle][1]
best = min(solve(items[:middle]), solve(items[middle:]))
bound = best[0]
strip = [p for p in items if (p[1] - split_x) ** 2 <= bound]
strip.sort(key=lambda p: (p[2], p[1], p[0]))
for i, a in enumerate(strip):
j = i + 1
while j < len(strip):
b = strip[j]
if (b[2] - a[2]) ** 2 > best[0]:
break
best = min(best, score(a, b))
j += 1
return best
return solve(ordered)
points = [(90, 0, 0), (7, 1, 0), (2, 0, 1), (30, 1, 1)]
assert closest_pair(points) == (1, 2, 30)
assert closest_pair(list(reversed(points))) == (1, 2, 30)
print(closest_pair(points))运行输出:
(1, 2, 30)
五、把重复坐标与没有点对区分开
重复坐标不应在导入时随手去重。两条设备记录位置相同可能恰好就是需要发现的异常;删去一条会改变问题的语义。只有业务已经明确认为坐标就是身份时,才应先做独立的数据归并,而不是偷偷修改最近点对算法。
下面是一段可独立运行的诊断预检,输入同样假定已校验。它把结果分成三种状态:点不足两个、已经存在零距离最优点对、还需要继续搜索。最后一种状态中的 None 不是最终答案,只是尚未计算。示例让坐标靠后的重复组拥有更小 id,验证算法确实比较全部重复组。实际核心函数已经包含这项逻辑,不需要在调用之前额外做一遍预检;单独列出它,是为了让日志和排错时能说清楚数据为什么返回零。
独立示例 5
from collections import defaultdict
# Diagnostic preflight for already validated integer rows.
def preflight(points):
rows = list(points)
if len(rows) < 2:
return 'no_pair', None
groups = defaultdict(list)
for pid, x, y in rows:
groups[x, y].append(pid)
zeros = []
for ids in groups.values():
if len(ids) >= 2:
first, second = sorted(ids)[:2]
zeros.append((0, first, second))
if zeros:
return 'zero_pair', min(zeros)
return 'needs_search', None
points = [(80, 0, 0), (9, 0, 0), (20, 0, 0),
(7, 5, 5), (2, 5, 5), (3, 5, 5)]
assert preflight(points) == ('zero_pair', (0, 2, 3))
assert preflight([]) == ('no_pair', None)
assert preflight([(1, 0, 0)]) == ('no_pair', None)
assert preflight([(1, 0, 0), (2, 1, 0)]) == ('needs_search', None)
print(preflight(points))
print(preflight([]))运行输出:
('zero_pair', (0, 2, 3))
('no_pair', None)六、小表也可以用 SQL 自连接做交叉核验
想在数据库侧核对几十条样本时,可以注册一个 Python 标量函数,让它接收原始整数坐标并返回平方距离的十进制字符串。SQL 只负责列出 id 较小到 id 较大的无序组合。不要把巨大的 Python 整数直接作为 SQLite 函数返回值,否则仍会遇到 SQLite 整数容量边界。
字符串排序也有陷阱:普通字典序会把十放在二前面。由于这里输出始终是没有前导零的非负十进制字符串,可以先按字符长度,再按 BINARY 字典序排序,最后按两个 id 排序。这个排序等价于比较精确的非负整数值。空表或单点时 fetchone 返回 None;示例的小表采用固定合法输入,生产入口仍须保留前面的类型检查。
注册函数的 deterministic 标记表示相同参数产生相同输出,不代表查询变成空间索引搜索。自连接仍然列举二次方数量的组合,数据库优化器还可能重复计算表达式,因此它是小样本核验工具。函数参数和返回类型的规则见 sqlite3 官方函数接口。
独立示例 6
import sqlite3
from contextlib import closing
def squared_text(ax, ay, bx, by):
return str((ax - bx) ** 2 + (ay - by) ** 2)
rows = [(90, 0, 0), (7, 1, 0), (2, 0, 1), (30, 1, 1)]
with closing(sqlite3.connect(':memory:', autocommit=True)) as con:
con.execute('CREATE TABLE point (id INTEGER PRIMARY KEY, x INTEGER, y INTEGER)')
con.executemany('INSERT INTO point VALUES (?, ?, ?)', rows)
con.create_function('squared_text', 4, squared_text, deterministic=True)
answer = con.execute("""
WITH pairs AS (
SELECT a.id AS id1, b.id AS id2,
squared_text(a.x, a.y, b.x, b.y) AS d2
FROM point AS a JOIN point AS b ON a.id < b.id
)
SELECT d2, id1, id2 FROM pairs
ORDER BY length(d2), d2 COLLATE BINARY, id1, id2
LIMIT 1
""").fetchone()
assert answer == ('1', 2, 30)
print(answer)运行输出:
('1', 2, 30)七、把读取、计算与结果写入放在同一事务里
真正接入业务时,正确的几何函数只解决了一半问题。读取一批点之后,如果另一个连接修改了这批数据,最终保存的结果可能已经不再描述当前表。下面给出独立、可直接运行的完整流水线,重复包含核心函数,不依赖第四段文件。批次字段隔离不同数据集,结果同时保存点数、状态、规范化点对和精确距离文本。
程序显式启用 autocommit,并用 SQL 的 BEGIN IMMEDIATE、COMMIT 和 ROLLBACK 管理每次计算事务。这里必须用 SQL 提交,不能混用 autocommit=True 下不起作用的连接 commit 方法。写事务在读取前就开始,避免计算过程中其他写事务改变源数据;失败时回滚,关闭连接则由 closing 保证。这些事务语义可查阅 SQLite 官方事务说明以及 Python 事务控制说明。
这个策略适合计算耗时受控的小中型离线批次,但会占用写事务,不应在繁忙在线库里长时间持有。更大的任务可以把源批次设计成不可变版本,在短事务中读取版本快照,再把结果绑定到该版本。单独记录行数不够:相同条数的数据也可能已经换了坐标。示例只展示一次计算,结果表的批次主键使重复执行报错;若要做覆盖更新,需先明确版本及幂等语义。
空批次和单点批次都写入 no_pair,点数则保留区别。有效结果使用 ok;重复坐标得到的距离字符串是零,仍属于有效结果。这样展示层不必猜测一个零到底代表重合、缺失还是失败。程序没有替应用定义单位,输入若以毫米计,距离平方就是平方毫米;转换为可读距离应在展示层明确标注单位和近似性。
独立示例 7
import sqlite3
from contextlib import closing
def closest_pair(points):
"""Return (distance_squared, smaller_id, larger_id), or None."""
rows = [tuple(row) for row in points]
if any(len(row) != 3 for row in rows):
raise ValueError('each point must contain id, x, y')
if any(type(value) is not int for row in rows for value in row):
raise TypeError('id, x and y must be Python integers')
if len({row[0] for row in rows}) != len(rows):
raise ValueError('point ids must be unique')
if len(rows) < 2:
return None
ordered = sorted(rows, key=lambda p: (p[1], p[2], p[0]))
zero = None
for a, b in zip(ordered, ordered[1:]):
if a[1:] == b[1:]:
candidate = (0, min(a[0], b[0]), max(a[0], b[0]))
zero = candidate if zero is None else min(zero, candidate)
if zero is not None:
return zero
def score(a, b):
dx, dy = a[1] - b[1], a[2] - b[2]
return (dx * dx + dy * dy, min(a[0], b[0]), max(a[0], b[0]))
def solve(items):
size = len(items)
if size <= 3:
return min(score(items[i], items[j])
for i in range(size) for j in range(i + 1, size))
middle = size // 2
split_x = items[middle][1]
best = min(solve(items[:middle]), solve(items[middle:]))
bound = best[0]
strip = [p for p in items if (p[1] - split_x) ** 2 <= bound]
strip.sort(key=lambda p: (p[2], p[1], p[0]))
for i, a in enumerate(strip):
j = i + 1
while j < len(strip):
b = strip[j]
if (b[2] - a[2]) ** 2 > best[0]:
break
best = min(best, score(a, b))
j += 1
return best
return solve(ordered)
with closing(sqlite3.connect(':memory:', autocommit=True)) as con:
con.execute("""CREATE TABLE point (
batch TEXT NOT NULL, id INTEGER NOT NULL,
x INTEGER NOT NULL CHECK(typeof(x) = 'integer'),
y INTEGER NOT NULL CHECK(typeof(y) = 'integer'),
PRIMARY KEY(batch, id), CHECK(typeof(id) = 'integer')
)""")
con.execute("""CREATE TABLE result (
batch TEXT PRIMARY KEY, point_count INTEGER NOT NULL,
status TEXT NOT NULL, id1 INTEGER, id2 INTEGER,
distance_squared TEXT
)""")
con.executemany('INSERT INTO point VALUES (?, ?, ?, ?)', [
('demo', 8, 0, 0), ('demo', 3, 3, 0),
('demo', 12, 3, 2), ('demo', 5, 8, 8),
('single', 1, 9, 9)
])
for batch in ('demo', 'empty', 'single'):
con.execute('BEGIN IMMEDIATE')
try:
points = con.execute(
'SELECT id, x, y FROM point WHERE batch = ?', (batch,)
).fetchall()
answer = closest_pair(points)
if answer is None:
record = (batch, len(points), 'no_pair', None, None, None)
else:
d2, id1, id2 = answer
record = (batch, len(points), 'ok', id1, id2, str(d2))
con.execute('INSERT INTO result VALUES (?, ?, ?, ?, ?, ?)', record)
con.execute('COMMIT')
except BaseException:
if con.in_transaction:
con.execute('ROLLBACK')
raise
result = con.execute('SELECT * FROM result ORDER BY batch').fetchall()
assert result == [
('demo', 4, 'ok', 3, 12, '4'),
('empty', 0, 'no_pair', None, None, None),
('single', 1, 'no_pair', None, None, None)
]
for row in result:
print(row)运行输出:
('demo', 4, 'ok', 3, 12, '4')
('empty', 0, 'no_pair', None, None, None)
('single', 1, 'no_pair', None, None, None)八、用差分测试和不变性测试寻找隐藏反例
通过一个正方形远远不能证明分治写对了。这里把核心函数和独立暴力参考实现放进同一份可运行程序,验证固定边界样例、小网格的全部子集,以及固定随机种子的多组输入。随机数据分别强调重复坐标、同一竖线、六十四位极值附近;id 则刻意包含负数和非连续值,避免把输入序号误当作真实身份。
每一组都比较完整三元组,不仅比较距离。随后再做三种变换:逆转输入顺序、整体平移,以及交换坐标轴并反射。三种操作都不改变距离及点对身份,因此结果必须完全相同。平移后的部分坐标可能超出数据库整数范围,这是有意测试纯 Python 函数的任意精度能力;这些变换数据不会再次写入 SQLite。
最后检查重复 id、布尔值、浮点数、字段数不对和字符串坐标都会被拒绝。这里使用 type(value) is int 而不是 isinstance,是因为 Python 的 bool 属于 int 子类,但业务点位不应悄悄接受 True 作为身份。断言是测试工具,不是安全校验机制;核心函数真正拒绝非法输入的逻辑使用显式异常,因此即使关闭断言也不会失去入口校验。
独立示例 8
import random
from itertools import combinations
def closest_pair(points):
"""Return (distance_squared, smaller_id, larger_id), or None."""
rows = [tuple(row) for row in points]
if any(len(row) != 3 for row in rows):
raise ValueError('each point must contain id, x, y')
if any(type(value) is not int for row in rows for value in row):
raise TypeError('id, x and y must be Python integers')
if len({row[0] for row in rows}) != len(rows):
raise ValueError('point ids must be unique')
if len(rows) < 2:
return None
ordered = sorted(rows, key=lambda p: (p[1], p[2], p[0]))
zero = None
for a, b in zip(ordered, ordered[1:]):
if a[1:] == b[1:]:
candidate = (0, min(a[0], b[0]), max(a[0], b[0]))
zero = candidate if zero is None else min(zero, candidate)
if zero is not None:
return zero
def score(a, b):
dx, dy = a[1] - b[1], a[2] - b[2]
return (dx * dx + dy * dy, min(a[0], b[0]), max(a[0], b[0]))
def solve(items):
size = len(items)
if size <= 3:
return min(score(items[i], items[j])
for i in range(size) for j in range(i + 1, size))
middle = size // 2
split_x = items[middle][1]
best = min(solve(items[:middle]), solve(items[middle:]))
bound = best[0]
strip = [p for p in items if (p[1] - split_x) ** 2 <= bound]
strip.sort(key=lambda p: (p[2], p[1], p[0]))
for i, a in enumerate(strip):
j = i + 1
while j < len(strip):
b = strip[j]
if (b[2] - a[2]) ** 2 > best[0]:
break
best = min(best, score(a, b))
j += 1
return best
return solve(ordered)
from itertools import combinations
def brute_force(points):
rows = sorted(points, key=lambda p: p[0])
best = None
for left, right in combinations(rows, 2):
distance = sum((left[k] - right[k]) ** 2 for k in (1, 2))
candidate = (distance, left[0], right[0])
if best is None or candidate < best:
best = candidate
return best
rng = random.Random(20261019)
lo, hi = -(1 << 63), (1 << 63) - 1
cases = [[], [(1, 0, 0)], [(9, 0, 0), (2, 0, 0), (7, 0, 0)],
[(1, lo, lo), (2, hi, hi)],
[(50, 0, 0), (1, 0, 1), (2, 1, 1), (60, 1, 0)],
[(8, 0, 0), (3, 0, 2), (7, 0, 4), (1, 0, 6)]]
grid = [(50 - 3 * i, i % 3, i // 3) for i in range(9)]
for count in range(10):
cases.extend(list(group) for group in combinations(grid, count))
for index in range(2500):
count = rng.randrange(56)
ids = rng.sample(range(-2000, 2001), count)
if index % 3 == 0:
coords = [(rng.randrange(-4, 5), rng.randrange(-4, 5)) for _ in ids]
elif index % 3 == 1:
coords = [(0, rng.randrange(-1000, 1001)) for _ in ids]
else:
choices = [lo, lo + 1, -1, 0, 1, hi - 1, hi]
coords = [(rng.choice(choices), rng.choice(choices)) for _ in ids]
cases.append([(pid, x, y) for pid, (x, y) in zip(ids, coords)])
invariance_checks = 0
for points in cases:
expected = brute_force(points)
assert closest_pair(points) == expected, points
variants = [list(reversed(points)),
[(pid, x + 123, y - 456) for pid, x, y in points],
[(pid, -y, x) for pid, x, y in points]]
for variant in variants:
assert closest_pair(variant) == expected, variant
invariance_checks += 1
invalid = [[(1, 0, 0), (1, 2, 3)], [(True, 0, 0)],
[(1, 1.0, 0)], [(1, 0)], [(1, '0', 0)]]
for points in invalid:
try:
closest_pair(points)
except (TypeError, ValueError):
pass
else:
raise AssertionError('invalid input was accepted')
print('verified:', len(cases), 'cases,', invariance_checks,
'invariance checks,', len(invalid), 'invalid inputs')运行输出:
verified: 3018 cases, 9054 invariance checks, 5 invalid inputs
九、数据太大时,不能只取每块的局部答案
一个常见的错误优化是用 fetchmany 分块取出点,分别求最近点对,最后在各块结果里取最小。这样只保留块内候选,跨块的两个最近点完全没有机会出现。下面四个点就能给出反例:两块的内部间距都是一百,但两块边界之间只隔一个单位。
给横纵坐标建普通索引也不会自动补齐这些跨块候选。索引可以帮助按批次过滤、排序或读取,能否正确缩减几何候选则需要额外证明。若全量点无法放进内存,应选择具有明确边界合并规则的外存算法、分区加完整邻域搜索,或者交给具有合适空间检索能力的系统;不能把分页本身当成正确性保障。
上线前还应固定坐标的含义:本文处理平面整数坐标和欧氏距离,不适用于直接比较经纬度,也没有处理不同坐标轴尺度不一致的情况。任何单位归一化或坐标投影都应在导入前完成并记录版本。数值精确并不自动意味着业务度量正确。
最后回看整个流程:唯一 id 确定身份,整数平方确定精确大小,完整三元组确定平局,重复坐标预检确定零距离语义,事务与批次版本确定结果属于哪份输入,独立参考实现确定优化没有改变答案。把这些约束写进程序和测试,比只展示一个最快算法名称更能减少后续维护时的误判。
独立示例 9
from itertools import combinations
def brute_force(points):
rows = sorted(points, key=lambda p: p[0])
best = None
for left, right in combinations(rows, 2):
distance = sum((left[k] - right[k]) ** 2 for k in (1, 2))
candidate = (distance, left[0], right[0])
if best is None or candidate < best:
best = candidate
return best
points = [(1, 0, 0), (2, 100, 0), (3, 101, 0), (4, 201, 0)]
chunks = [points[:2], points[2:]]
local_answer = min(brute_force(chunk) for chunk in chunks)
global_answer = brute_force(points)
assert local_answer == (10000, 1, 2)
assert global_answer == (1, 2, 3)
assert local_answer != global_answer
print('chunk-only:', local_answer)
print('global:', global_answer)运行输出:
chunk-only: (10000, 1, 2) global: (1, 2, 3)


