Published
Edited
Mar 9, 2021
Importers
Insert cell
md`# Polynomials`
Insert cell
d3 = require('d3')
Insert cell
p1 = [1, 0, 1]
Insert cell
pBCH = [1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1]
Insert cell
function pToNum(p) {
return p.reduce(function(x, pi, i) {
return 2 * x + pi;
}, 0);
}
Insert cell
function numToP(x) {
let p = [];
let r = x;
while (r > 0) {
p.push(r % 2);
r = Math.trunc(r / 2);
}
return p.reverse();
}
Insert cell
function pow(p, a) {
return [].concat(p, new Array(a).fill(0));
}
Insert cell
function str(p) {
const n = p.length;
return p
.map(function(pi, i) {
const a = n - i - 1;
if (a === 0 && pi === 1) {
return 1;
}
return pi === 1 ? `x^${a}` : '';
})
.filter(d => d)
.join(' + ');
}
Insert cell
str(pBCH)
Insert cell
function degree(p1) {
if (!p1) {
return -1;
}
return p1.length - 1;
}
Insert cell
function shrink(p) {
let leadingZeros = true;
return p.reduce(function(shrunkP, pi) {
if (!leadingZeros || pi !== 0) {
leadingZeros = false;
shrunkP.push(pi);
}
return shrunkP;
}, []);
}
Insert cell
function pad(p, n) {
const np = p.length;
if (np >= n) {
return p;
}
return [].concat(new Array(n - np).fill(0), p);
}
Insert cell
pad([1, 2, 3], 10)
Insert cell
function add(p1, p2) {
const d1 = degree(p1);
const d2 = degree(p2);
const d = Math.max(d1, d2);

return shrink(
d3
.range(0, d + 1)
.map(function(p, i) {
return (i <= d1 ? p1[d1 - i] : 0) + (i <= d2 ? p2[d2 - i] : 0);
})
.reverse()
);
}
Insert cell
add([1, 1], [1, 0, 1])
Insert cell
function mul(p1, p2) {
const d1 = degree(p1);
const d2 = degree(p2);
let p = new Array(d1 + d2 + 1).fill(0);

[...p1].reverse().forEach(function(p1i, i1) {
[...p2].reverse().forEach(function(p2i, i2) {
p[i1 + i2] += p1i * p2i;
});
});
return [...p].reverse();
}
Insert cell
mul([1, 1], [1, -1])
Insert cell
function smul(p, k) {
return p.map(pi => (pi * k ? pi * k : 0));
}
Insert cell
smul([1, 1], -2)
Insert cell
function div(p1, p2) {
const d1 = degree(p1);
const d2 = degree(p2);
const a = d1 - d2;
if (a < 0) {
return [[], p1];
}
const q = pow([p1[0] / p2[0]], a);
const r = add(p1, smul(mul(q, p2), -1));
const [rq, rr] = div(r, p2);
return [add(q, rq), rr];
}
Insert cell
smul(
div(
[1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1]
)[1],
-1
)
Insert cell
function xor(p1, p2) {
const n = p1.length;
if (n !== p2.length) {
return undefined;
}
return d3.range(0, n).map(i => p1[i] ^ p2[i]);
}
Insert cell
xor([1, 1, 0, 0], [1, 0, 1, 0])
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more