Error-correcting codes
Add redundancy to a message so that a few corrupted symbols can be found and fixed. A linear code is a subspace of ; its minimum distance says how many errors it can correct, and its parity-check matrix says where they are.
The Hamming code
import { hammingCode, isPerfect } from "@ratmath/discrete";
const h = hammingCode(3); // [7, 4] over Z_2
h.minimumDistance().distance; // 3: corrects one error
isPerfect(h); // true
const cw = h.encode([1, 0, 1, 1]); // [1, 0, 1, 1, 0, 1, 0]
h.decode([1, 0, 0, 1, 0, 1, 0]).steps;
// ["received 1001010", "syndrome H·rᵀ = 110",
// "the lightest error with that syndrome is 0010000 (weight 1)", "corrected codeword 1011010, message 1011"]
A code with generator matrix () encodes as . Put in systematic form ; then satisfies , and a word is a codeword exactly when its syndrome is zero. If , the syndrome is , so decoding is finding the lightest error with that syndrome, the coset leader. In the Hamming code the columns of are all non-zero vectors, so the syndrome of a single error is its position written in binary.
Distance and bounds
A code with minimum distance corrects errors, because balls of radius round the codewords do not overlap. Counting the words in those balls gives the Hamming (sphere-packing) bound, and a code that meets it is perfect:
import { codeBounds, ballSize } from "@ratmath/discrete";
codeBounds(7, 3, 2); // { hamming: 16n, singleton: 32n, gilbertVarshamov: 5n }
ballSize(7, 1); // 8n, and 16 · 8 = 2^7: the Hamming code is perfect
h.weightDistribution(); // [1, 0, 0, 7, 7, 0, 0, 1]
h.dual().minimumDistance().distance; // 4: the [7, 3] simplex code
Reed–Solomon
import { reedSolomon } from "@ratmath/discrete";
const rs = reedSolomon({ p: 11, n: 10, k: 4 }); // corrects 3 errors
const w = rs.encode([3, 1, 4, 1]); // the values of 3 + x + 4x² + x³ at 1, …, 10
const y = w.slice(); y[0] += 1; y[5] += 3; y[9] += 7; // three errors (mod 11)
rs.decode(y.map((v) => v % 11)).errors; // [0, 5, 9]
A message is a polynomial of degree below , sent as its values at distinct points. Two such polynomials agree in at most places, so the distance is , meeting the Singleton bound. Berlekamp–Welch decoding looks for an error locator of degree (monic) and of degree below with for every : a linear system over . Then , and vanishes at the error positions. The steps show the system, , and the division.
@ratmath/discrete and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.