Article View: comp.lang.c++
Article #1013A minimal nextafter()
From: Bonita Montero
Date: Mon, 23 Nov 2026 17:01
Date: Mon, 23 Nov 2026 17:01
35 lines
2274 bytes
2274 bytes
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.
Technical Details
Message-ID:
<11e1rge$22iab$1@raubtier-asyl.eternal-september.org>Path:
mbox-mo1.pugleaf.net!srv.newsdeef.eu!news.hispagatos.org!eternal-september.org!feeder.eternal-september.org!nntp.eternal-september.org!raubtier-asyl.eternal-september.org!.POSTED!not-for-mailShow Full Headers
Complete Article Headers
Path: mbox-mo1.pugleaf.net!srv.newsdeef.eu!news.hispagatos.org!eternal-september.org!feeder.eternal-september.org!nntp.eternal-september.org!raubtier-asyl.eternal-september.org!.POSTED!not-for-mail From: Bonita Montero <Bonita.Montero@gmail.com> Newsgroups: comp.lang.c++ Subject: A minimal nextafter() Date: Mon, 23 Nov 2026 18:01:02 +0100 Organization: A noiseless patient Spider Lines: 35 Message-ID: <11e1rge$22iab$1@raubtier-asyl.eternal-september.org> MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Mon, 23 Nov 2026 17:01:03 +0000 (UTC) Injection-Info: raubtier-asyl.eternal-september.org; logging-data="2181451"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/MgGjKRH+/vB99kcYJ3TyCoHv/9beg5+Y="; posting-host="6d91dc74f77a8fc154aca66c0d8ca15e" User-Agent: Mozilla Thunderbird Cancel-Lock: sha1:X0dnK1mkCQ1Q3wqpYINj9GnZ2Ac= sha256:aaw1HrKpI9vFq63DwHcrO/PXVDRzTt119a9GMWKtdjM= sha1:np++5iaSq4Sn9uMtvZ7vt3XsH90= sha256:PSilLFm+f/g/csjlYYwcXMv83aPNp+AXzTsJ0AyL2wk= Content-Language: de-DE