Vanetza
 
Loading...
Searching...
No Matches
unit_interval.hpp
1#ifndef UNIT_INTERVAL_HPP_BG1EK7QX
2#define UNIT_INTERVAL_HPP_BG1EK7QX
3
4#include <boost/operators.hpp>
5#include <iterator>
6#include <type_traits>
7
8namespace vanetza
9{
10
11/**
12 * UnitInterval represents a number within the unit interval [0.0, 1.0]
13 *
14 * UnitInterval is not an interval on its own but limits all numbers to this interval.
15 * Mantissa (positive fractional part of a real number) behaves differently, thus:
16 * - Mantissa(42.1234) = 0.1234
17 * - UnitInterval(42.1234) = 1.0
18 * UnitInterval is also related to "(proper) decimal fraction" but latter does not include 1.0.
19 */
21 boost::arithmetic<UnitInterval>,
22 boost::arithmetic<UnitInterval, double>,
23 boost::totally_ordered<UnitInterval>
24{
25public:
26 constexpr UnitInterval() : UnitInterval(0.0) {}
27 constexpr explicit UnitInterval(double v) : m_value(clamp(v)) {}
28 UnitInterval(const UnitInterval&) = default;
29 UnitInterval& operator=(const UnitInterval&) = default;
30
31 // arithmetic
32 UnitInterval& operator+=(const UnitInterval&);
33 UnitInterval& operator-=(const UnitInterval&);
34 UnitInterval& operator*=(const UnitInterval&);
35 UnitInterval& operator/=(const UnitInterval&);
36
37 UnitInterval& operator+=(double);
38 UnitInterval& operator-=(double);
39 UnitInterval& operator*=(double);
40 UnitInterval& operator/=(double);
41
42 // partially ordered
43 bool operator<(const UnitInterval& other) const;
44 bool operator==(const UnitInterval& other) const;
45
46 double value() const { return m_value; }
47 UnitInterval complement() const;
48
49private:
50 constexpr static double clamp(double v)
51 {
52 return (v > 1.0 ? 1.0 : (v < 0.0 ? 0.0 : v));
53 }
54 UnitInterval& clamp();
55
56 double m_value;
57};
58
59/**
60 * Calculate mean value of two unit intervals
61 * \param lhs
62 * \param rhs
63 * \return mean unit interval
64 */
66
67/**
68 * Calculate mean of a range of unit intervals
69 * \param begin of range
70 * \params end of range
71 * \reutrn mean unit interval
72 */
73template<
74 typename Iterator,
75 typename std::enable_if<
76 std::is_convertible<typename std::iterator_traits<Iterator>::value_type, UnitInterval>::value,
77 int>::type = 0
78>
79UnitInterval mean(Iterator begin, Iterator end)
80{
81 unsigned count = 0;
82 double accu = 0.0;
83
84 for (Iterator it = begin; it != end; ++it)
85 {
86 accu += it->value();
87 ++count;
88 }
89
90 return UnitInterval { count > 1 ? (accu / count) : accu };
91}
92
93} // namespace vanetza
94
95#endif /* UNIT_INTERVAL_HPP_BG1EK7QX */
96