Created
July 3, 2024 17:40
-
-
Save lafkpages/fa742827fef07962239b9e4a20c4dfea to your computer and use it in GitHub Desktop.
Modifies the global sine function to interpolate between randomly generated points.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const points = {}; | |
const amplitude = 15; | |
// For polynomial interpolation | |
const interpolationLeft = 3; | |
const interpolationRight = 3; | |
// When true, uses polynomial interpolation | |
// Otherwise, uses linear interpolation | |
const usePolynomialInterpolation = true; | |
function ensurePointsAt(x) { | |
if (!(x in points)) { | |
points[x] = 2 * amplitude * Math.random() - amplitude; | |
} | |
} | |
function linearInterpolation(t, a, b) { | |
return t * b + (1 - t) * a; | |
} | |
function polynomialInterpolation(x, xn, yn) { | |
let y = 0; | |
for (let i = 0; i < xn.length; i++) { | |
let n = 1; | |
for (let j = 0; j < xn.length; j++) { | |
if (i !== j) { | |
n *= (x - xn[j]) / (xn[i] - xn[j]); | |
} | |
} | |
y += n * yn[i]; | |
} | |
return y; | |
} | |
if (usePolynomialInterpolation) { | |
Math.sin = (x) => { | |
const nearestInt = Math.floor(x); | |
// Gather datapoints | |
const xn = []; | |
const yn = []; | |
for ( | |
let i = nearestInt - interpolationLeft; | |
i < nearestInt + interpolationRight; | |
i++ | |
) { | |
xn.push(i); | |
ensurePointsAt(i); | |
yn.push(points[i]); | |
} | |
// Interpolate | |
return polynomialInterpolation(x, xn, yn); | |
}; | |
} else { | |
Math.sin = (x) => { | |
const nearestInt = Math.floor(x); | |
const nextNearest = nearestInt + 1; | |
// Ensure the closest random | |
// points are generated | |
ensurePointsAt(nearestInt); | |
ensurePointsAt(nextNearest); | |
// Interpolate between the closest random points | |
return linearInterpolation( | |
x - nearestInt, | |
points[nearestInt], | |
points[nextNearest], | |
); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment