Lagrange polynomial
http://en.wikipedia.org/wiki/Lagrange_polynomial
/**
* Copyright makc3d ( http://wonderfl.net/user/makc3d )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/x1tB
*/
// http://en.wikipedia.org/wiki/Lagrange_polynomial
package {
import flash.display.Sprite;
[SWF(frameRate="7")]
public class FlashTest extends Sprite {
public function FlashTest() {
Wonderfl.capture_delay (10);
stage.addEventListener ("mouseDown", onMouseDown);
stage.addEventListener ("mouseUp", onMouseUp);
stage.addEventListener ("enterFrame", onEnterFrame);
}
public var mouseDown:Boolean = false;
public function onMouseDown (e:*):void {
posx.length = 0;
posy.length = 0;
mouseDown = true;
}
public function onMouseUp (e:*):void {
mouseDown = false;
}
public var posx:Array = [];
public var posy:Array = [];
public function onEnterFrame (e:*):void {
if (mouseDown) {
posx.push (mouseX);
posy.push (mouseY);
}
var i:int = 0, ts:Array = [];
graphics.clear ();
graphics.lineStyle ();
graphics.beginFill (0xFF0000);
for (i = 0; i < posx.length; i++) {
ts.push (i);
graphics.drawCircle (posx [i], posy [i], 3);
}
graphics.endFill ();
if (!mouseDown && (posx.length > 1)) {
graphics.lineStyle (0, 0);
for (var t:Number = 0; t < 100; t += 0.1) {
var tx:Number = lagrangeInterpolatingPolynomial (
ts, posx, t);
var ty:Number = lagrangeInterpolatingPolynomial (
ts, posy, t);
if (t == 0)
graphics.moveTo (tx, ty);
else
graphics.lineTo (tx, ty);
}
}
}
public function lagrangeInterpolatingPolynomial (
pos:Array, val:Array, desiredPos:Number):Number {
var degree:int = pos.length;
var retVal:Number = 0;
for (var i:int = 0; i < degree; i++) {
var weight:Number = 1;
for (var j:int = 0; j < degree; j++) {
// The i-th term has to be skipped
if (j != i) {
weight *= (desiredPos - pos[j]) / (pos[i] - pos[j]);
}
}
retVal += weight * val[i];
}
return retVal;
}
}
}