Last active
April 27, 2024 16:03
-
-
Save gpiffault/10556503 to your computer and use it in GitHub Desktop.
Javascript piecewise function factory
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
function Piecewise(xs, ys) { | |
return function(x) { | |
//bisect | |
var lo = 0, hi = xs.length - 1; | |
while (hi - lo > 1) { | |
var mid = (lo + hi) >> 1; | |
if (x < xs[mid]) hi = mid; | |
else lo = mid; | |
} | |
//project | |
return ys[lo] + (ys[hi] - ys[lo]) / (xs[hi] - xs[lo]) * (x - xs[lo]); | |
}; | |
} |
Thanks, i will use it.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice, It could be a small npm module.