A minimal nextafter()
From
Bonita Montero@3:633/10 to
All on Mon Nov 23 18:01:02 2026
template<bool Up, typename Fp>
constexpr Fp fp_next( Fp v ) noexcept
{
using namespace std;
static_assert( is_floating_point_v<Fp> );
constexpr bool Dbl = is_same_v<Fp, double>;
using word = conditional_t<Dbl, uint64_t, uint32_t>;
using sword = make_signed_t<word>;
constexpr word
Sign = Dbl ? 1ull << 63 : 1u << 31,
Exp = Dbl ? 0x7FFull << 52 : 0xFFu << 23;
sword sBin = bit_cast<word>( v );
word uBin = sBin & ~Sign;
sword mxDiff = uBin - Exp;
if( mxDiff > 0 ) [[unlikely]] // NaN
return v;
if( !uBin ) [[unlikely]] // +/-0
sBin = Up ? 0 : Sign;
bool toInf = (sBin < 0) ^ Up;
if( !mxDiff && toInf ) [[unlikely]] // +/-Inf -> +/-Inf
return v;
sBin += toInf ? 1 : -1;
if( word exp = sBin & Exp; // result == inf / denormal
exp == Exp || !exp ) [[unlikely]]
{
if constexpr( (math_errhandling & MATH_ERREXCEPT) )
feraiseexcept( FE_INEXACT | (exp == Exp ? FE_OVERFLOW : FE_UNDERFLOW) );
if constexpr( (math_errhandling & MATH_ERRNO) )
errno = ERANGE;
}
return bit_cast<Fp>( sBin );
}
A bit different sicne the direction is a template bool.
--- PyGate Linux v1.5.19
* Origin: Dragon's Lair, PyGate NNTP<>Fido Gate (3:633/10)