问题
I have known data points and their values described as arrays, speed
and power
speed = [2, 6, 8, 10, 12]
power = [200, 450, 500, 645, 820],
I want to estimate the power value that corresponds to speed value (e.g. 7) that is not listed within source array (2 through 12).
I.e. I am seeking a way to perform interpolation
回答1:
The simplest way to do that is to perceive your power-from-speed dependency as a collection of lines and assuming your target point falls between two known points of a certain line, calculate the value.
E.g. you may do the following:
const speed = [2, 6, 8, 10, 12], power = [200, 450, 500, 645, 820]
const interpolate = (xarr, yarr, xpoint) => {
const xa = [...xarr].reverse().find(x => x<=xpoint),
xb = xarr.find(x => x>= xpoint),
ya = yarr[xarr.indexOf(xa)],
yb =yarr[xarr.indexOf(xb)]
return yarr[xarr.indexOf(xpoint)] || ya+(xpoint-xa)*(yb-ya)/(xb-xa)
}
console.log(interpolate(speed,power,7))
.as-console-wrapper{min-height:100%}
来源:https://stackoverflow.com/questions/59264119/how-do-i-interpolate-the-value-in-certain-data-point-by-array-of-known-points