Skip to content

Instantly share code, notes, and snippets.

@troufster
Created February 13, 2011 17:24
Show Gist options
  • Save troufster/824861 to your computer and use it in GitHub Desktop.
Save troufster/824861 to your computer and use it in GitHub Desktop.
Cubic extrapolator
/*
* A cubic extrapolator using the polynomial
* P(T) = aT^2 + bT + c
*/
function Extrapolator() {
this.s = [];
this.t = [];
this.sol = [];
};
/*
* Add a sample to the extrapolator
* @param {Number} s Sample
* @param {Number} t Time
*/
Extrapolator.prototype.addSample = function(s, t) {
this.s.push(s);
this.t.push(t);
//We only handle 3 samples, so shift if we get more
if(this.s.length > 3) {
this.s.shift();
this.t.shift();
}
//Only compute solution if we have 3 samples
if(this.s.length > 2) {
this.sol = Extrapolator._solve(this.s,this.t);
}
};
/*
* Return a predicted value from the extrapolator.
* @param {Number} t Time to predict value for.
* @Return {Number} P(T) of polynomial.
*/
Extrapolator.prototype.getValue = function(t) {
var s = this.sol;
return s[0] * t * t + s[1] * t + s[2];
};
/*
* Solves a 3x3 simultaneous equation system
* using cramers rule.
*/
Extrapolator._solve = function(p, t) {
//cramers rule.
var t0 = t[0], t1 = t[1], t2 = t[2],
p0 = p[0], p1 = p[1], p2 = p[2],
//Set up system
a = t0 * t0, b = t0, c = 1, d = p0,
e = t1 * t1, f = t1, g = 1, h = p1,
i = t2 * t2, j = t2, k = 1, l = p2,
//Delta determinant
delta = (a * f * k) + (b * g * i) +
(c * e * j) - (c * f * i) -
(a * g * j) - (b * e * k),
//x answer(a);
xnum = (d * f * k) + (b * g * l) +
(c * h * j) - (c * f * l) -
(d * g * j) - (b * h * k),
xans = xnum/delta,
//y answer(b)
ynum = (a * h * k) + (d * g * i) +
(c * e * l) - (c * h * i) -
(a * g * l) - (d * e * k),
yans = ynum/delta,
//z answer(c)
znum = (a * f * l) + (b * h * i) +
(d * e * j) - (d * f * i) -
(a * h * j) - (b * e * l),
zans = znum/delta;
return [xans, yans, zans];
};
/*
* A 2D Vector extrapolator using
* one extrapolator for each component
*/
function Vector2Extrapolator() {
this.ex = new Extrapolator();
this.ey = new Extrapolator();
};
/*
* Add a sample to the extrapolator
* @param {Number} s Sample
* @param {Number} t Time
*/
Vector2Extrapolator.prototype.addSample = function(v,t) {
this.ex.addSample(v.x, t);
this.ey.addSample(v.y, t);
};
/*
* Return a predicted value from the extrapolator.
* @param {Number} t Time to predict value for.
* @Return {Number} P(T) of polynomial.
*/
Vector2Extrapolator.prototype.getValue = function(t) {
var x = this.ex.getValue(t);
var y = this.ey.getValue(t);
return new Vector(x,y);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment