| 1 |
// Copyright Nick Thompson 2019. |
| 2 |
// Use, modification and distribution are subject to the |
| 3 |
// Boost Software License, Version 1.0. (See accompanying file |
| 4 |
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) |
| 5 |
|
| 6 |
#ifndef BOOST_MATH_DISTRIBUTIONS_EMPIRICAL_CUMULATIVE_DISTRIBUTION_FUNCTION_HPP |
| 7 |
#define BOOST_MATH_DISTRIBUTIONS_EMPIRICAL_CUMULATIVE_DISTRIBUTION_FUNCTION_HPP |
| 8 |
#include <algorithm> |
| 9 |
#include <iterator> |
| 10 |
#include <stdexcept> |
| 11 |
#include <type_traits> |
| 12 |
#include <utility> |
| 13 |
|
| 14 |
#include <boost/math/tools/is_standalone.hpp> |
| 15 |
#ifndef BOOST_MATH_STANDALONE |
| 16 |
#include <boost/config.hpp> |
| 17 |
#ifdef BOOST_MATH_NO_CXX17_IF_CONSTEXPR |
| 18 |
#error "The header <boost/math/norms.hpp> can only be used in C++17 and later." |
| 19 |
#endif |
| 20 |
#endif |
| 21 |
|
| 22 |
namespace boost { namespace math{ |
| 23 |
|
| 24 |
template<class RandomAccessContainer> |
| 25 |
class empirical_cumulative_distribution_function { |
| 26 |
using Real = typename RandomAccessContainer::value_type; |
| 27 |
public: |
| 28 |
empirical_cumulative_distribution_function(RandomAccessContainer && v, bool sorted = false) |
| 29 |
{ |
| 30 |
if (v.size() == 0) { |
| 31 |
throw std::domain_error("At least one sample is required to compute an empirical CDF."); |
| 32 |
} |
| 33 |
m_v = std::move(v); |
| 34 |
if (!sorted) { |
| 35 |
std::sort(m_v.begin(), m_v.end()); |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
auto operator()(Real x) const { |
| 40 |
if constexpr (std::is_integral_v<Real>) |
| 41 |
{ |
| 42 |
if (x < m_v[0]) { |
| 43 |
return static_cast<double>(0); |
| 44 |
} |
| 45 |
if (x >= m_v[m_v.size()-1]) { |
| 46 |
return static_cast<double>(1); |
| 47 |
} |
| 48 |
auto it = std::upper_bound(m_v.begin(), m_v.end(), x); |
| 49 |
return static_cast<double>(std::distance(m_v.begin(), it))/static_cast<double>(m_v.size()); |
| 50 |
} |
| 51 |
else |
| 52 |
{ |
| 53 |
if (x < m_v[0]) { |
| 54 |
return Real(0); |
| 55 |
} |
| 56 |
if (x >= m_v[m_v.size()-1]) { |
| 57 |
return Real(1); |
| 58 |
} |
| 59 |
auto it = std::upper_bound(m_v.begin(), m_v.end(), x); |
| 60 |
return static_cast<Real>(std::distance(m_v.begin(), it))/static_cast<Real>(m_v.size()); |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
RandomAccessContainer&& return_data() { |
| 65 |
return std::move(m_v); |
| 66 |
} |
| 67 |
|
| 68 |
private: |
| 69 |
RandomAccessContainer m_v; |
| 70 |
}; |
| 71 |
|
| 72 |
}} |
| 73 |
#endif |