Berlekamp–Welch纠错实战:不知道哪两个符号错了,为什么先乘一个定位多项式就能找回原文

10-08 6阅读

收到七个编码符号,其中两项被改成了错误数字,却没有人告诉你是哪两项。直接挑三个点插值可能恰好挑到坏点;先用None标记缺失的擦除恢复方法,在这里也没有已知位置可用。Berlekamp–Welch把未知错误位置一起变成多项式方程里的未知量。

本文在素数域F257中传输次数小于k的多项式求值,消息就是它的k个系数。若长度n至少为k加二倍错误预算t,最多t个任意位置的符号错误可以唯一纠正。符号范围为零到256,程序没有把它冒充为普通八位字节协议。

Berlekamp–Welch纠错实战:不知道哪两个符号错了,为什么先乘一个定位多项式就能找回原文
AI模型生成概念插图:损坏采样点被定位环隔离,连续色带表示恢复多项式,非精确函数图或检测截图;图形仅表达机制。

让错误位置变成某个多项式的根

设原多项式为P,接收值为y。构造一个非零定位多项式E,使每个坏位置xi都满足E(xi)等于零。于是无论该处y错成什么,乘积y乘E(xi)都为零;在正确位置,y本来就等于P(xi)。全部位置因此统一满足Q(xi)等于y乘E(xi),其中Q定义为P乘E。

关键是先把Q当成独立未知多项式,而不在方程里直接展开两个未知多项式P和E的乘积。Q的次数小于k加t,E的次数取t且首项系数固定为一,这样所有剩余未知系数只一次出现,得到线性方程组。

固定首项,避免全零解混进来

若不给E任何规范化条件,Q和E同时为零总能满足方程,却不能相除恢复消息。源码把E的最高项固定为一,只求它前面的t个系数;Q有k加t个未知系数,总计k加二t个。

每个接收位置提供一行方程:Q系数前是相应的幂,E低次系数前是负y乘这些幂,固定最高项移到等式右边。这里减法、乘法和求逆全部在同一个素数域内进行,不能使用浮点高斯消元再把答案四舍五入。

错误少于预算时,自由变量并不一定是故障

实际只有e个错误且e小于t时,可以在真实错误定位因子之外再乘一个次数为t减e的多项式,所以定位式未必唯一。线性系统可能出现自由变量,代码把它们设零,并保留E首一这一硬约束。

这时E也可能在正确位置为零,不能把它的所有根直接宣布为损坏位置。本文恢复P以后重新逐点求值,把与接收数据真正不一致的位置列出来。主样本恰有两错且预算也是二,打印出的定位式为x平方减六x加五,在位置一和五为零。

为什么不同线性解仍会给出同一条P

对任何一组符合方程的Q、E,与真实P比较Q减PE。至少n减t个正确位置使它为零,而其次数小于k加t。由n至少k加二t可知根的数量超过可能次数,因而它只能是零多项式,Q必然恰好等于PE。

这个论证不仅解释存在性,也说明自由变量不会改变可纠正范围内的商。最后仍要实际做多项式除法,检查余数为零、商的次数小于k,再检查不一致位置不超过t;不能因为线性方程求出一组数,就跳过解码结果的合同验收。

七个位置里恢复两处未知错误

消息系数为四、二、九,在零到六求值得到七个符号。测试只把位置一加三十三、位置五加七十七,再按257取余,接收端看到的是(4,48,44,91,156,59,83),没有额外的错误位置提示。

解码恢复(4,2,9),并通过重新编码指出位置一、五不一致。这里返回的是幂次系数,不是最前面三个求值符号;若应用需要系统型编码,还应明确消息到多项式的映射,不能把两种表示混着比较。

超过半距离预算时,检查也不能保证找回原文

最小距离为n减k加一,两个合法码字不可能同时距离同一接收字不超过t,前提正是二t小于该距离。但若真实错误数超过t,接收字可能离另一份合法消息很近,算法就会合理地返回那份候选。

程序用四个位置演示:原消息零、零本应编码成全零,改坏三项得到(1,1,1,0)。以一错预算解码,会得到常数一的消息(1,0),因为它只与最后一项不符。这个反例说明重编码距离检查不能替代传输来源认证,也不能在预算外识别历史上的真实原文。

随机恢复与整个小域穷举分别核对

600次随机测试从独立的幂次求和编码器生成目标值,再改变不超过预算的随机位置,比较恢复系数。它覆盖零错、少于预算和用满预算,也包含高次系数为零的情况,避免把固定次数假设偷偷加进消息。

第二套测试使用F7的四位置、两系数、一错模型。枚举全部49份合法码字,再对全部2401份接收字直接计算汉明距离,与解码器是否成功以及返回哪份消息对照。这个裁判不解线性方程,因而能发现错误接受、错误拒绝与商计算问题。

本实现限制k至多八、t至多四、n至多32,并只允许两个明确的素数域。若未知量数为m等于k加二t,直接消元约需O(nm²)次域运算,适合教学而非高速存储纠错库。位置互异、消息版本和域参数必须一致;冗余不足与非法符号会在求解前拒绝。

完整程序与本次实际输出

将以下程序保存为demo.py,执行python3 demo.py。本次在Linux、CPython 3.12.14运行,退出码为0,标准错误为空。程序只使用标准库与内存样本,不安装软件、不访问网络或业务文件。

from itertools import product
from random import Random


def value(coefficients,x,p):
    out=0
    for c in reversed(coefficients): out=(out*x+c)%p
    return out


def trim(a):
    while len(a)>1 and a[-1]==0: a.pop()
    return a


def linear_solve(rows,width,p):
    a=[row[:] for row in rows]
    pivots=[]; r=0
    for c in range(width):
        pivot=next((j for j in range(r,len(a)) if a[j][c]),None)
        if pivot is None: continue
        a[r],a[pivot]=a[pivot],a[r]
        inv=pow(a[r][c],-1,p)
        a[r]=[v*inv%p for v in a[r]]
        for j in range(len(a)):
            if j!=r and a[j][c]:
                factor=a[j][c]
                a[j]=[(x-factor*y)%p for x,y in zip(a[j],a[r])]
        pivots.append(c); r+=1
    if any(not any(row[:width]) and row[width] for row in a):
        raise ValueError('inconsistent decoding equations')
    answer=[0]*width  # Free variables may be zero; E remains monic.
    for j,c in enumerate(pivots): answer[c]=a[j][width]
    return answer


def divide(numerator,denominator,p):
    rest=trim(numerator[:]); divisor=trim(denominator[:])
    out=[0]*max(1,len(rest)-len(divisor)+1)
    while rest!=[0] and len(rest)>=len(divisor):
        degree=len(rest)-len(divisor)
        factor=rest[-1]*pow(divisor[-1],-1,p)%p
        out[degree]=factor
        for i,c in enumerate(divisor): rest[i+degree]=(rest[i+degree]-factor*c)%p
        trim(rest)
    return trim(out),rest


def decode(k,t,received,p=257):
    if (type(p) is not int or p not in (7,257) or type(k) is not int or not 1<=k<=8 or
            type(t) is not int or not 0<=t<=4 or type(received) is not tuple or
            not k+2*t<=len(received)<=min(32,p) or
            any(type(y) is not int or not 0<=y<p for y in received)):
        raise ValueError('invalid field word or n < k + 2t')
    q_count=k+t
    rows=[]
    for x,y in enumerate(received):
        rows.append([pow(x,j,p) for j in range(q_count)] +
                    [(-y*pow(x,j,p))%p for j in range(t)] + [y*pow(x,t,p)%p])
    solution=linear_solve(rows,k+2*t,p)
    q,e=solution[:q_count],solution[q_count:]+[1]
    polynomial,remainder=divide(q,e,p)
    if remainder!=[0] or len(polynomial)>k:
        raise ValueError('candidate does not divide to a degree-bounded message')
    message=tuple(polynomial+[0]*(k-len(polynomial)))
    wrong=[i for i,y in enumerate(received) if value(message,i,p)!=y]
    if len(wrong)>t:
        raise ValueError('candidate exceeds correction radius')
    return message,tuple(e),wrong


message=(4,2,9)
word=tuple(value(message,x,257) for x in range(7))
damaged=list(word); damaged[1]=(damaged[1]+33)%257; damaged[5]=(damaged[5]+77)%257
answer,e,wrong=decode(3,2,tuple(damaged))
print('received:',tuple(damaged))
print('recovered coefficients:',answer)
print('monic locator coefficients:',e)
print('mismatching positions:',wrong)
assert answer==message and wrong==[1,5]
assert all(value(e,x,257)==0 for x in wrong)
rng=Random(7408)
for _ in range(600):
    k,t=rng.randrange(1,7),rng.randrange(4)
    n=k+2*t+rng.randrange(3)
    coefficients=tuple(rng.randrange(257) for j in range(k))
    # Independent powers-based encoder, not the Horner evaluator.
    received=[sum(c*pow(x,j,257) for j,c in enumerate(coefficients))%257 for x in range(n)]
    for x in rng.sample(range(n),rng.randrange(t+1)):
        received[x]=(received[x]+rng.randrange(1,257))%257
    assert decode(k,t,tuple(received))[0]==coefficients
print('unknown-error coefficient recovery checks:',600)
codebook=[(c,tuple((c[0]+c[1]*x)%7 for x in range(4))) for c in product(range(7),repeat=2)]
for received in product(range(7),repeat=4):
    matches=[c for c,w in codebook if sum(a!=b for a,b in zip(w,received))<=1]
    assert len(matches)<=1
    try: answer=decode(2,1,received,7)[0]
    except ValueError: assert not matches
    else: assert matches==[answer]
print('all F7 four-symbol words checked against 49 codewords:',7**4)
original=(0,0)
received=(1,1,1,0)
changed=decode(2,1,received)[0]
assert changed==(1,0) and changed!=original
print('three corruptions from zero can decode to another message:',changed)
for args in [(3,2,(0,)*6),(2,1,(True,0,0,0))]:
    try: decode(*args)
    except ValueError: pass
    else: raise AssertionError('invalid word accepted')
print('insufficient redundancy and boolean symbol rejected')

以下是上述完整程序本次实际标准输出,复制运行时不要把输出块带入代码。

received: (4, 48, 44, 91, 156, 59, 83)
recovered coefficients: (4, 2, 9)
monic locator coefficients: (5, 251, 1)
mismatching positions: [1, 5]
unknown-error coefficient recovery checks: 600
all F7 four-symbol words checked against 49 codewords: 2401
three corruptions from zero can decode to another message: (1, 0)
insufficient redundancy and boolean symbol rejected

参考资料

一手资料与本地运行核验日期:2026年10月8日。本文实现、样本及测试独立编写,有限实验不代表完整生产系统或性能保证。


文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。