function interpolation(x, y) {
// x, y :: number[] (same size)
// result = 0
var result = [];
for (var k = 0; k < x.length; k++) {
result[k] = 0;
}
for (var i = 0; i < x.length; i++) {
var basis = [1];
for (var j = 0; j < x.length; j++) {
if (i != j) {
if (x[i] == x[j]) {
throw new Error("All x-values must be distinct");
}
// basis = conv(basis, [1, -x[j]])/(x[i] - x[j])
basis = conv(basis, [1, -x[j]]).map(function(z) {
return z/(x[i] - x[j]);
});
}
}
// result += y[i] * basis
result = result.map(function(r, k) {
return r + y[i] * basis[k];
});
}
return result;
}
function conv(x, y) {
// x, y :: number[]
var result = [];
for (var k = 0; k < x.length + y.length - 1; k++) {
var sum = 0;
for (var i = 0; i < x.length; i++) {
var j = k - i;
if (j >= 0 && j < y.length) {
sum += x[i] * y[j];
}
}
result[k] = sum;
}
return result;
}
console.log('interpolation([1, 2, 3], [1, 4, 9]) =',
interpolation([1, 2, 3], [1, 4, 9]));
console.log('interpolation([1, 2, 3], [1, 8, 27]) =',
interpolation([1, 2, 3], [1, 8, 27]));