tetl 0.1.0
Embedded Template Library
Loading...
Searching...
No Matches
midpoint.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: BSL-1.0
2#ifndef TETL_NUMERIC_MIDPOINT_HPP
3#define TETL_NUMERIC_MIDPOINT_HPP
4
13
14namespace etl {
15
26template <typename Int>
28constexpr auto midpoint(Int a, Int b) noexcept -> Int
29{
30 using UInt = etl::make_unsigned_t<Int>;
31
32 auto const shift = static_cast<UInt>(etl::numeric_limits<UInt>::digits - 1);
33 auto const diff = static_cast<UInt>(UInt(b) - UInt(a));
34 auto const sign = static_cast<UInt>(b < a);
35 auto const half = static_cast<UInt>((diff / 2) + (sign << shift) + (sign & diff));
36
37 return a + static_cast<Int>(half);
38}
39
41template <etl::floating_point Float>
42constexpr auto midpoint(Float a, Float b) noexcept -> Float
43{
44 auto const lo = etl::numeric_limits<Float>::min() * 2;
45 auto const hi = etl::numeric_limits<Float>::max() / 2;
46
47 if (etl::abs(a) <= hi and etl::abs(b) <= hi) {
48 return (a + b) / 2;
49 }
50 if (etl::abs(a) < lo) {
51 return a + b / 2;
52 }
53 if (etl::abs(b) < lo) {
54 return a / 2 + b;
55 }
56
57 return a / 2 + b / 2;
58}
59
61template <typename Ptr>
63constexpr auto midpoint(Ptr a, Ptr b) noexcept -> Ptr
64{
65 return a + etl::midpoint(etl::ptrdiff_t(0), b - a);
66}
67
68} // namespace etl
69
70#endif // TETL_NUMERIC_MIDPOINT_HPP
constexpr auto abs(complex< T > const &z) -> T
Definition abs.hpp:13
constexpr auto midpoint(Int a, Int b) noexcept -> Int
Returns half the sum of a + b. If the sum is odd, the result is rounded towards a.
Definition midpoint.hpp:28
Definition adjacent_find.hpp:8
constexpr bool is_integral_v
Definition is_integral.hpp:28
constexpr bool is_pointer_v
Definition is_pointer.hpp:30
constexpr bool is_same_v
Definition is_same.hpp:11
typename make_unsigned< T >::type make_unsigned_t
Definition make_unsigned.hpp:75
TETL_BUILTIN_PTRDIFF ptrdiff_t
etl::ptrdiff_t is the signed integer type of the result of subtracting two pointers.
Definition ptrdiff_t.hpp:14
Definition half.hpp:15
static constexpr int digits
Definition numeric_limits.hpp:24
static constexpr auto max() noexcept
Definition numeric_limits.hpp:21
static constexpr auto min() noexcept
Definition numeric_limits.hpp:20