开发者

Interpolating "missing years" in JavaScript?

开发者 https://www.devze.com 2023-03-12 03:55 出处:网络
Before: idyearvalue SE195067 SE1960开发者_如何学Python71 SE196582 NO197565 NO198575 After: data : { SE : {

Before:

id   year  value
SE   1950  67
SE   1960  开发者_如何学Python71
SE   1965  82
NO   1975  65
NO   1985  75

After:

data : {
    SE : {
        data : {
             1950 : 67,
             1951 : 67.4,
             1952 : 67.8,
             [...]
             1965 : 82
        },
        min_year : 1950,
        max_year : 1965

    }    
    NO : {
        data : {
             [...]
        },
        [...]   
    }    
} 

So basically, what is the most effective way of filling the gaps/interpolating based on adjacent values in JS?


JS as a language has no tools to help you directly.

You can implement linear or polynomial interpolation quite easily. Polynomial (of degree say 3) will probably provide slightly nicer numbers in the middle, although the endpoints can be problematic - depends on the data.

Linear interpolation is easier although on the whole I would presume it wouldn't give as accurate an estimation as a higher degree polynomial interpolation.

An alternative could be splines (cubic are relatively easy) which will be more than accurate enough for your purposes. It might be slight overkill, although maybe not - not sure the scope of this requirement.

You might consider doing this server-side and using one of many libraries for other languages that implement these interpolatory functions. That would give you a really accurate and general way to solve the problem efficiently without having to implement it yourself.

It's difficult to say since the degree of accuracy, the range of data and the scope of the project all factor in to what type of interpolation you need, if it can be done server/client side, etc.


If you just want straight linear interpolation, then given n_0 and n_1 as indices for which you do know the values:

val[n] = val[n_0] + (n - n_0) * (val[n_1] - val[n_0]) / (n_1 - n_0);

Given your data for SE, for example, the interpolated value for 1960 would be:

67.8 + (1960 - 1952) * (82 - 67.8) / (1965 - 1952)

i.e. about 76.5

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号