Logo
Fully annotated reference manual - version 1.8.12
Loading...
Searching...
No Matches
interpolation.hpp
Go to the documentation of this file.
1/*
2 Copyright (C) 2022 Quaternion Risk Management Ltd
3 All rights reserved.
4
5 This file is part of ORE, a free-software/open-source library
6 for transparent pricing and risk analysis - http://opensourcerisk.org
7
8 ORE is free software: you can redistribute it and/or modify it
9 under the terms of the Modified BSD License. You should have received a
10 copy of the license along with this program.
11 The license is also available online at <http://opensourcerisk.org>
12
13 This program is distributed on the basis that it will form a useful
14 contribution to risk analytics and model standardisation, but WITHOUT
15 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
17*/
18
19/*! \file qle/utilities/time.hpp
20 \brief time related utilities.
21*/
22
23#pragma once
24
25#include <tuple>
26
27namespace QuantExt {
28
29/*! Given a non-empty container x of distinct and sorted values and a value v return a tuple (m,p,w) s.t.
30 w * y[m] + (1-w) * y[p]
31 linearly interpolates between points (x[0], y[0]), ..., (x[n], y[n]) and extrapolates flat at x = v.
32 It is m = p if and only if v <= x[0] or v >= x[n]. In this case we have w = 1 and
33 either m = p = 0 (if v <= [0]) or m = p = n (if v >= x[n]). */
34template <typename T> std::tuple<Size, Size, Real> interpolationIndices(const T& x, const Real v) {
35 QL_REQUIRE(!x.empty(), "interpolationIndices(x," << v << "): empty x");
36 if (x.size() == 1)
37 return std::make_tuple(0, 0, 1.0);
38 if (v < x.front() || QuantLib::close_enough(v, x.front()))
39 return std::make_tuple(0, 0, 1.0);
40 if (v > x.back() || QuantLib::close_enough(v, x.back()))
41 return std::make_tuple(x.size() - 1, x.size() - 1, 1.0);
42 Size index = std::distance(x.begin(), std::upper_bound(x.begin(), x.end(), v, [](Real x1, Real x2) {
43 return x1 < x2 && !QuantLib::close_enough(x1, x2);
44 }));
45 return std::make_tuple(index - 1, index, (x[index] - v) / (x[index] - x[index - 1]));
46}
47
48} // namespace QuantExt
std::tuple< Size, Size, Real > interpolationIndices(const T &x, const Real v)