Skip to content

Commit 715567d

Browse files
authored
[libc++] simplify the midpoint function (#81717)
Right now we've a nested ternary for the midpoint function, but this can be simplified a bit more, using if statements. This also slightly increases the readability of that function.
1 parent 97eff26 commit 715567d

File tree

1 file changed

+10
-8
lines changed

1 file changed

+10
-8
lines changed

libcxx/include/__numeric/midpoint.h

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -67,14 +67,16 @@ template <class _Fp>
6767
_LIBCPP_HIDE_FROM_ABI constexpr enable_if_t<is_floating_point_v<_Fp>, _Fp> midpoint(_Fp __a, _Fp __b) noexcept {
6868
constexpr _Fp __lo = numeric_limits<_Fp>::min() * 2;
6969
constexpr _Fp __hi = numeric_limits<_Fp>::max() / 2;
70-
return std::__fp_abs(__a) <= __hi && std::__fp_abs(__b) <= __hi
71-
? // typical case: overflow is impossible
72-
(__a + __b) / 2
73-
: // always correctly rounded
74-
std::__fp_abs(__a) < __lo ? __a + __b / 2 : // not safe to halve a
75-
std::__fp_abs(__b) < __lo ? __a / 2 + __b
76-
: // not safe to halve b
77-
__a / 2 + __b / 2; // otherwise correctly rounded
70+
71+
// typical case: overflow is impossible
72+
if (std::__fp_abs(__a) <= __hi && std::__fp_abs(__b) <= __hi)
73+
return (__a + __b) / 2; // always correctly rounded
74+
if (std::__fp_abs(__a) < __lo)
75+
return __a + __b / 2; // not safe to halve a
76+
if (std::__fp_abs(__b) < __lo)
77+
return __a / 2 + __b; // not safe to halve b
78+
79+
return __a / 2 + __b / 2; // otherwise correctly rounded
7880
}
7981

8082
#endif // _LIBCPP_STD_VER >= 20

0 commit comments

Comments
 (0)