xxxxxxxxxx
112
//Click to show polynomial interpolant of next degree.
//This is a quick program to test out an idea about
//Newton polynomials and the Fibonacci sequence.
//Need to replace hard-coded values with vars, probably
//do more refactoring, etc.
//See Sketch Files for classes.
//VARIABLES
let cnv; //canvas
let win; //graph window (includes origin and scale for axes)
let points; //array of [x, y] pairs
let fibCurves = []; //array of interpolants (as curves)
let maxDegree = 1; //max degree of polynomial interpolants
//CUSTOM FUNCTIONS
function falling(x, k) {//kth falling power of x for integer k >=0
let power = 1;
for (let i = 0; i < k; i++) {
power *= x - i;
}
return power;
}
function fib(n) {//nth term in Fibonacci sequence, n = 0, 1, 2...
let f0 = 0;
let f1 = 1;
let fn = 0;
if (n === 0) {
fn = f0;
}
else if (n === 1) {
fn = f1;
}
else {
for (let k = 0; k < n - 1; k++) {
fn = f0 + f1;
f0 = f1;
f1 = fn;
}
}
return fn;
}
function c(n) {//coefficient for interpolant
return (-1) ** (n+1) * fib(n) / falling(n,n);
}
function p(x, n) {//interpolant for fib(0), ... ,fib(n), evaluated at x
let poly = 0;
for (let k = 0; k < n + 1; k++) {
poly += c(k) * falling(x, k);
}
return poly;
}
function pFunc(n) {
return x => p(x, n);
}
//return graph of f, starting from x = a, with given step size and count
function graph(f, a, stepCount, stepSize = 0.01) {
let xi, yi;
let pairs = [];
for (let i = 0; i < stepCount; i++) {
xi = a + i * stepSize;
yi = f(xi);
pairs.push([xi, yi]);
}
return pairs;
}
//SETUP AND DRAW
function setup() {
createCanvas(400, 400);
plot = createGraphics(400, 400);
win = createGraphWindow(20, 380, 50, 50);
}
function draw() {
//make window
plot.background(229, 255, 234);
plot.stroke(0);
plot.strokeWeight(1);
win.axis('horizontal', plot);
win.axis('vertical', plot);
//make curves
for (let n = 1; n <= maxDegree; n++) {
points = graph(pFunc(n), 0, 800);
fibCurves.push(createCurve(points, win));
}
plot.stroke(232, 51, 232);
plot.strokeWeight(2);
for (let i = 0; i < fibCurves.length; i++) {
fibCurves[i].draw(plot);
}
//show plot
image(plot, 0, 0);
noLoop();
}
//INTERACTIVITY
function mousePressed() {
maxDegree++;
loop();
}