Python + SQLite:精确有理数 Gröbner 基、Buchberger 算法与可重放证书
当一组多项式被当作约束使用时,一个常见问题是:新的表达式能否写成这些约束的多项式线性组合?这就是理想成员判定。本文把它做成一条可运行、可保存、可复核的小流水线:Python 负责有理数上的符号计算,SQLite 保存输入、环的约定和代数证书。目标不是通用计算机代数系统,而是把每一个判定结论落实到可检查的恒等式。

运行条件是带 sqlite3 的 CPython 3.10 或更新版本;本文实测环境为 Python 3.12.14。九段代码均可各自复制到新文件独立运行,只用标准库,不读取前一段生成的文件,也不需要安装符号计算包。为保证独立性,基础函数会在若干段中重复。输出中的 (a,b) 代表指数,系数字符串保留精确分数,空列表代表零。
需要先区分三个问题:理想成员、根上的取值为零、数值残差很小,并不是同一件事。本文只处理第一个。例如在理想 ⟨x²⟩ 中,x 在唯一的 x 坐标根零处消失,但 x 不属于该理想。精确除法不会使用容差,也不会把一个很小的非零分数当作零。
示例一:先固定有理数、指数与项序
本文的计算环固定为 Q[x,y],变量顺序固定为 x、y。字典键 (a,b) 表示单项式 x 的 a 次方乘 y 的 b 次方,值是有理系数;空字典表示零,多项式不保存零系数。这几个约定必须随数据一起持久化。把变量顺序交换后继续读取旧数据,会得到另一道题,不能只换一个显示标签。
lex 按指数元组从左到右比较,因此 x 大于任意 y 的正整数次幂。grlex 先比总次数,再比 lex。本篇所有算法使用 lex,示例里的另一个排序仅用于解释差别。合法项序还必须与乘法相容并且良序,随意按系数大小排序不能替代项序。这里不接收浮点输入;Fraction 从整数或有理数字符串构造,避免把二进制近似误当作原始精确数。
from fractions import Fraction as Q
def P(data):
out = {}
for e, c in data.items():
if (not isinstance(e, tuple) or len(e) != 2
or any(type(k) is not int or k < 0 for k in e)):
raise ValueError("expected two nonnegative exponents")
if type(c) not in (int, str, Q):
raise TypeError("use exact coefficients")
c = Q(c)
if c:
out[e] = c
return out
def add(p, q, scale=1):
r = dict(p)
for e, c in q.items():
r[e] = r.get(e, Q(0)) + scale * c
if not r[e]:
del r[e]
return r
def shift(p, e, c=1):
return {tuple(a + b for a, b in zip(k, e)): v * c
for k, v in p.items() if v * c}
def mul(p, q):
r = {}
for e, c in q.items():
r = add(r, shift(p, e, c))
return r
def divides(a, b):
return all(x <= y for x, y in zip(a, b))
def show(p):
return [(e, str(p[e])) for e in sorted(p, reverse=True)]
p = P({(1, 0): "1/3", (0, 2): "-2/5", (0, 0): 0})
print(show(p))
print("lex:", max(p))
print("grlex:", max(p, key=lambda e: (sum(e), e)))
print("exact:", Q("0.1") + Q("0.2") == Q("0.3"))
try:
P({(1, 0): 0.1})
except TypeError:
print("float rejected")精确输出:
[((1, 0), '1/3'), ((0, 2), '-2/5')] lex: (1, 0) grlex: (0, 2) exact: True float rejected
示例二:稀疏运算的三个不变量
加法合并同指数项,乘法把指数逐分量相加,单项式倍乘同时平移指数并缩放系数。每一步都删掉零项,且返回新字典,避免约化时意外改写保存的生成元。输出统一列出降序指数与系数字符串,故不依赖字典插入顺序,也无需写一个容易混淆负号和幂的表达式解析器。
下面用有理系数验证乘法与分配律,并检查输入未被修改。它不是随机数值代入:两个字典相同,意味着每个单项式的精确系数相同。后续证书验证采用同样的多项式恒等式检查,而不是在少数采样点上碰巧相等。
from fractions import Fraction as Q
def P(data):
out = {}
for e, c in data.items():
if (not isinstance(e, tuple) or len(e) != 2
or any(type(k) is not int or k < 0 for k in e)):
raise ValueError("expected two nonnegative exponents")
if type(c) not in (int, str, Q):
raise TypeError("use exact coefficients")
c = Q(c)
if c:
out[e] = c
return out
def add(p, q, scale=1):
r = dict(p)
for e, c in q.items():
r[e] = r.get(e, Q(0)) + scale * c
if not r[e]:
del r[e]
return r
def shift(p, e, c=1):
return {tuple(a + b for a, b in zip(k, e)): v * c
for k, v in p.items() if v * c}
def mul(p, q):
r = {}
for e, c in q.items():
r = add(r, shift(p, e, c))
return r
def divides(a, b):
return all(x <= y for x, y in zip(a, b))
def show(p):
return [(e, str(p[e])) for e in sorted(p, reverse=True)]
p = P({(1, 0): "1/2", (0, 1): "1/3"})
q = P({(1, 0): 2, (0, 1): -3})
original = dict(p)
print(show(mul(p, q)))
print("distributive:", mul(p, add(p, q)) == add(mul(p, p), mul(p, q)))
print("unchanged:", p == original)
print("zero:", show(add(p, p, -1)))精确输出:
[((2, 0), '1'), ((1, 1), '-5/6'), ((0, 2), '-1')] distributive: True unchanged: True zero: []
示例三:普通生成元的余式为什么会误导
多元除法反复选择当前首项,寻找首单项式能整除它的除式。找到后减掉合适的单项式倍数;找不到就把该项移入余式。因每次处理都使工作多项式的首单项式严格下降,合法项序保证此过程结束。商列表与余式满足输入等于各商乘除式之和再加余式,但对于任意生成元列表,余式可能随除式顺序变化。
取 f₁=x²−y、f₂=xy−1。多项式 x²y−x 明明等于 x f₂,却可能被另一种除法次序留下非零余式。因此“得到非零余式”只有在除式已验证是 Gröbner 基时,才能作为不属于理想的结论。反过来,余式为零总能给出生成元线性组合,成立不需要先满足 Gröbner 条件。
from fractions import Fraction as Q
def P(data):
out = {}
for e, c in data.items():
if (not isinstance(e, tuple) or len(e) != 2
or any(type(k) is not int or k < 0 for k in e)):
raise ValueError("expected two nonnegative exponents")
if type(c) not in (int, str, Q):
raise TypeError("use exact coefficients")
c = Q(c)
if c:
out[e] = c
return out
def add(p, q, scale=1):
r = dict(p)
for e, c in q.items():
r[e] = r.get(e, Q(0)) + scale * c
if not r[e]:
del r[e]
return r
def shift(p, e, c=1):
return {tuple(a + b for a, b in zip(k, e)): v * c
for k, v in p.items() if v * c}
def mul(p, q):
r = {}
for e, c in q.items():
r = add(r, shift(p, e, c))
return r
def divides(a, b):
return all(x <= y for x, y in zip(a, b))
def show(p):
return [(e, str(p[e])) for e in sorted(p, reverse=True)]
def divide(p, G):
if any(not g for g in G):
raise ValueError("zero divisor")
work, rem = dict(p), {}
quot = [{} for _ in G]
while work:
e = max(work) # lex, x > y
for i, g in enumerate(G):
t = max(g)
if divides(t, e):
u = tuple(a - b for a, b in zip(e, t))
c = work[e] / g[t]
quot[i] = add(quot[i], {u: c})
work = add(work, shift(g, u, c), -1)
break
else:
rem[e] = work.pop(e)
return quot, rem
F = [P({(2, 0): 1, (0, 1): -1}),
P({(1, 1): 1, (0, 0): -1})]
h = P({(2, 1): 1, (1, 0): -1})
q, r = divide(h, F)
reconstructed = dict(r)
for a, f in zip(q, F):
reconstructed = add(reconstructed, mul(a, f))
print("F order:", show(r))
print("reversed:", show(divide(h, list(reversed(F)))[1]))
print("identity:", reconstructed == h)精确输出:
F order: [((1, 0), '-1'), ((0, 2), '1')] reversed: [] identity: True
示例四:S 多项式暴露首项抵消后的缺口
首单项式的最小公倍数按指数逐分量取最大值。将两个多项式各乘到这个单项式,并除去各自的首系数,然后相减,首项就精确抵消了。结果叫 S 多项式。它检查的正是两条约化路线在同一高项处发生冲突后,能否继续汇合。
本例 S(f₁,f₂)=y f₁−x f₂=x−y²,原列表不能消去这个余式,于是我们发现需要补充一条新关系。实现保留首系数除法,不能默认输入已经首一。顺序反过来只改变 S 多项式的符号,不影响它是否能约化到零。
from fractions import Fraction as Q
def P(data):
out = {}
for e, c in data.items():
if (not isinstance(e, tuple) or len(e) != 2
or any(type(k) is not int or k < 0 for k in e)):
raise ValueError("expected two nonnegative exponents")
if type(c) not in (int, str, Q):
raise TypeError("use exact coefficients")
c = Q(c)
if c:
out[e] = c
return out
def add(p, q, scale=1):
r = dict(p)
for e, c in q.items():
r[e] = r.get(e, Q(0)) + scale * c
if not r[e]:
del r[e]
return r
def shift(p, e, c=1):
return {tuple(a + b for a, b in zip(k, e)): v * c
for k, v in p.items() if v * c}
def mul(p, q):
r = {}
for e, c in q.items():
r = add(r, shift(p, e, c))
return r
def divides(a, b):
return all(x <= y for x, y in zip(a, b))
def show(p):
return [(e, str(p[e])) for e in sorted(p, reverse=True)]
def divide(p, G):
if any(not g for g in G):
raise ValueError("zero divisor")
work, rem = dict(p), {}
quot = [{} for _ in G]
while work:
e = max(work) # lex, x > y
for i, g in enumerate(G):
t = max(g)
if divides(t, e):
u = tuple(a - b for a, b in zip(e, t))
c = work[e] / g[t]
quot[i] = add(quot[i], {u: c})
work = add(work, shift(g, u, c), -1)
break
else:
rem[e] = work.pop(e)
return quot, rem
def spol(f, g):
a, b = max(f), max(g)
lcm = tuple(max(x, y) for x, y in zip(a, b))
u = tuple(x - y for x, y in zip(lcm, a))
v = tuple(x - y for x, y in zip(lcm, b))
return add(shift(f, u, 1 / f[a]),
shift(g, v, 1 / g[b]), -1)
F = [P({(2, 0): 1, (0, 1): -1}),
P({(1, 1): 1, (0, 0): -1})]
s = spol(F[0], F[1])
print("S:", show(s))
print("remainder:", show(divide(s, F)[1]))
print("antisymmetric:", spol(F[1], F[0]) == shift(s, (0, 0), -1))精确输出:
S: [((1, 0), '1'), ((0, 2), '-1')] remainder: [((1, 0), '1'), ((0, 2), '-1')] antisymmetric: True
示例五:一个完整而朴素的 Buchberger 循环
Buchberger 判据把无限多个多项式的问题压缩为有限个生成元对:一个有限非零列表是 Gröbner 基,当且仅当每对的 S 多项式对该列表约化为零。下面维护待处理索引队列,每发现非零余式就首一化,并把新元素与所有旧元素组成的新对加入队列。绝不能只检查初始列表中的那些对。
原生成元保留在列表中,新元素属于原理想,所以理想不变;新增余式的首单项式不能被已有首单项式整除,因此首单项式理想严格扩大。多项式环的 Noether 性保证这种扩张不能无限继续。这解释理论终止,不代表实际计算便宜。为防止误把教学程序用于大任务,代码设置处理对数上限,触发时抛错,不把不完整列表冒充答案。
得到的四个多项式是 Gröbner 基,但不是约化 Gröbner 基。后两项 x−y²、y³−1 已足够生成同一理想;示例保留冗余项以便观察补全过程。完整性由最后重新检查全部 S 对确认,不能仅凭列表看起来漂亮就宣布成功。
from fractions import Fraction as Q
def P(data):
out = {}
for e, c in data.items():
if (not isinstance(e, tuple) or len(e) != 2
or any(type(k) is not int or k < 0 for k in e)):
raise ValueError("expected two nonnegative exponents")
if type(c) not in (int, str, Q):
raise TypeError("use exact coefficients")
c = Q(c)
if c:
out[e] = c
return out
def add(p, q, scale=1):
r = dict(p)
for e, c in q.items():
r[e] = r.get(e, Q(0)) + scale * c
if not r[e]:
del r[e]
return r
def shift(p, e, c=1):
return {tuple(a + b for a, b in zip(k, e)): v * c
for k, v in p.items() if v * c}
def mul(p, q):
r = {}
for e, c in q.items():
r = add(r, shift(p, e, c))
return r
def divides(a, b):
return all(x <= y for x, y in zip(a, b))
def show(p):
return [(e, str(p[e])) for e in sorted(p, reverse=True)]
def divide(p, G):
if any(not g for g in G):
raise ValueError("zero divisor")
work, rem = dict(p), {}
quot = [{} for _ in G]
while work:
e = max(work) # lex, x > y
for i, g in enumerate(G):
t = max(g)
if divides(t, e):
u = tuple(a - b for a, b in zip(e, t))
c = work[e] / g[t]
quot[i] = add(quot[i], {u: c})
work = add(work, shift(g, u, c), -1)
break
else:
rem[e] = work.pop(e)
return quot, rem
def spol(f, g):
a, b = max(f), max(g)
lcm = tuple(max(x, y) for x, y in zip(a, b))
u = tuple(x - y for x, y in zip(lcm, a))
v = tuple(x - y for x, y in zip(lcm, b))
return add(shift(f, u, 1 / f[a]),
shift(g, v, 1 / g[b]), -1)
def buchberger(F, pair_limit=1000):
from collections import deque
from itertools import combinations
G = []
for f in F:
f = P(f)
if f:
G.append(shift(f, (0, 0), 1 / f[max(f)]))
pairs = deque(combinations(range(len(G)), 2))
done = 0
while pairs:
if done >= pair_limit:
raise RuntimeError("pair budget exhausted; no answer")
i, j = pairs.popleft()
done += 1
_, r = divide(spol(G[i], G[j]), G)
if r:
r = shift(r, (0, 0), 1 / r[max(r)])
pairs.extend((k, len(G)) for k in range(len(G)))
G.append(r)
return G
F = [P({(2, 0): 1, (0, 1): -1}),
P({(1, 1): 1, (0, 0): -1})]
from itertools import combinations
G = buchberger(F)
for i, g in enumerate(G):
print("G" + str(i + 1), show(g))
print("all pairs zero:", all(not divide(spol(a, b), G)[1]
for a, b in combinations(G, 2)))
print("zero ideal:", buchberger([{}]))精确输出:
G1 [((2, 0), '1'), ((0, 1), '-1')] G2 [((1, 1), '1'), ((0, 0), '-1')] G3 [((1, 0), '1'), ((0, 2), '-1')] G4 [((0, 3), '1'), ((0, 0), '-1')] all pairs zero: True zero ideal: []
示例六:成员判定附带原生成元见证
仅保存最终基还不够。我们为每个基元素同步保存一个多项式向量 H,使 gᵢ 等于 H 的第 i 行与原生成元向量的内积。初始化是缩放后的单位向量;构造 S 多项式、减去各商倍数和首一化时,对见证执行完全相同的线性运算。它是代数意义上的来源追踪,并不是字符串操作日志。
将待测 h 除以最终基得到 q 与 r,再计算 a=qH,便有 h=Σaⱼfⱼ+r。r 为零时,a 是直接可验的成员证书;r 非零时,还需知道基确实完整且 r 已不可约,才能断言非成员。下面同时测试 x³−1 与 x,并把每个基元素的来源都重新展开核验。这里的理想系数属于 Q[x,y],不能把结论直接迁移到整数系数理想。
from fractions import Fraction as Q
def P(data):
out = {}
for e, c in data.items():
if (not isinstance(e, tuple) or len(e) != 2
or any(type(k) is not int or k < 0 for k in e)):
raise ValueError("expected two nonnegative exponents")
if type(c) not in (int, str, Q):
raise TypeError("use exact coefficients")
c = Q(c)
if c:
out[e] = c
return out
def add(p, q, scale=1):
r = dict(p)
for e, c in q.items():
r[e] = r.get(e, Q(0)) + scale * c
if not r[e]:
del r[e]
return r
def shift(p, e, c=1):
return {tuple(a + b for a, b in zip(k, e)): v * c
for k, v in p.items() if v * c}
def mul(p, q):
r = {}
for e, c in q.items():
r = add(r, shift(p, e, c))
return r
def divides(a, b):
return all(x <= y for x, y in zip(a, b))
def show(p):
return [(e, str(p[e])) for e in sorted(p, reverse=True)]
def divide(p, G):
if any(not g for g in G):
raise ValueError("zero divisor")
work, rem = dict(p), {}
quot = [{} for _ in G]
while work:
e = max(work) # lex, x > y
for i, g in enumerate(G):
t = max(g)
if divides(t, e):
u = tuple(a - b for a, b in zip(e, t))
c = work[e] / g[t]
quot[i] = add(quot[i], {u: c})
work = add(work, shift(g, u, c), -1)
break
else:
rem[e] = work.pop(e)
return quot, rem
def spol(f, g):
a, b = max(f), max(g)
lcm = tuple(max(x, y) for x, y in zip(a, b))
u = tuple(x - y for x, y in zip(lcm, a))
v = tuple(x - y for x, y in zip(lcm, b))
return add(shift(f, u, 1 / f[a]),
shift(g, v, 1 / g[b]), -1)
def certified_basis(F):
from collections import deque
from itertools import combinations
G, H = [], []
for i, f in enumerate(F):
f = P(f)
if not f:
continue
c = 1 / f[max(f)]
G.append(shift(f, (0, 0), c))
H.append([{(0, 0): c} if j == i else {}
for j in range(len(F))])
pairs = deque(combinations(range(len(G)), 2))
done = 0
while pairs:
if done >= 1000:
raise RuntimeError("pair budget exhausted; no answer")
done += 1
i, j = pairs.popleft()
a, b = max(G[i]), max(G[j])
lcm = tuple(max(x, y) for x, y in zip(a, b))
u = tuple(x - y for x, y in zip(lcm, a))
v = tuple(x - y for x, y in zip(lcm, b))
witness = [add(shift(h, u), shift(k, v), -1)
for h, k in zip(H[i], H[j])]
quot, r = divide(spol(G[i], G[j]), G)
if r:
for q, row in zip(quot, H):
witness = [add(h, mul(q, k), -1)
for h, k in zip(witness, row)]
c = 1 / r[max(r)]
pairs.extend((k, len(G)) for k in range(len(G)))
G.append(shift(r, (0, 0), c))
H.append([shift(h, (0, 0), c) for h in witness])
return G, H
def combine(coeffs, polys):
r = {}
for a, f in zip(coeffs, polys):
r = add(r, mul(a, f))
return r
F = [P({(2, 0): 1, (0, 1): -1}),
P({(1, 1): 1, (0, 0): -1})]
G, H = certified_basis(F)
assert all(combine(row, F) == g for row, g in zip(H, G))
for name, h in [("x^3-1", P({(3, 0): 1, (0, 0): -1})),
("x", P({(1, 0): 1}))]:
q, r = divide(h, G)
a = [{} for _ in F]
for qi, row in zip(q, H):
a = [add(ai, mul(qi, hij)) for ai, hij in zip(a, row)]
print(name, "member:", not r, "remainder:", show(r))
print("witness:", [show(ai) for ai in a])
print("identity:", add(combine(a, F), r) == h)精确输出:
x^3-1 member: True remainder: [] witness: [[((1, 0), '1')], [((0, 0), '1')]] identity: True x member: False remainder: [((0, 2), '1')] witness: [[((0, 1), '1')], [((1, 0), '-1')]] identity: True
示例七:SQLite 保存的是精确数据,不做有理数算术
Python 的整数可以超过机器字长,但 SQLite 的 INTEGER 是有范围的整数存储类别。把任意大的分子、分母声明成 NUMERIC 也不保险,类型亲和性可能把超范围数字文本转换成 REAL。这里明确用 TEXT 保存十进制分子和正分母,读取后用 Python 的 int 与 Fraction 恢复;指数同样按 JSON 文本保存,避免额外引入整数上界。
元数据记录变量、系数域和项序。主键避免同一多项式重复保存同指数项;外键显式开启,参数绑定负责传值。规范化分数必须在应用层检查,数据库不会自动证明分母非零、指数非负或分数已约分。零多项式拥有 poly 行但没有 term 行,因而与“找不到这个多项式”有明确区别。本例特意使用超过有符号六十四位范围的分子,检验全程仍是文本和精确分数。
import json
import sqlite3
from fractions import Fraction as Q
con = sqlite3.connect(":memory:")
con.execute("PRAGMA foreign_keys = ON")
con.executescript("""
CREATE TABLE ring(id INTEGER PRIMARY KEY, vars TEXT, domain TEXT, ord TEXT);
CREATE TABLE poly(id INTEGER PRIMARY KEY, ring_id INTEGER REFERENCES ring(id));
CREATE TABLE term(
poly_id INTEGER REFERENCES poly(id), exp TEXT, num TEXT, den TEXT,
PRIMARY KEY(poly_id, exp));
""")
p = {(2, 0): Q(10**40 + 1, 7), (0, 1): Q(-2, 3)}
with con:
con.execute("INSERT INTO ring VALUES(1, ?, ?, ?)",
(json.dumps(["x", "y"]), "QQ", "lex"))
con.execute("INSERT INTO poly VALUES(1, 1)")
con.execute("INSERT INTO poly VALUES(2, 1)")
for e, c in p.items():
con.execute("INSERT INTO term VALUES(?, ?, ?, ?)",
(1, json.dumps(e), str(c.numerator), str(c.denominator)))
restored = {}
for e, n, d in con.execute("SELECT exp, num, den FROM term WHERE poly_id=1"):
e = tuple(json.loads(e))
if len(e) != 2 or any(type(v) is not int or v < 0 for v in e):
raise ValueError("bad exponent")
q = Q(int(n), int(d))
if (str(q.numerator), str(q.denominator)) != (n, d) or not q:
raise ValueError("noncanonical coefficient")
restored[e] = q
print("round trip:", restored == p)
print("storage:", con.execute("SELECT DISTINCT typeof(num), typeof(den) FROM term").fetchall())
print("zero rows:", con.execute("SELECT count(*) FROM term WHERE poly_id=2").fetchone()[0])
print("ring:", con.execute("SELECT domain, ord FROM ring").fetchone())
con.close()精确输出:
round trip: True
storage: [('text', 'text')]
zero rows: 0
ring: ('QQ', 'lex')示例八:关掉数据库后重新验算证书
真正有用的重放不要求相信生成证书的那次进程。下面将原生成元、一个较小的基、基的来源向量以及两个查询的恒等式证书写入临时 SQLite 文件,然后关闭连接,再从新连接读取。验证器不运行补全算法,而是检查三件事:每个基元素属于原理想;原生成元对该基余式为零;全部 S 对余式为零。前两项建立理想相等,第三项建立 Gröbner 性。
随后展开每个查询的 h=Σaⱼfⱼ+r,并检查 r 的每个单项式均不能被基首单项式整除。这样才能把非零 r 用作非成员证据。证书不是只有一串哈希:SHA-256 用来发现意外改动,并不认证作者;即使攻击者重算哈希,数学关系也仍须重新验证。例子故意改动非成员余式,展示恒等式检查会拒绝它。
此格式是受控本地教学样本,解析器检查关键结构与规范系数;若接收外部上传,还要限制文件大小、项数、整数位数、指数和验证预算,防止资源耗尽。失败应作为“证书无效或无法在预算内验证”,不能转换成“数学命题为假”。这里的重放对象是足以重算结论的代数证书,不承诺还原原进程的每一条指令。
from fractions import Fraction as Q
def P(data):
out = {}
for e, c in data.items():
if (not isinstance(e, tuple) or len(e) != 2
or any(type(k) is not int or k < 0 for k in e)):
raise ValueError("expected two nonnegative exponents")
if type(c) not in (int, str, Q):
raise TypeError("use exact coefficients")
c = Q(c)
if c:
out[e] = c
return out
def add(p, q, scale=1):
r = dict(p)
for e, c in q.items():
r[e] = r.get(e, Q(0)) + scale * c
if not r[e]:
del r[e]
return r
def shift(p, e, c=1):
return {tuple(a + b for a, b in zip(k, e)): v * c
for k, v in p.items() if v * c}
def mul(p, q):
r = {}
for e, c in q.items():
r = add(r, shift(p, e, c))
return r
def divides(a, b):
return all(x <= y for x, y in zip(a, b))
def show(p):
return [(e, str(p[e])) for e in sorted(p, reverse=True)]
def divide(p, G):
if any(not g for g in G):
raise ValueError("zero divisor")
work, rem = dict(p), {}
quot = [{} for _ in G]
while work:
e = max(work) # lex, x > y
for i, g in enumerate(G):
t = max(g)
if divides(t, e):
u = tuple(a - b for a, b in zip(e, t))
c = work[e] / g[t]
quot[i] = add(quot[i], {u: c})
work = add(work, shift(g, u, c), -1)
break
else:
rem[e] = work.pop(e)
return quot, rem
def spol(f, g):
a, b = max(f), max(g)
lcm = tuple(max(x, y) for x, y in zip(a, b))
u = tuple(x - y for x, y in zip(lcm, a))
v = tuple(x - y for x, y in zip(lcm, b))
return add(shift(f, u, 1 / f[a]),
shift(g, v, 1 / g[b]), -1)
import json
import hashlib
import sqlite3
import tempfile
from pathlib import Path
from itertools import combinations
def wire(p):
return [[*e, str(p[e].numerator), str(p[e].denominator)]
for e in sorted(p, reverse=True)]
def unwire(rows):
out = {}
for a, b, n, d in rows:
c = Q(int(n), int(d))
if (n, d) != (str(c.numerator), str(c.denominator)) or not c:
raise ValueError("bad coefficient")
e = (a, b)
if e in out:
raise ValueError("duplicate exponent")
out.update(P({e: c}))
return out
def combine(a, F):
out = {}
for q, f in zip(a, F):
out = add(out, mul(q, f))
return out
def verify(doc):
try:
if (doc["version"], doc["vars"], doc["domain"], doc["order"]) != (1, ["x", "y"], "QQ", "lex"):
return False
F = [unwire(p) for p in doc["F"]]
G = [unwire(p) for p in doc["G"]]
H = [[unwire(p) for p in row] for row in doc["H"]]
if not G or any(not g for g in G) or len(H) != len(G):
return False
if any(len(row) != len(F) or combine(row, F) != g
for row, g in zip(H, G)):
return False
if any(divide(f, G)[1] for f in F):
return False
if any(divide(spol(a, b), G)[1] for a, b in combinations(G, 2)):
return False
for item in doc["queries"]:
h, r = unwire(item["h"]), unwire(item["r"])
a = [unwire(p) for p in item["a"]]
if len(a) != len(F) or add(combine(a, F), r) != h:
return False
if any(divides(max(g), e) for g in G for e in r):
return False
return True
except (ValueError, TypeError, KeyError, ZeroDivisionError):
return False
F = [P({(2, 0): 1, (0, 1): -1}),
P({(1, 1): 1, (0, 0): -1})]
G = [P({(1, 0): 1, (0, 2): -1}), P({(0, 3): 1, (0, 0): -1})]
H = [[P({(0, 1): 1}), P({(1, 0): -1})],
[P({(0, 2): -1}), P({(1, 1): 1, (0, 0): 1})]]
queries = [
{"h": wire(P({(3, 0): 1, (0, 0): -1})),
"a": [wire(P({(1, 0): 1})), wire(P({(0, 0): 1}))], "r": []},
{"h": wire(P({(1, 0): 1})),
"a": [wire(p) for p in H[0]], "r": wire(P({(0, 2): 1}))}
]
doc = {"version": 1, "vars": ["x", "y"], "domain": "QQ", "order": "lex",
"F": [wire(p) for p in F], "G": [wire(p) for p in G],
"H": [[wire(p) for p in row] for row in H], "queries": queries}
raw = json.dumps(doc, sort_keys=True, separators=(",", ":"))
digest = hashlib.sha256(raw.encode()).hexdigest()
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / "proof.sqlite"
con = sqlite3.connect(path)
con.execute("CREATE TABLE proof(id INTEGER PRIMARY KEY, payload TEXT, digest TEXT)")
with con:
con.execute("INSERT INTO proof VALUES(1, ?, ?)", (raw, digest))
con.close()
con = sqlite3.connect(path)
saved, checksum = con.execute("SELECT payload, digest FROM proof WHERE id=1").fetchone()
con.close()
loaded = json.loads(saved)
checksum_ok = hashlib.sha256(saved.encode()).hexdigest() == checksum
valid = verify(loaded)
print("checksum:", checksum_ok)
print("replay:", valid)
if not checksum_ok or not valid:
raise ValueError("invalid replay; no membership conclusion")
print("members:", [not item["r"] for item in loaded["queries"]])
loaded["queries"][1]["r"][0][2] = "2"
print("tampered:", verify(loaded))精确输出:
checksum: True replay: True members: [True, False] tampered: False
示例九:用独立商环公式穷举,而非自证正确
把同一个函数再调用一次不算独立检验。对这个特定理想,由 x=y²、y³=1 可得 xᵃyᵇ 的标准余式是 y 的 (2a+b) 模三次方。因此可以不用除法、S 多项式或待处理队列,直接将系数归入三个桶,作为独立的预言机。此公式来自本例的已验证关系,不能拿去检验任意输入理想。
代码穷举六个指定单项式上的三值系数,共七百二十九个多项式,并额外检验有理缩放生成元、单位理想和空生成元列表。零理想只能接受零多项式;含非零常数的理想等于整个环。另外把两个生成元分别乘以 2/3 和 −7/5,并用同一组输入确认这两次缩放不改变标准余式。穷举的边界写得清楚,比声称“全部多项式都测试过”更可靠。
from fractions import Fraction as Q
def P(data):
out = {}
for e, c in data.items():
if (not isinstance(e, tuple) or len(e) != 2
or any(type(k) is not int or k < 0 for k in e)):
raise ValueError("expected two nonnegative exponents")
if type(c) not in (int, str, Q):
raise TypeError("use exact coefficients")
c = Q(c)
if c:
out[e] = c
return out
def add(p, q, scale=1):
r = dict(p)
for e, c in q.items():
r[e] = r.get(e, Q(0)) + scale * c
if not r[e]:
del r[e]
return r
def shift(p, e, c=1):
return {tuple(a + b for a, b in zip(k, e)): v * c
for k, v in p.items() if v * c}
def mul(p, q):
r = {}
for e, c in q.items():
r = add(r, shift(p, e, c))
return r
def divides(a, b):
return all(x <= y for x, y in zip(a, b))
def show(p):
return [(e, str(p[e])) for e in sorted(p, reverse=True)]
def divide(p, G):
if any(not g for g in G):
raise ValueError("zero divisor")
work, rem = dict(p), {}
quot = [{} for _ in G]
while work:
e = max(work) # lex, x > y
for i, g in enumerate(G):
t = max(g)
if divides(t, e):
u = tuple(a - b for a, b in zip(e, t))
c = work[e] / g[t]
quot[i] = add(quot[i], {u: c})
work = add(work, shift(g, u, c), -1)
break
else:
rem[e] = work.pop(e)
return quot, rem
def spol(f, g):
a, b = max(f), max(g)
lcm = tuple(max(x, y) for x, y in zip(a, b))
u = tuple(x - y for x, y in zip(lcm, a))
v = tuple(x - y for x, y in zip(lcm, b))
return add(shift(f, u, 1 / f[a]),
shift(g, v, 1 / g[b]), -1)
def buchberger(F, pair_limit=1000):
from collections import deque
from itertools import combinations
G = []
for f in F:
f = P(f)
if f:
G.append(shift(f, (0, 0), 1 / f[max(f)]))
pairs = deque(combinations(range(len(G)), 2))
done = 0
while pairs:
if done >= pair_limit:
raise RuntimeError("pair budget exhausted; no answer")
i, j = pairs.popleft()
done += 1
_, r = divide(spol(G[i], G[j]), G)
if r:
r = shift(r, (0, 0), 1 / r[max(r)])
pairs.extend((k, len(G)) for k in range(len(G)))
G.append(r)
return G
F = [P({(2, 0): 1, (0, 1): -1}),
P({(1, 1): 1, (0, 0): -1})]
from itertools import product
def oracle(p):
out = {}
for (a, b), c in p.items():
e = (0, (2 * a + b) % 3)
out[e] = out.get(e, Q(0)) + c
return {e: c for e, c in out.items() if c}
G = buchberger(F)
scaled = buchberger([shift(F[0], (0, 0), Q(2, 3)),
shift(F[1], (0, 0), Q(-7, 5))])
mons = [(0, 0), (1, 0), (0, 1), (2, 0), (1, 1), (0, 3)]
count = 0
for coeffs in product((-1, 0, 1), repeat=len(mons)):
p = P(dict(zip(mons, coeffs)))
expected = oracle(p)
assert divide(p, G)[1] == expected
assert divide(p, scaled)[1] == expected
count += 1
unit = buchberger([P({(0, 0): "2/3"})])
print("exhaustive:", count)
print("unit ideal:", not divide(P({(7, 2): "5/11"}), unit)[1])
print("zero ideal:", divide(P({(1, 0): 1}), buchberger([]))[1] == P({(1, 0): 1}))
print("scaled generators:", "PASS")精确输出:
exhaustive: 729 unit ideal: True zero ideal: True scaled generators: PASS
复杂度、边界与工程取舍
输入项数少不意味着中间结果少。每次 S 多项式计算都可能引入更高次数和更大的分子、分母;基元素增加又会带来二次量级的候选对数。以最终基规模 m 计,不跳过的无序对有 m(m−1)/2 个,但 m 自身并不是输入大小的固定多项式上界,不能据此把整个算法说成二次时间。对两个稀疏多项式,朴素乘法要处理项数乘积那么多的项对;整数位数增长又使每次有理运算变贵。
更困难的输入会遇到极高的次数和存储膨胀,变量数增多尤其危险。本文没有实现乘积判据、链判据、F4 的矩阵批处理或模块化重构。生产计算通常应交给成熟计算机代数系统,并在外层设置时间、内存、项数与系数位长预算。只设置示例中的对数上限仍不足以保证内存安全,因为一次约化本身就可能很大。
SQLite 在这里承担可重现记录,而不是加速代数运算:用事务把一份完整证书一起提交,以显式主键定位记录;读取时同时核对变量顺序、系数域、项序和格式版本。若要长期保存,再加入算法版本、输入摘要和资源统计,但不要把版本号或摘要当成数学证明。换项序后应另建运行记录,旧的首项、余式及证书不能悄悄复用。
最后的检查清单可以很短:所有系数精确;零项清理;除式非零;新增对没有遗漏;预算不足显式失败;基与原理想双向一致;每对 S 多项式归零;查询恒等式成立;余式不可约。前面九个例子分别把这些责任拆开,使一个可以演示的答案进一步成为别人能够重新验算的答案。
原始资料与进一步阅读
Bruno Buchberger:Towards the Automated Synthesis of a Gröbner Bases Algorithm,第 2、3 节给出多项式约化、S 多项式判据与补全框架。
Python 官方文档:fractions,核对有理数构造、规范分子分母及浮点构造的区别。
Python 官方文档:sqlite3,核对参数绑定、连接、事务与类型转换。
SQLite 官方文档:Datatypes In SQLite,核对 INTEGER 范围、TEXT 与 NUMERIC 类型亲和性。
SQLite 官方文档:Foreign Key Support,核对连接级外键开启方式。
SQLite 官方文档:Transaction,核对提交、回滚与事务边界。
资料核查日期:2026 年 10 月 20 日。示例、证书格式、测试预言机与讲解均为本文原创实现;文档链接说明接口和数学依据,不意味着示例具有工业级性能或安全性。

