Skip to content

Instantly share code, notes, and snippets.

@brenapp
Last active November 3, 2023 16:58
Show Gist options
  • Save brenapp/aa69f22b465fddd4b44e6ee23376667d to your computer and use it in GitHub Desktop.
Save brenapp/aa69f22b465fddd4b44e6ee23376667d to your computer and use it in GitHub Desktop.
// Adj. Close for Each Month
let adj = [
30.550734,
29.040157,
28.25503,
32.47147,
28.410118,
30.476208,
30.281532,
28.305592,
31.629807,
31.307159,
29.93041,
29.832214,
27.838818,
27.912491,
29.984467,
30.349529,
29.816734,
30.399223,
29.457609,
36.048897,
34.842018,
41.931904,
41.759998,
41.990002
];
console.log("Linearly interpolating...")
// Actually calculates the linear function
function interpolate(point1, point2) {
let m = doDecimalSafeMath(
doDecimalSafeMath(point2[1], "-", point1[1]),
"/",
doDecimalSafeMath(point2[0], "-", point1[0])
),
b = doDecimalSafeMath(m, "*", point1[0])
return `y = ${m}x + ${b}`
}
function doDecimalSafeMath(a, operation, b, precision) {
function decimalLength(numStr) {
var pieces = numStr.toString().split(".");
if(!pieces[1]) return 0;
return pieces[1].length;
}
// Figure out what we need to multiply by to make everything a whole number
precision = precision || Math.pow(10, Math.max(decimalLength(a), decimalLength(b)));
a = a*precision;
b = b*precision;
// Figure out which operation to perform.
var operator;
switch(operation.toLowerCase()) {
case '-':
operator = function(a,b) { return a - b; }
break;
case '+':
operator = function(a,b) { return a + b; }
break;
case '*':
case 'x':
precision = precision*precision;
operator = function(a,b) { return a * b; }
break;
case '÷':
case '/':
precision = 1;
operator = function(a,b) { return a / b; }
break;
// Let us pass in a function to perform other operations.
default:
operator = operation;
}
var result = operator(a,b);
// Remove our multiplier to put the decimal back.
return result/precision;
}
// Creates all the sets of points for each function
let points = [...Array(adj.length - 2)].map((v, i, a) => [adj[i], adj[i + 1]]);
for (var i = 0; i < points.length; i++) {
var line = points[i];
console.log(
interpolate([i, line[0]], [i + 1, line[1]])
)
}
console.log("Done");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment