Arene Base
Fundamental Utilities For Safety Critical C++
Loading...
Searching...
No Matches
ulp_distance.hpp
Go to the documentation of this file.
1// parasoft-begin-suppress AUTOSAR-A2_8_1-a "False positive: also defines arene::base::ulp_distance"
2// Copyright 2026, Toyota Motor Corporation
3//
4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5
6#ifndef INCLUDE_GUARD_ARENE_BASE_ARENE_BASE_MATH_ULP_DISTANCE_HPP_
7#define INCLUDE_GUARD_ARENE_BASE_ARENE_BASE_MATH_ULP_DISTANCE_HPP_
8
9// parasoft-begin-suppress AUTOSAR-A16_2_2-a "Arene Base aggregate headers permitted by A16-2-2 Permit #1"
12#include "arene/base/detail/is_representable_as.hpp"
15#include "arene/base/result.hpp"
16#include "arene/base/stdlib_choice/cstdint.hpp"
17#include "arene/base/stdlib_choice/enable_if.hpp"
18#include "arene/base/stdlib_choice/is_integral.hpp"
19#include "arene/base/stdlib_choice/is_same.hpp"
20#include "arene/base/stdlib_choice/is_signed.hpp"
21#include "arene/base/stdlib_choice/make_signed.hpp"
22#include "arene/base/stdlib_choice/make_unsigned.hpp"
23#include "arene/base/stdlib_choice/numeric_limits.hpp"
28// parasoft-end-suppress AUTOSAR-A16_2_2-a
29
30// Due to issue https://github.com/include-what-you-use/include-what-you-use/issues/1127
31// IWYU pragma: no_include "arene/base/type_manipulation/static_if.hpp"
32
33namespace arene {
34namespace base {
35
36/// @brief determines if a type can be compared with @c ulp_distance
37///
38/// Users may specialize @c enable_ulp_distance_comparable for cv-unqualified
39/// program-defined types.
40///
41/// A type that is ULP distance comparable must:
42/// * be an implicit lifetime type
43/// * be bit-castable to a signed integer type with the same number of bits
44/// * use an IEEE 754 bit representation, where the sign bit is the most
45/// significant bit and the magnitude is ordered such that adjacent
46/// representable values have adjacent integer representations
47///
48/// If a program specializes @c enable_ulp_distance_comparable to @c true for a
49/// type that does not meet the requirements listed above, the behaviour is
50/// undefined.
51template <class T, class = constraints<>>
52extern constexpr bool enable_ulp_distance_comparable = false;
53
54/// @brief determines if a type can be compared with @c ulp_distance
55/// Specialization enabled for @c float and @c double, conditional on IEC 559 conformance
56template <class T>
57extern constexpr bool enable_ulp_distance_comparable<
58 T,
61
62/// @brief enumeration used in the result error type of @c ulp_distance to
63///
64/// Provides the error reason if @c ulp_distance cannot return a ULP distance
65/// between two values.
67 /// @brief one of the arguments is incomparable
69 /// @brief the ULP distance is not representable in the specifed result value type
71};
72
73namespace ulp_distance_detail {
74
75/// @brief obtain the most significant bit of a signed integer
76/// @param value integer value
77/// @return @c true if the most significant bit is set, @c false otherwise
78template <class I>
79constexpr auto most_significant_bit(I const& value) noexcept -> bool {
80 return value < I{};
81}
82
83/// @brief function object to determine the distance in units in last place (bits)
84/// @tparam ResultValue signed integral type used for the result value
85template <class ResultValue>
86class ulp_distance_fn {
87 /// @brief obtain the unsigned integer type with the same number of bytes
88 /// @tparam T type whose size determines the resulting unsigned integer type
89 template <class T>
90 using unsigned_integer_for_t = smallest_unsigned_integer_for_type<T>;
91
92 /// @brief converts an integer to a result, checking representability
93 /// @tparam T integer type to convert from
94 /// @param value integer value to convert
95 /// @return @c value converted to @c ResultValue on success, or
96 /// @c ulp_distance_error::distance_not_representable if @c value
97 /// cannot be represented in @c ResultValue.
98 template <class T>
99 static constexpr auto to_result(T const& value) noexcept -> result<ResultValue, ulp_distance_error> {
100 if (!detail::is_representable_as<ResultValue>(value)) {
101 return {in_place_error, ulp_distance_error::distance_not_representable};
102 }
103 return {in_place_value, static_cast<ResultValue>(value)};
104 }
105
106 public:
107 static_assert(std::is_signed<ResultValue>::value, "'ResultValue' must be a signed type.");
108 static_assert(std::is_integral<ResultValue>::value, "'ResultValue' must be an integer type.");
109
110 /// @brief result type for @c ulp_distance
111 using result_type = result<ResultValue, ulp_distance_error>;
112
113 /// @brief returns the distance in units in last place (bits)
114 /// @tparam T floating-point type to compare
115 /// @param left first value to compare
116 /// @param right second value to compare
117 ///
118 /// Returns the distance between @c x and @c y in terms of units in last
119 /// place. The sign of the result indicates direction: positive if
120 /// @c x < @c y, negative if @c x > @c y.
121 ///
122 /// @return A result containing:
123 /// - the signed ULP distance from @c x to @c y on success.
124 /// - @c ulp_distance_error::unordered_argument if either @c x or @c y is
125 /// incomparable
126 /// - @c ulp_distance_error::distance_not_representable if the distance
127 /// cannot be represented in @c ResultValue
128 ///
129 /// @post If the result has a value, let <c> lower = min(x, y) </c> and
130 /// <c> upper = max(x, y) </c>. Then <c> abs(result.value()) </c>
131 /// equals the number of successive @c std::nextafter(lower, upper)
132 /// calls needed to reach @c upper from @c lower.
133 ///
134 /// @note @c +0.0 and @c -0.0 are treated as 0 ULPs apart, consistent
135 /// with IEEE 754 equality.
136 template <
137 class T,
144 T const& //
145 > //
146 > //
147 > = nullptr>
148 ARENE_BIT_CAST_CONSTEXPR auto operator()(T const& left, T const& right) const noexcept -> result_type {
149 if (::arene::base::isnan(left) || ::arene::base::isnan(right)) {
150 return {in_place_error, ulp_distance_error::unordered_argument};
151 }
152
153 using unsigned_integer_type = unsigned_integer_for_t<T>;
154 using signed_integer_type = std::make_signed_t<unsigned_integer_type>;
155
156 constexpr auto as_bits = bit_cast<signed_integer_type>;
157
158 auto const left_bits = as_bits(math::abs(left));
159 auto const right_bits = as_bits(math::abs(right));
160
161 auto const left_signbit = most_significant_bit(as_bits(left));
162 auto const right_signbit = most_significant_bit(as_bits(right));
163
164 if (left_signbit == right_signbit) {
165 // 'left_bits' and 'right_bits' are both non-negative (bit-casts of absolute
166 // values), so their difference cannot overflow a signed subtraction.
167 auto const dist = left_bits - right_bits;
168 return left_signbit ? to_result(dist) : to_result(-dist);
169 }
170
171 auto const dist = static_cast<unsigned_integer_type>(
172 static_cast<unsigned_integer_type>(left_bits) + static_cast<unsigned_integer_type>(right_bits)
173 );
174
175 if (right < left) {
176 using unsigned_result = std::make_unsigned_t<ResultValue>;
177 constexpr unsigned_result max_abs_lowest{
178 static_cast<unsigned_result>(std::numeric_limits<ResultValue>::max()) + unsigned_result{1U}
179 };
180
181 if (cmp_less(max_abs_lowest, dist)) {
182 return {in_place_error, ulp_distance_error::distance_not_representable};
183 }
184
185 // Negate in unsigned_result space to avoid truncation when
186 // unsigned_integer_type is narrower than ResultValue (e.g. uint32_t vs
187 // uint64_t). The result is then reinterpreted as a signed value via two's
188 // complement, which correctly represents the minimum value of ResultValue
189 // (e.g. -128 for int8_t) that has no positive counterpart.
190 return {
191 in_place_value,
192 static_cast<ResultValue>(static_cast<unsigned_result>(-static_cast<unsigned_result>(dist)))
193 };
194 }
195
196 return to_result(dist);
197 }
198};
199} // namespace ulp_distance_detail
200
201/// @brief Compute the distance in units in the last place between two floating-point values.
202/// @tparam ResultValue signed integral type used for the result value, defaults to @c std::int64_t
203template <class ResultValue = std::int64_t>
204extern constexpr auto ulp_distance = ulp_distance_detail::ulp_distance_fn<ResultValue>{};
205
206} // namespace base
207} // namespace arene
208#endif // INCLUDE_GUARD_ARENE_BASE_ARENE_BASE_MATH_ULP_DISTANCE_HPP_
#define ARENE_BIT_CAST_CONSTEXPR
Definition bit_cast.hpp:31
static constexpr value_type value
Definition integral_constant.hpp:34
static constexpr bool is_iec559
For floating point types, true if the type adheres to the IEC559 standard, otherwise false.
Definition numeric_limits.hpp:221
static constexpr auto max() noexcept -> T
The maximum finite value.
Definition numeric_limits.hpp:230
Definition accumulate.hpp:37
constexpr bool is_invocable_v
Determine if a functor type is invocable with the specified argument types.
constexpr bool enable_ulp_distance_comparable
determines if a type can be compared with ulp_distance
constexpr bit_cast_detail::do_bit_cast< To > bit_cast
Reinterpret the object representation of one type as that of another.
ulp_distance_error
enumeration used in the result error type of ulp_distance to
Definition ulp_distance.hpp:66
@ distance_not_representable
the ULP distance is not representable in the specifed result value type
Definition ulp_distance.hpp:70
@ unordered_argument
one of the arguments is incomparable
Definition ulp_distance.hpp:68
typename constraints_impl::constraints< EnableIfs... >::type constraints
Helper used to express template constraints in a consistent way using std::enable_if_t.
Definition constraints.hpp:51
constexpr auto ulp_distance
Compute the distance in units in the last place between two floating-point values.
smallest_unsigned_integer_for< 1ULL<<(sizeof(T) *CHAR_BIT - 1)> smallest_unsigned_integer_for_type
Calculates the smallest unsigned integer type that can be used to hold values of type T.
Definition smallest_integer_for.hpp:49
Definition accumulate.hpp:36
typename make_signed< Type >::type make_signed_t
A type alias for the equivalent signed type for integral and enumeration types other than bool.
Definition make_signed.hpp:252
::uint8_t uint8_t
An 8-bit unsigned integer type.
Definition cstdint.hpp:30
typename enable_if< Condition, Type >::type enable_if_t
Type alias to support constraining templates. Is an alias for the specified type if the Condition is ...
Definition enable_if.hpp:41
typename make_unsigned< Type >::type make_unsigned_t
A type alias for the equivalent unsigned type for integral and enumeration types other than bool.
Definition make_unsigned.hpp:252
Public export header for the result subpackage.
Provides backports of the safe integer comparison functions from C++20.