File: interpolate.hpp

package info (click to toggle)
libfplus 0.2.13-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,904 kB
  • sloc: cpp: 27,543; javascript: 634; sh: 105; python: 103; makefile: 6
file content (45 lines) | stat: -rw-r--r-- 1,325 bytes parent folder | download | duplicates (3)
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Copyright 2015, Tobias Hermann and the FunctionalPlus contributors.
// https://github.com/Dobiasd/FunctionalPlus
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

#pragma once

#include <fplus/container_common.hpp>
#include <fplus/maybe.hpp>

#include <cmath>

namespace fplus
{

// API search type: elem_at_float_idx : (Float, [a]) -> a
// fwd bind count: 1
// Interpolates linearly between elements.
// xs must be non-empty.
template <typename Container,
    typename T = typename Container::value_type>
T elem_at_float_idx(double idx, const Container& xs)
{
    assert(is_not_empty(xs));
    if (idx <= 0.0)
    {
        return xs.front();
    }
    std::size_t idx_floor = static_cast<std::size_t>(floor(idx));
    std::size_t idx_ceil = static_cast<std::size_t>(ceil(idx));
    if (idx_ceil >= size_of_cont(xs))
    {
        return xs.back();
    }
    double idx_floor_float = static_cast<double>(idx_floor);
    double idx_ceil_float = static_cast<double>(idx_ceil);
    double weight_floor = idx_ceil_float - idx;
    double weight_ceil = idx - idx_floor_float;
    return
        (weight_floor * elem_at_idx(idx_floor, xs) +
            weight_ceil * elem_at_idx(idx_ceil, xs));
}

} // namespace fplus