C++ Algorithm to Compute the One-Dimensional (Linear) Interpolat

  • 时间:2020-09-27 14:36:16
  • 分类:网络文摘
  • 阅读:159 次

Consider the time series of measurements m = [40.0, 41.0, 40.0, 45.0] and time points t1 = [0.0, 1.1, 1.9, 3.0] respectively and another sequence of time points t2 = [0.4, 0.7, 1.8, 2.9, 3.3].

Write a function to, where possible, return the one-dimensional interpolated values of m at t2.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
double interpolated(double targetValue, double x1, double x2, double y1, double y2) {
    auto x = x2 - x1;
    return (targetValue - x1) / x * y1 + (x2 - targetValue) / x * y2;
}
 
// assume m and t1 is sorted in non-descending order
vector<double> linearPolated(const vector<double> &t1, const vector<double> &m, const vector<double> &t2) {
    auto sz_t1 = t1.size();
    auto sz_m = m.size();
    // input sizes of t1 and m should be equal
    assert(sz_t1 == sz_m);
    auto sz_t2 = t2.size();
    vector<double> r;
    r.reserve(sz_t2);
    for (const auto &n: t2) {
        int j = 0;
        for (int i = 0; i < sz_t1 - 1; ++ i) {
            if (n >= t1[i] && n <= t1[i + 1]) {
                j = i;
                break;
            }
        }
        // TODO: check how interpolation actually works.
        auto nv = interpolated(n, t1[j], t1[j + 1], m[j], m[j + 1]);
        r.push_back(nv);
    }
    return r;
}
double interpolated(double targetValue, double x1, double x2, double y1, double y2) {
    auto x = x2 - x1;
    return (targetValue - x1) / x * y1 + (x2 - targetValue) / x * y2;
}

// assume m and t1 is sorted in non-descending order
vector<double> linearPolated(const vector<double> &t1, const vector<double> &m, const vector<double> &t2) {
    auto sz_t1 = t1.size();
    auto sz_m = m.size();
    // input sizes of t1 and m should be equal
    assert(sz_t1 == sz_m);
    auto sz_t2 = t2.size();
    vector<double> r;
    r.reserve(sz_t2);
    for (const auto &n: t2) {
        int j = 0;
        for (int i = 0; i < sz_t1 - 1; ++ i) {
            if (n >= t1[i] && n <= t1[i + 1]) {
                j = i;
                break;
            }
        }
        // TODO: check how interpolation actually works.
        auto nv = interpolated(n, t1[j], t1[j + 1], m[j], m[j + 1]);
        r.push_back(nv);
    }
    return r;
}

Note: above C++ code may not have been tested.

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
绿色食品与有机食品的联系和区别  盘点人体需要的11种膳食营养补充剂  食品安全事件:商家无良心消费不放心  食药总局启动《食品安全法》修订工作  炎炎夏日怎样选择冰棍雪糕更安全?  问题“毒皮蛋”再引食品安全大讨论  教你六招辨别保健食品真假的方法  警惕保健食品的五大非法宣传“陷阱”  官员竟然称质疑转基因食品是民众无知  转基因食品的利与弊及潜在危害浅析 
评论列表
添加评论