fixed_point128 1.0.1.0
128 bit integer, fixed point and floating point arithmetic for C++20
Loading...
Searching...
No Matches
float128.h
Go to the documentation of this file.
1/***********************************************************************************
2 MIT License
3
4 Copyright (c) 2025 Eric Gur (ericgur@iname.com)
5
6 Permission is hereby granted, free of charge, to any person obtaining a copy
7 of this software and associated documentation files (the "Software"), to deal
8 in the Software without restriction, including without limitation the rights
9 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 copies of the Software, and to permit persons to whom the Software is
11 furnished to do so, subject to the following conditions:
12
13 The above copyright notice and this permission notice shall be included in all
14 copies or substantial portions of the Software.
15
16 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 SOFTWARE.
23************************************************************************************/
24
25/***********************************************************************************
26 Acknologements
27 The function div_128bit is derived from the book "Hacker's Delight" 2nd Edition
28 by Henry S. Warren Jr. It implements Knuth's "Algorithm D", specialized to a 128 bit
29 divisor and written in 64 bit limbs.
30
31 The functions log, log2, log10 are derived from Dan Moulding's code:
32 https://github.com/dmoulding/log2fix
33
34 The function sqrt is based on the book "Math toolkit for real time programming"
35 by Jack W. Crenshaw. The sin/cos/atan functions use some ideas from the book.
36
37************************************************************************************/
38
39/**
40 * @file float128.h
41 * @brief 128-bit IEEE 754-2008 quadruple-precision floating-point type.
42 *
43 * Provides the @ref fp128::float128 class with the same bit layout as
44 * IEEE 754 binary128: 112-bit fraction, 15-bit exponent, and 1-bit sign.
45 * Supports full arithmetic, comparison, and conversion operators, as well as
46 * a comprehensive set of math functions (sqrt, cbrt, sin, cos, tan, asin,
47 * acos, atan, atan2, sinh, cosh, tanh, asinh, acosh, atanh, exp, exp2, log,
48 * log2, log10, pow, erf, erfc, etc.).
49 * All methods are inline for maximum performance.
50 *
51 * The arithmetic, the conversions and the operations of IEEE 754-2008 clause 5 are correctly
52 * rounded. The rounding directions and exception flags the standard also requires are opt in,
53 * through FP128_IEEE_ENV; see the floating point environment section below.
54 *
55 * @see fp128_shared.h for supporting intrinsics and utilities.
56 */
57
58#ifndef FP128_FLOAT128_H
59#define FP128_FLOAT128_H
60
61#include <algorithm>
62#include <array>
63#include <cfenv> // FE_ rounding directions and exception flags, which the float128 environment reuses
64#include <cfloat> // LDBL_MANT_DIG, which selects the long double conversion
65#include <cmath> // FP_NAN and friends, and the double seeds of sqrt/cbrt
66#include <climits> // INT_MAX, the ilogb answer for an infinity
67#include <cstdlib> // strtoull, for the nan() payload
68#include <charconv> // to_chars_result, from_chars_result, chars_format
69#include <format> // std::formatter
70#include <functional> // std::hash
71#include <istream>
72#include <limits>
73#include <memory> // std::unique_ptr, for the workspace of a decimal input past forty digits
74#include <new> // std::nothrow
75#include <ostream>
76#include "fp128_shared.h"
77#include "fp128_decimal.h"
78#include "uint128_t.h"
79
80namespace fp128
81{
82/***********************************************************************************
83 * Forward declarations
84 ************************************************************************************/
85
86class fp128_gtest; // Google test class
87class float128;
88
89/// @brief Reads a decimal string into a float128. Defined below, declared here because the
90/// constructor from a string delegates to it.
91std::from_chars_result from_chars(const char* first, const char* last, float128& value);
92/// @brief Reads a decimal or hexadecimal string into a float128. Defined below.
93std::from_chars_result from_chars(const char* first, const char* last, float128& value, std::chars_format fmt);
94
95namespace detail
96{
97/// @brief Renders a float128 as text. Defined below, declared here because the conversions to a
98/// string delegate to it.
99[[nodiscard]] std::string render(const float128& value, char style, int32_t precision, bool uppercase, bool alternate, char sign_char,
100 bool bare_hex = false);
101} // namespace detail
102
103/// @brief User-defined literal for constructing float128 from a string.
104float128 operator""_f128(const char*);
105
106/// @name CRT-Style Math Functions (Forward Declarations)
107/// @brief Free functions providing standard math library equivalents for float128.
108/// @{
109constexpr float128 fabs(const float128& x) noexcept;
110constexpr float128 floor(const float128& x) noexcept;
111constexpr float128 ceil(const float128& x) noexcept;
112constexpr float128 trunc(const float128& x) noexcept;
113constexpr float128 round(const float128& x) noexcept;
114constexpr int64_t llrint(const float128& x) noexcept;
115constexpr int64_t llround(const float128& x) noexcept;
116constexpr int32_t lrint(const float128& x) noexcept;
117constexpr int32_t lround(const float128& x) noexcept;
118constexpr int32_t ilogb(const float128& x) noexcept;
119constexpr float128 copysign(const float128& x, const float128& y) noexcept;
120float128 fmod(const float128& x, const float128& y) noexcept;
121constexpr float128 modf(const float128& x, float128* iptr) noexcept;
122constexpr float128 fdim(const float128& x, const float128& y) noexcept;
123constexpr float128 fmin(const float128& x, const float128& y) noexcept;
124constexpr float128 fmax(const float128& x, const float128& y) noexcept;
125constexpr float128 fma(float128 x, float128 y, float128 z) noexcept;
126float128 hypot(const float128& x, const float128& y) noexcept;
127float128 cbrt(const float128 x, uint32_t iterations = 2) noexcept;
128float128 sqrt(const float128& x, uint32_t iterations = 3) noexcept;
129float128 erf(float128 x) noexcept;
130float128 erfc(float128 x) noexcept;
131float128 sin(float128 x) noexcept;
132float128 asin(float128 x) noexcept;
133float128 cos(float128 x) noexcept;
134float128 acos(float128 x) noexcept;
135float128 tan(float128 x) noexcept;
136float128 atan(float128 x) noexcept;
137float128 atan2(float128 y, float128 x) noexcept;
138float128 sinh(float128 x) noexcept;
139float128 asinh(float128 x) noexcept;
140float128 cosh(float128 x) noexcept;
141float128 acosh(float128 x) noexcept;
142float128 tanh(float128 x) noexcept;
143float128 atanh(float128 x) noexcept;
144float128 exp(const float128& x) noexcept;
145float128 exp2(const float128& x) noexcept;
146float128 expm1(const float128& x) noexcept;
147float128 pow(const float128& x, const float128& y) noexcept;
148float128 pow(const float128& x, int32_t y) noexcept;
149float128 log(float128 x) noexcept;
150float128 log2(float128 x) noexcept;
151float128 log10(float128 x) noexcept;
152float128 logb(float128 x) noexcept;
153float128 log1p(float128 x) noexcept;
154constexpr float128 frexp(float128 x, int* expptr) noexcept;
155constexpr float128 ldexp(float128 x, int exp) noexcept;
156constexpr bool isfinite(const float128& x) noexcept;
157constexpr bool signbit(const float128& x) noexcept;
158constexpr bool isnormal(const float128& x) noexcept;
159constexpr int fpclassify(const float128& x) noexcept;
160constexpr bool isunordered(const float128& x, const float128& y) noexcept;
161constexpr bool isgreater(const float128& x, const float128& y) noexcept;
162constexpr bool isgreaterequal(const float128& x, const float128& y) noexcept;
163constexpr bool isless(const float128& x, const float128& y) noexcept;
164constexpr bool islessequal(const float128& x, const float128& y) noexcept;
165constexpr bool islessgreater(const float128& x, const float128& y) noexcept;
166constexpr float128 rint(const float128& x) noexcept;
167constexpr float128 nearbyint(const float128& x) noexcept;
168constexpr float128 scalbn(const float128& x, int n) noexcept;
169constexpr float128 scalbln(const float128& x, long n) noexcept;
170constexpr float128 nextafter(const float128& x, const float128& y) noexcept;
171constexpr float128 nexttoward(const float128& x, const float128& y) noexcept;
172float128 remainder(const float128& x, const float128& y) noexcept;
173float128 remquo(const float128& x, const float128& y, int* quo) noexcept;
174float128 hypot(const float128& x, const float128& y, const float128& z) noexcept;
175float128 lgamma(float128 x) noexcept;
176float128 tgamma(float128 x) noexcept;
177constexpr float128 abs(const float128& x) noexcept;
178constexpr bool totalorder(const float128& x, const float128& y) noexcept;
179constexpr bool totalordermag(const float128& x, const float128& y) noexcept;
180constexpr float128 fmaxmag(const float128& x, const float128& y) noexcept;
181constexpr float128 fminmag(const float128& x, const float128& y) noexcept;
182constexpr bool iscanonical(const float128& x) noexcept;
183constexpr bool issignaling(const float128& x) noexcept;
184constexpr bool issubnormal(const float128& x) noexcept;
185constexpr bool iszero(const float128& x) noexcept;
186/// The only one of these that a call cannot reach through argument dependent lookup: its argument
187/// is a plain character pointer, so the name has to be visible at namespace scope - and a call has
188/// to be qualified as fp128::nan(...) wherever `<cmath>` puts its own nan(const char*) in scope too.
189float128 nan(const char* payload) noexcept;
190/// @}
191
192/// @name Non-CRT Utility Functions (Forward Declarations)
193/// @{
194float128 reciprocal(const float128& x) noexcept;
195void fact_reciprocal(int x, float128& res) noexcept;
196float128 double_factorial(int x) noexcept;
197/// @}
198
199/***********************************************************************************
200 * Floating point environment
201 ************************************************************************************/
202
203/**
204 * @name Floating point environment
205 *
206 * IEEE 754-2008 asks two things of a binary format beyond its arithmetic. Clause 4 requires four
207 * rounding-direction attributes the program can choose between: to nearest with ties to even, the
208 * default, and towards zero, towards positive infinity and towards negative infinity. Clause 7
209 * requires five exceptions - invalid operation, division by zero, overflow, underflow and inexact -
210 * each reported by a status flag that stays raised until the program lowers it.
211 *
212 * float128 provides both, as a per thread environment of its own that is entirely separate from the
213 * hardware one `<cfenv>` controls: setting the rounding direction here does not change how double
214 * rounds, and an exception raised by a float128 operation shows up here and not in fetestexcept().
215 *
216 * <B>The environment is opt in.</B> It exists only when every translation unit that includes this
217 * header is compiled with FP128_IEEE_ENV defined. Without it, which is the default, every operation
218 * rounds to nearest with ties to even, no flag is ever raised, and the code that would maintain the
219 * environment compiles away, leaving the arithmetic exactly as fast as it was before the
220 * environment existed. The functions below are still declared, so the same source builds either
221 * way: they report the fixed default and refuse to change it.
222 *
223 * The macro changes the definition of inline functions, so it must have the same value in every
224 * translation unit of a program. Mixing the two violates the one definition rule.
225 *
226 * The rounding directions and exception flags are named with the FE_ constants of `<cfenv>`, so the
227 * calls read the way their hardware counterparts do:
228 * @code
229 * fp128::fesetround(FE_UPWARD);
230 * float128 bound = a / b; // rounded towards +inf
231 * if (fp128::fetestexcept(FE_INEXACT)) { ... } // the quotient was not exact
232 * @endcode
233 * The calls have to be qualified: their arguments are plain integers, so argument dependent lookup
234 * cannot tell them from the `<cfenv>` functions of the same name.
235 * @{
236 */
237
238namespace detail
239{
240/// @brief The rounding-direction attributes IEEE 754-2008 requires of a binary format.
241enum class rounding : uint8_t {
242 nearest_even, ///< roundTiesToEven, the default
243 toward_zero, ///< roundTowardZero
244 upward, ///< roundTowardPositive
245 downward ///< roundTowardNegative
246};
247
248/// @brief The per thread state behind the float128 environment.
249struct float_env {
250 rounding mode = rounding::nearest_even; ///< Rounding direction in effect.
251 int flags = 0; ///< Raised exceptions, as FE_ bits.
252};
253
254#ifdef FP128_IEEE_ENV
255/// @brief The environment of the calling thread.
256inline thread_local float_env env;
257#endif
258
259/**
260 * @brief The rounding direction every float128 operation applies.
261 *
262 * Constant evaluation always rounds to nearest: a thread local cannot be read there, and a constant
263 * whose value depended on the thread that happened to compile it would be meaningless anyway.
264 *
265 * Never store the result in a const local: `const rounding mode = current_rounding();` makes the
266 * initializer manifestly constant evaluated, so it would always see nearest_even. Pass the call
267 * as an argument, or keep the local non const.
268 *
269 * @return The current rounding direction, or nearest_even without FP128_IEEE_ENV.
270 */
271[[nodiscard]] FP128_FORCE_INLINE constexpr rounding current_rounding() noexcept
272{
273#ifdef FP128_IEEE_ENV
274 if (!std::is_constant_evaluated())
275 return env.mode;
276#endif
278}
279
280/**
281 * @brief Raises exception flags. Does nothing without FP128_IEEE_ENV or during constant evaluation.
282 * @param flags FE_ bits to raise
283 */
284FP128_FORCE_INLINE constexpr void raise_flags([[maybe_unused]] int flags) noexcept
285{
286#ifdef FP128_IEEE_ENV
287 if (!std::is_constant_evaluated())
288 env.flags |= flags;
289#endif
290}
291
292/**
293 * @brief Sets the exception flags aside for its lifetime, and discards whatever is raised meanwhile.
294 *
295 * For computations whose intermediate operations raise exceptions the result does not: the trial
296 * parses of the shortest decimal search, or the Newton steps of sqrt(), which are inexact even when
297 * the root they converge on is exact. Compiles to nothing without FP128_IEEE_ENV.
298 */
300{
301public:
302 flag_quiet() noexcept
303 {
304#ifdef FP128_IEEE_ENV
305 saved = env.flags;
306#endif
307 }
309 {
310#ifdef FP128_IEEE_ENV
311 env.flags = saved;
312#endif
313 }
314 flag_quiet(const flag_quiet&) = delete;
315 flag_quiet& operator=(const flag_quiet&) = delete;
316
317private:
318 [[maybe_unused]] int saved = 0; ///< Flags raised before the scope began.
319};
320
321/**
322 * @brief Reduces what a math function's internal operations raise to what its result justifies.
323 *
324 * A function such as sin() is built from dozens of additions and multiplications, and those raise
325 * exceptions of their own: a series term underflows, an intermediate overflows on a path whose
326 * result does not. IEEE 754-2008 9.2 asks the function to signal as one operation would - inexact
327 * when the result is, overflow when the result overflowed, underflow when it is tiny and inexact.
328 * Constructed after a function has dealt with its special cases, which raise invalid and division
329 * by zero themselves, it sets the caller's flags aside; operator() then keeps inexact if any step
330 * raised it and derives the rest from the result. Compiles to nothing without FP128_IEEE_ENV.
331 */
333{
334public:
335 flag_filter() noexcept
336 {
337#ifdef FP128_IEEE_ENV
338 saved = env.flags;
339 env.flags = 0;
340#endif
341 }
343 {
344#ifdef FP128_IEEE_ENV
345 env.flags = saved | kept;
346#endif
347 }
348 flag_filter(const flag_filter&) = delete;
350
351 /**
352 * @brief The same as operator(), for a result known to be inexact without an operation
353 * having said so: an overflow or underflow decided from the argument's range alone.
354 * @tparam T float128
355 * @param result The function's result
356 * @return result
357 */
358 template <typename T> [[nodiscard]] T inexact(const T& result) noexcept
359 {
360 raise_flags(FE_INEXACT);
361 return (*this)(result);
362 }
363
364 /**
365 * @brief Records the flags a result justifies and passes the result through.
366 * @tparam T float128, which is incomplete where this is declared
367 * @param result The function's result, from finite operands
368 * @return result
369 */
370 template <typename T> [[nodiscard]] T operator()(const T& result) noexcept
371 {
372#ifdef FP128_IEEE_ENV
373 const int raised = env.flags;
374 int justified = raised & FE_INEXACT;
375 if (result.is_nan())
376 justified |= FE_INVALID;
377 else if (result.is_inf())
378 justified |= FE_OVERFLOW | FE_INEXACT;
379 else if ((result.is_zero() || result.is_subnormal()) && (raised & FE_INEXACT) != 0)
380 justified |= FE_UNDERFLOW;
381 kept |= justified;
382#endif
383 return result;
384 }
385
386private:
387 [[maybe_unused]] int saved = 0; ///< Flags raised before the function began.
388 [[maybe_unused]] int kept = 0; ///< Flags the result justified.
389};
390
391/**
392 * @brief The digit rounding the current direction comes down to for a value of a given sign.
393 * @param sign Sign of the value being converted
394 * @return How to round its last digit.
395 */
396[[nodiscard]] inline digit_rounding digit_rounding_for(uint32_t sign) noexcept
397{
398 switch (current_rounding()) {
402 default: return digit_rounding::nearest_even;
403 }
404}
405} // namespace detail
406
407/**
408 * @brief The rounding direction float128 arithmetic uses on the calling thread.
409 * @return One of FE_TONEAREST, FE_TOWARDZERO, FE_UPWARD or FE_DOWNWARD.
410 */
411[[nodiscard]] inline int fegetround() noexcept
412{
413 switch (detail::current_rounding()) {
414 case detail::rounding::toward_zero: return FE_TOWARDZERO;
415 case detail::rounding::upward: return FE_UPWARD;
416 case detail::rounding::downward: return FE_DOWNWARD;
417 default: return FE_TONEAREST;
418 }
419}
420
421/**
422 * @brief Selects the rounding direction float128 arithmetic uses on the calling thread.
423 * @param round One of FE_TONEAREST, FE_TOWARDZERO, FE_UPWARD or FE_DOWNWARD
424 * @return Zero on success. Non zero for an unknown direction, and for anything but FE_TONEAREST
425 * when the program was built without FP128_IEEE_ENV.
426 */
427inline int fesetround(int round) noexcept
428{
430 if (round == FE_TOWARDZERO)
432 else if (round == FE_UPWARD)
434 else if (round == FE_DOWNWARD)
436 else if (round != FE_TONEAREST)
437 return 1;
438
439#ifdef FP128_IEEE_ENV
440 detail::env.mode = mode;
441 return 0;
442#else
443 return (mode == detail::rounding::nearest_even) ? 0 : 1;
444#endif
445}
446
447/**
448 * @brief Tests float128 exception flags (IEEE 754 testFlags).
449 * @param excepts FE_ bits to test
450 * @return The subset of @p excepts that is raised. Always zero without FP128_IEEE_ENV.
451 */
452[[nodiscard]] inline int fetestexcept([[maybe_unused]] int excepts) noexcept
453{
454#ifdef FP128_IEEE_ENV
455 return detail::env.flags & excepts & FE_ALL_EXCEPT;
456#else
457 return 0;
458#endif
459}
460
461/**
462 * @brief Lowers float128 exception flags (IEEE 754 lowerFlags).
463 * @param excepts FE_ bits to clear
464 * @return Zero.
465 */
466inline int feclearexcept([[maybe_unused]] int excepts) noexcept
467{
468#ifdef FP128_IEEE_ENV
469 detail::env.flags &= ~excepts;
470#endif
471 return 0;
472}
473
474/**
475 * @brief Raises float128 exception flags (IEEE 754 raiseFlags).
476 * @param excepts FE_ bits to raise
477 * @return Zero on success; non zero without FP128_IEEE_ENV, when there is nowhere to raise them.
478 */
479inline int feraiseexcept(int excepts) noexcept
480{
481#ifdef FP128_IEEE_ENV
482 detail::env.flags |= excepts & FE_ALL_EXCEPT;
483 return 0;
484#else
485 return (excepts & FE_ALL_EXCEPT) != 0 ? 1 : 0;
486#endif
487}
488
489/**
490 * @brief Saves the state of float128 exception flags (IEEE 754 saveAllFlags).
491 * @param flagp Receives the saved state
492 * @param excepts FE_ bits to save
493 * @return Zero.
494 */
495inline int fegetexceptflag(std::fexcept_t* flagp, int excepts) noexcept
496{
497 if (flagp != nullptr)
498 *flagp = static_cast<std::fexcept_t>(fetestexcept(excepts));
499 return 0;
500}
501
502/**
503 * @brief Restores float128 exception flags saved by fegetexceptflag (IEEE 754 restoreFlags).
504 *
505 * Only the flags named in @p excepts are written, each set to the state it had when saved.
506 *
507 * @param flagp State saved by fegetexceptflag()
508 * @param excepts FE_ bits to restore
509 * @return Zero.
510 */
511inline int fesetexceptflag([[maybe_unused]] const std::fexcept_t* flagp, [[maybe_unused]] int excepts) noexcept
512{
513#ifdef FP128_IEEE_ENV
514 if (flagp != nullptr) {
515 const int mask = excepts & FE_ALL_EXCEPT;
516 detail::env.flags = (detail::env.flags & ~mask) | (static_cast<int>(*flagp) & mask);
517 }
518#endif
519 return 0;
520}
521/// @}
522
523namespace detail
524{
525/**
526 * @brief The binary expansion of 2/pi after the binary point, most significant word first.
527 *
528 * The trigonometric functions reduce a large argument by multiplying it with a window of these
529 * bits chosen by its exponent (see float128::reduce_large()). An argument near the top of the
530 * binary128 range reads about 16650 bits in. Generated by tools/gen_two_over_pi.py, which also
531 * verifies it; do not edit by hand.
532 */
533inline constexpr uint64_t two_over_pi_bits[] = {
534 0xA2F9836E4E441529, 0xFC2757D1F534DDC0, 0xDB6295993C439041, 0xFE5163ABDEBBC561,
535 0xB7246E3A424DD2E0, 0x06492EEA09D1921C, 0xFE1DEB1CB129A73E, 0xE88235F52EBB4484,
536 0xE99C7026B45F7E41, 0x3991D639835339F4, 0x9C845F8BBDF9283B, 0x1FF897FFDE05980F,
537 0xEF2F118B5A0A6D1F, 0x6D367ECF27CB09B7, 0x4F463F669E5FEA2D, 0x7527BAC7EBE5F17B,
538 0x3D0739F78A5292EA, 0x6BFB5FB11F8D5D08, 0x56033046FC7B6BAB, 0xF0CFBC209AF4361D,
539 0xA9E391615EE61B08, 0x6599855F14A06840, 0x8DFFD8804D732731, 0x06061556CA73A8C9,
540 0x60E27BC08C6B47C4, 0x19C367CDDCE8092A, 0x8359C4768B961CA6, 0xDDAF44D15719053E,
541 0xA5FF07053F7E33E8, 0x32C2DE4F98327DBB, 0xC33D26EF6B1E5EF8, 0x9F3A1F35CAF27F1D,
542 0x87F121907C7C246A, 0xFA6ED5772D30433B, 0x15C614B59D19C3C2, 0xC4AD414D2C5D000C,
543 0x467D862D71E39AC6, 0x9B0062337CD2B497, 0xA7B4D55537F63ED7, 0x1810A3FC764D2A9D,
544 0x64ABD770F87C6357, 0xB07AE715175649C0, 0xD9D63B3884A7CB23, 0x24778AD623545AB9,
545 0x1F001B0AF1DFCE19, 0xFF319F6A1E666157, 0x9947FBACD87F7EB7, 0x652289E83260BFE6,
546 0xCDC4EF09366CD43F, 0x5DD7DE16DE3B5892, 0x9BDE2822D2E88628, 0x4D58E232CAC616E3,
547 0x08CB7DE050C017A7, 0x1DF35BE01834132E, 0x6212830148835B8E, 0xF57FB0ADF2E91E43,
548 0x4A48D36710D8DDAA, 0x425FAECE616AA428, 0x0AB499D3F2A6067F, 0x775C83C2A3883C61,
549 0x78738A5A8CAFBDD7, 0x6F63A62DCBBFF4EF, 0x818D67C12645CA55, 0x36D9CAD2A8288D61,
550 0xC277C9121426049B, 0x4612C459C444C5C8, 0x91B24DF31700AD43, 0xD4E5492910D5FDFC,
551 0xBE00CC941EEECE70, 0xF53E1380F1ECC3E7, 0xB328F8C79405933E, 0x71C1B3092EF3450B,
552 0x9C12887B20AB9FB5, 0x2EC292472F327B6D, 0x550C90A7721FE76B, 0x96CB314A1679E279,
553 0x4189DFF49794E884, 0xE6E29731996BED88, 0x365F5F0EFDBBB49A, 0x486CA46742727132,
554 0x5D8DB8159F09E5BC, 0x25318D3974F71C05, 0x30010C0D68084B58, 0xEE2C90AA4702E774,
555 0x24D6BDA67DF77248, 0x6EEF169FA6948EF6, 0x91B45153D1F20ACF, 0x3398207E4BF56863,
556 0xB25F3EDD035D407F, 0x8985295255C06437, 0x10D86D324832754C, 0x5BD4714E6E5445C1,
557 0x090B69F52AD56614, 0x9D072750045DDB3B, 0xB4C576EA17F9877D, 0x6B49BA271D296996,
558 0xACCCC65414AD6AE2, 0x9089D98850722CBE, 0xA4049407777030F3, 0x27FC00A871EA49C2,
559 0x663DE06483DD9797, 0x3FA3FD94438C860D, 0xDE41319D39928C70, 0xDDE7B7173BDF082B,
560 0x3715A0805C93805A, 0x921110D8E80FAF80, 0x6C4BFFDB0F903876, 0x185915A562BBCB61,
561 0xB989C7BD401004F2, 0xD2277549F6B6EBBB, 0x22DBAA140A2F2689, 0x768364333B091A94,
562 0x0EAA3A51C2A31DAE, 0xEDAF12265C4DC26D, 0x9C7A2D9756C0833F, 0x03F6F0098C402B99,
563 0x316D07B43915200C, 0x5BC3D8C492F54BAD, 0xC6A5CA4ECD37A736, 0xA9E69492AB6842DD,
564 0xDE6319EF8C76528B, 0x6837DBFCABA1AE31, 0x15DFA1AE00DAFB0C, 0x664D64B705ED3065,
565 0x29BF56573AFF47B9, 0xF96AF3BE75DF9328, 0x3080ABF68C6615CB, 0x040622FA1DE4D9A4,
566 0xB33D8F1B5709CD36, 0xE9424EA4BE13B523, 0x331AAAF0A8654FA5, 0xC1D20F3F0BCD785B,
567 0x76F923048B7B7217, 0x8953A6C6E26E6F00, 0xEBEF584A9BB7DAC4, 0xBA66AACFCF761D02,
568 0xD12DF1B1C1998C77, 0xADC3DA4886A05DF7, 0xF480C62FF0AC9AEC, 0xDDBC5C3F6DDED01F,
569 0xC790B6DB2A3A25A3, 0x9AAF009353AD0457, 0xB6B42D297E804BA7, 0x07DA0EAA76A1597B,
570 0x2A12162DB7DCFDE5, 0xFAFEDB89FDBE896C, 0x76E4FCA90670803E, 0x156E85FF87FD073E,
571 0x2833676186182AEA, 0xBD4DAFE7B36E6D8F, 0x3967955BBF3148D7, 0x8416DF30432DC735,
572 0x6125CE70C9B8CB30, 0xFD6CBFA200A4E46C, 0x05A0DD5A476F21D2, 0x1262845CB9496170,
573 0xE0566B0152993755, 0x50B7D51EC4F1335F, 0x6E13E4305DA92E85, 0xC3B21D3632A1A4B7,
574 0x08D4B1EA21F716E4, 0x698F77FF2780030C, 0x2D408DA0CD4F99A5, 0x20D3A2B30A5D2F42,
575 0xF9B4CBDA11D0BE7D, 0xC1DB9BBD17AB81A2, 0xCA5C6A0817552E55, 0x0027F0147F8607E1,
576 0x640B148D4196DEBE, 0x872AFDDAB6256B34, 0x897BFEF3059EBFB9, 0x4F6A68A82A4A5AC4,
577 0x4FBCF82D985AD795, 0xC7F48D4D0DA63A20, 0x5F57A4B13F149538, 0x800120CC86DD71B6,
578 0xDEC9F560BF11654D, 0x6B0701ACB08CD0C0, 0xB24855510EFB1EC3, 0x72953B06A33540C0,
579 0x7BDC06CC45E0FA29, 0x4EC8CAD641F3E8DE, 0x647CD8649B31BED9, 0xC397A4D45877C5E3,
580 0x6913DAF03C3ABA46, 0x18465F7555F5BDD2, 0xC6926E5D2EACED44, 0x0E423E1C87C461E9,
581 0xFD29F3D6E7CA7C22, 0x35916FC5E0088DD7, 0xFFE26A6EC6FDB0C1, 0x0893745D7CB2AD6B,
582 0x9D6ECD7B723E6A11, 0xC6A9CFF7DF7329BA, 0xC9B55100B70DB2E2, 0x24BA74607DE58AD8,
583 0x742C150D0C188194, 0x667E162901767A9F, 0xBEFDFDEF4556367E, 0xD913D9ECB9BA8BFC,
584 0x97C427A831C36EF1, 0x36C59456A8D8B5A8, 0xB40ECCCF2D891234, 0x576F89562CE3CE99,
585 0xB920D6AA5E6B9C2A, 0x3ECC5F114A0BFDFB, 0xF4E16D3B8E2C86E2, 0x84D4E9A9B4FCD1EE,
586 0xEFC9352E61392F44, 0x2138C8D91B0AFC81, 0x6A4AFBD81C2F84B4, 0x538C994ECC2254DC,
587 0x552AD6C6C096190B, 0xB8701A649569605A, 0x26EE523F0F117F11, 0xB5F4F5CBFC2DBC34,
588 0xEEBC34CC5DE8605E, 0xDD9B8E67EF3392B8, 0x17C99B5861BC57E1, 0xC68351103ED84871,
589 0xDDDD1C2DA118AF46, 0x2C21D7F359987AD9, 0xC0549EFA864FFC06, 0x56AE79E536228922,
590 0xAD38DC9367AAE855, 0x3826829BE7CAA40D, 0x51B133990ED7A948, 0x0569F0B265A7887F,
591 0x974C8836D1F9B392, 0x214A827B21CF98DC, 0x9F405547DC3A74E1, 0x42EB67DF9DFE5FD4,
592 0x5EA4677B7AACBAA2, 0xF65523882B55BA41, 0x086E59862A218347, 0x39E6E389D49EE540,
593 0xFB49E956FFCA0F1C, 0x8A59C52BFA94C5C1, 0xD3CFC50FAE5ADB86, 0xC5476243853B8621,
594 0x94792C8761107B4C, 0x2A1A2C8012BF4390, 0x2688893C78E4C4A8, 0x7BDBE5C23AC4EAF4,
595 0x268A67F7BF920D2B, 0xA365B1933D0B7CBD, 0xDC51A463DD27DDE1, 0x6919949A9529A828,
596 0xCE68B4ED09209F44, 0xCA984E638270237C, 0x7E32B90F8EF5A7E7, 0x561408F1212A9DB5,
597 0x4D7E6F5119A5ABF9, 0xB5D6DF8261DD9602, 0x36169F3AC4A1A283, 0x6DED727A8D39A9B8,
598 0x825C326B5B2746ED, 0x34007700D255F4FC, 0x4D59018071E0E13F, 0x89B295F364A8F1AE,
599 0xA74B38FC4CEAB2BB, 0x47270BABC3A734BA, 0x6052DD34F8563AEB, 0x7E8A31BB365895B7,
600};
601} // namespace detail
602
603/***********************************************************************************
604 * Main Code
605 ************************************************************************************/
606
607/**
608 * @brief 128 bit floating point class.
609 *
610 * This class implements the standard operators a floating point data type.<BR>
611 * All of float128's methods are inline for maximum performance.
612 *
613 * <B>IEEE 754-2008:</B>
614 * <UL>
615 * <LI>Addition, subtraction, multiplication, division, sqrt(), fma(), the remainders, the
616 * rounding to an integral value and the conversions to and from double, float, long double,
617 * the integer types and text are correctly rounded - each computes the exact result and rounds
618 * it once, to the destination's width, its subnormal range included (see round_pack()).</LI>
619 * <LI>Every one of them follows the standard's rules for zeros, infinities and NaNs: the sign of
620 * an exact zero sum, the invalid operations, a signaling NaN quieted, the payload of the first
621 * NaN operand delivered.</LI>
622 * <LI>Round to nearest, ties to even, is the only rounding direction and no exception flag is
623 * kept, unless FP128_IEEE_ENV is defined; with it fp128::fesetround() chooses among the four
624 * directions clause 4 requires, and the five flags of clause 7 are raised and tested through
625 * fp128::fetestexcept() and its siblings. Only with the macro does the type claim conformance
626 * (numeric_limits::is_iec559, is754version2008()).</LI>
627 * <LI>The math functions of clause 9 follow its special values but are not correctly rounded,
628 * which the standard recommends rather than requires. Each one's error is measured and stated
629 * in tests/float128_accuracy_gtest.cpp.</LI>
630 * </UL>
631 *
632 * <B>Implementation notes:</B>
633 * <UL>
634 * <LI>Same bit layout as binary128: 112 bit fraction, 15 bit exponent and 1 bit for the sign.</LI>
635 * <LI>A float128 object is not thread safe. Accessing a const object from multiple threads is safe.</LI>
636 * <LI>Only 64 bit builds are supported.</LI>
637 * </UL>
638 *
639 * <B>Compile time evaluation:</B><BR>
640 * Everything that stays within the 128 bit encoding is constexpr:
641 * <UL>
642 * <LI>Construction from any builtin arithmetic type and from the raw QWORDs, copy, move,
643 * assignment and the conversions to the integer and floating point types.</LI>
644 * <LI>Addition, subtraction, multiplication, square(), the shifts, the unary operators and the
645 * comparisons.</LI>
646 * <LI>The queries and the component accessors: is_zero(), is_normal(), is_nan(), is_inf(),
647 * is_int(), get_exponent(), get_class(), get_components(), set_components() and the rest,
648 * along with every named constant (one(), pi(), inf(), nan(), ...).</LI>
649 * <LI>The math functions fabs, floor, ceil, trunc, round, llround, lround, llrint, lrint, ilogb,
650 * copysign, modf, fdim, fmin, fmax, fma, frexp, ldexp, sqr, isnan, isinf, isfinite, and the
651 * nextUp/nextDown/exp10 helpers.</LI>
652 * </UL>
653 *
654 * Two things make that possible. The bit counting and extended arithmetic intrinsics are not
655 * constant expressions, so fp128_shared.h wraps each one in a constexpr function that
656 * serves a constant evaluated call from a portable implementation of the same operation. And the
657 * fields of the high QWORD are read through the shift and mask accessors rather than the
658 * _float128_bits view, because reading the inactive member of a union is not allowed during
659 * constant evaluation. A runtime call is unaffected by either.
660 *
661 * The rest cannot be constexpr, for one of two reasons:
662 * <UL>
663 * <LI>Division and modulo, and everything built on them. Nothing in div_128bit itself is barred
664 * from a constant expression, so what keeps operator/=() out of one is the surrounding code
665 * rather than the long division.</LI>
666 * <LI>The string conversions allocate, and the transcendental functions parse their constants
667 * from strings held in function local statics, which a constexpr function may not declare.</LI>
668 * </UL>
669 */
670
672{
673 // build time validation of template parameters
674 static_assert(sizeof(void*) == 8, "float128 is supported in 64 bit builds only!");
675 friend class fp128_gtest;
676
677 static constexpr int32_t EXP_BITS = 15; ///< Number of exponent bits in binary128.
678 static constexpr int32_t EXP_BIAS = 0x3FFF; ///< Exponent bias (16383) for binary128.
679 static constexpr int32_t ZERO_EXP_BIASED = -EXP_BIAS; ///< Biased exponent value representing zero.
680 static constexpr int32_t ZERO_EXP_UNBIASED = 0; ///< Unbiased exponent value for zero encoding.
681 static constexpr int32_t SUBNORM_EXP_BIASED = 0; ///< Biased exponent value for subnormal numbers.
682 static constexpr int32_t SUBNORM_EXP_UNBIASED = -EXP_BIAS; ///< Unbiased exponent value for subnormal numbers.
683 static constexpr int32_t INF_EXP_BIASED = 0x7FFF; ///< Biased exponent value for infinity/NaN.
684 static constexpr int32_t INF_EXP_UNBIASED = INF_EXP_BIASED - EXP_BIAS; ///< Unbiased exponent value for infinity/NaN.
685 static constexpr uint64_t EXP_MASK = INF_EXP_BIASED; ///< Bitmask for the exponent field.
686 static constexpr int32_t FRAC_BITS = 112; ///< Number of fraction (mantissa) bits.
687 static constexpr int32_t EXP_SHIFT = FRAC_BITS - 64; ///< Bit position of the exponent field within the high QWORD.
688 static constexpr uint64_t UPPER_FRAC_MASK = FP128_MAX_VALUE_64(FRAC_BITS - 64); ///< Bitmask for upper fraction bits within the high QWORD.
689 static constexpr uint64_t FRAC_UNITY = FP128_ONE_SHIFT(FRAC_BITS - 64); ///< The implicit unity bit position in the high QWORD.
690 static constexpr uint64_t SIGN_MASK = 1ull << 63; ///< Bitmask for the sign bit.
691 static constexpr uint64_t QUIET_NAN_BIT = 1ull << (EXP_SHIFT - 1); ///< Leading fraction bit, set on a quiet NaN.
692
693 /// @brief Bit-field view of the upper 64 bits of a float128.
694 ///
695 /// Retained for the debugger visualizer (fixed_point128.natvis), which reads the three fields
696 /// by name. The code itself reaches the same fields through the shift and mask accessors
697 /// below: reading the inactive member of a union is not allowed during constant evaluation,
698 /// and every operation on this type funnels through those accessors.
699 struct _float128_bits {
700 uint64_t f : 48; ///< Upper 48 bits of the 112-bit fraction.
701 uint64_t e : 15; ///< 15-bit biased exponent.
702 uint64_t s : 1; ///< Sign bit (0 = positive, 1 = negative).
703 };
704
705 /// @brief IEEE 754 classification categories for float128 values.
706 enum float128_class_t {
707 signalingNaN, ///< Signaling NaN.
708 quietNaN, ///< Quiet NaN.
709 negativeInfinity, ///< Negative infinity.
710 negativeNormal, ///< Negative normal number.
711 negativeSubnormal, ///< Negative subnormal (denormalized) number.
712 negativeZero, ///< Negative zero.
713 positiveZero, ///< Positive zero.
714 positiveSubnormal, ///< Positive subnormal (denormalized) number.
715 positiveNormal, ///< Positive normal number.
716 positiveInfinity ///< Positive infinity.
717 };
718
719 /// @brief Internal storage: 128-bit value split into low and high QWORDs.
720 struct {
721 uint64_t low; ///< Lower 64 bits of the float128 encoding.
722 union {
723 uint64_t high; ///< Upper 64 bits (raw).
724 _float128_bits high_bits; ///< Upper 64 bits (bit-field view).
725 };
726 };
727
728public:
729 /**
730 * @brief Default constructor, creates an instance with a value of zero.
731 */
732 FP128_FORCE_INLINE constexpr float128() noexcept : low(0), high(0) {}
733 /**
734 * @brief Copy constructor
735 * @param rhs Object to copy from
736 */
737 FP128_FORCE_INLINE constexpr float128(const float128& rhs) noexcept : low(rhs.low), high(rhs.high) {}
738 /**
739 * @brief Move constructor
740 * Doesn't modify the right hand side object. Acts like a copy constructor.
741 * @param rhs Object to copy from
742 */
743 FP128_FORCE_INLINE constexpr float128(float128&& rhs) noexcept : low(rhs.low), high(rhs.high) {}
744 /**
745 * @brief Low level constructor
746 * @param l Low QWORD
747 * @param h High QWORD
748 */
749 FP128_FORCE_INLINE constexpr float128(uint64_t l, uint64_t h) noexcept : low(l), high(h) {}
750 /**
751 * @brief Low level constructor
752 * @param lf Low fraction part (bits 63:0)
753 * @param hf High fraction part (bits 111:64)
754 * @param e Exponent
755 * @param s sign
756 */
757 FP128_FORCE_INLINE constexpr float128(uint64_t lf, uint64_t hf, uint32_t e, uint32_t s) noexcept :
758 low(lf), high((hf & FP128_MAX_VALUE_64(48)) | (((0x7FFFull & e) << 48)) | ((1ull & s) << 63))
759 {
760 }
761 /**
762 * @brief Constructor from the double type
763 * @param x Input value
764 */
765 FP128_INLINE constexpr float128(double x) noexcept
766 {
767 low = high = 0;
768 // hack the double bit fields
769 const Double d(x);
770
771 // very common case. The sign is kept: -0.0 is a value of its own.
772 if (x == 0) {
773 set_sign(d.s());
774 return;
775 }
776
777 // subnormal numbers
778 if (d.e() == 0) {
779 // the exponent is -1022 (1-1023)
780 auto msb = 64 - static_cast<int32_t>(lzcnt64(d.f()));
781 // exponent
782 int32_t x_expo = static_cast<int32_t>(d.e()) - 1023;
783 int32_t expo = x_expo + msb - dbl_frac_bits;
784 // fraction
785 low = d.f() & ~(1ull << (msb - 1)); // clear the msb
786 auto shift = static_cast<int32_t>(FRAC_BITS - msb + 1);
788 set_exponent(expo);
789 }
790 // NaN & INF
791 else if (d.e() == 0x7FF) {
792 set_exponent_bits(INF_EXP_BIASED);
793 if (d.f() != 0) {
794 // A NaN keeps its payload, moved to the top of the wider fraction where the
795 // conversion back to double looks for it, and its quiet bit lands on the quiet bit.
796 // A signaling NaN is quieted: the conversion is an operation, and a signaling
797 // operand makes it the invalid one.
798 low = d.f() << (FRAC_BITS - dbl_frac_bits);
799 set_fraction_bits(d.f() >> (64 - (FRAC_BITS - dbl_frac_bits)));
800 if (is_signaling()) {
801 detail::raise_flags(FE_INVALID);
802 high |= QUIET_NAN_BIT;
803 }
804 }
805 }
806 // normal numbers
807 else {
808 low = d.f() << 60;
809 high = d.f() >> 4;
810 set_exponent(static_cast<int32_t>(d.e()) - 1023);
811 }
812
813 // copy the sign
814 set_sign(d.s());
815 }
816 /**
817 * @brief Generic constructor for integral and floating-point types.
818 *
819 * Every value of every builtin arithmetic type is representable, so the conversion is exact.
820 * float goes through double, which holds it exactly. A long double wider than a double - the
821 * x87 extended format, or binary128 itself - is read from its encoding, since a double would
822 * round it. Integral types are converted directly. Character pointer types delegate to the
823 * const char* constructor.
824 *
825 * @tparam T Source type (must be arithmetic or a character pointer type)
826 * @param x Input value
827 */
828 template <typename T> constexpr float128(T x) noexcept : low(0), high(0)
829 {
830 if constexpr (std::is_floating_point_v<T>) {
831 if constexpr (std::is_same_v<T, long double> && LDBL_MANT_DIG != 53) {
832 *this = from_long_double(x);
833 } else if constexpr (std::is_same_v<T, float>) {
834 // A signaling NaN is the invalid operation, as the double constructor has it. The
835 // hardware conversion to double quiets one before that constructor could see it, so
836 // it is detected here, and quieted first so that every compiler delivers the same
837 // quiet NaN, its payload kept.
838 const uint32_t bits = std::bit_cast<uint32_t>(x);
839 if ((bits & 0x7F800000u) == 0x7F800000u && (bits & 0x003FFFFFu) != 0 && (bits & 0x00400000u) == 0) {
840 detail::raise_flags(FE_INVALID);
841 *this = float128(static_cast<double>(std::bit_cast<float>(bits | 0x00400000u)));
842 } else {
843 *this = float128(static_cast<double>(x));
844 }
845 } else {
846 *this = float128(static_cast<double>(x));
847 }
848 return;
849 } else if constexpr (std::is_same_v<char*, T> || std::is_same_v<unsigned char*, T> || std::is_same_v<const unsigned char*, T>) {
850 *this = float128(static_cast<const char*>(x));
851 return;
852 } else if constexpr (std::is_integral_v<T>) {
853 uint64_t sign = 0;
854 // The magnitude is taken in the unsigned domain, where the conversion sign extends and
855 // the negation wraps. Negating the signed value instead is undefined for the most
856 // negative one, which has no positive counterpart, and produces the same bit pattern
857 // for every other value.
858 low = static_cast<uint64_t>(x);
859 if constexpr (std::is_signed_v<T>) {
860 // always do positive multiplication
861 if (x < 0) {
862 low = 0ull - low;
863 sign = 1;
864 }
865 }
866
867 if (low == 0)
868 return;
869
870 auto expo = log2(low); // this is the index of the msb as well
871 auto shift = static_cast<int32_t>(FRAC_BITS - expo);
873 set_sign(sign);
874 set_exponent(static_cast<int32_t>(expo));
875 return;
876 }
877 }
878 /**
879 * @brief Construct from a string
880 * Allows creating very high precision values, approximately 34 decimal digits.
881 * Much slower than the other constructors.
882 * @param x Input string
883 */
884 float128(const char* x) noexcept
885 {
886 low = high = 0;
887 if (x == nullptr)
888 return;
889
890 // Everything is read by from_chars(), which builds the exact value and rounds it once:
891 // a decimal number, a hexadecimal one (0x1.8p1, the form printf's %a writes), or one of
892 // inf, infinity, nan, nan(payload) and snan. Leading white space is skipped, as strtod()
893 // skips it.
894 //
895 // The decimal path used to live here: it accumulated the digits as a float128 and divided
896 // by a power of ten held in the type. Negative powers of ten are not representable in
897 // binary, so that division rounded, and the value came back about an ulp away from the
898 // one the string named. The hexadecimal path that remained here read integers only, so
899 // 0x1.8p1 came back as 1, and it truncated the digits past the 29th rather than rounding.
900 while (*x != 0 && isspace(static_cast<unsigned char>(*x)))
901 ++x;
902 const char* const end = x + strlen(x);
903 const char* body = x;
904 if (*body == '-' || *body == '+')
905 ++body;
906 if (body[0] == '0' && (body[1] == 'x' || body[1] == 'X')) {
907 // std::from_chars takes a hexadecimal number without its prefix. A value out of range
908 // comes back as the infinity or zero it rounds to, and takes the sign as well: only
909 // text that is no number at all leaves the value zero. "-0x1p100000" used to read +inf.
910 if (from_chars(body + 2, end, *this, std::chars_format::hex).ec != std::errc::invalid_argument && *x == '-') {
911 invert_sign();
912 }
913 return;
914 }
915 from_chars(x, end, *this);
916 }
917 /**
918 * @brief Constructor from std::string.
919 * Allows creating very high precision values. Much slower than the other constructors.
920 * @param x Input string
921 */
922 FP128_INLINE float128(const std::string& x) noexcept
923 {
924 // delegate to the char* c'tor
925 *this = float128(x.c_str());
926 }
927 /**
928 * @brief Destructor
929 */
930 constexpr ~float128() = default;
931
932 /**
933 * @brief Assignment operator
934 * @param rhs Object to copy from
935 * @return This object.
936 */
937 constexpr FP128_FORCE_INLINE float128& operator=(const float128& rhs) noexcept
938 {
939 high = rhs.high;
940 low = rhs.low;
941 return *this;
942 }
943 /**
944 * @brief Move assignment operator
945 * @param rhs Object to copy from
946 * @return This object.
947 */
949 {
950 high = rhs.high;
951 low = rhs.low;
952 return *this;
953 }
954
955 //
956 // conversion operators
957 //
958
959 /**
960 * @name Conversion to narrower floating point formats
961 *
962 * IEEE 754-2008 5.4.2 convertFormat: the value is rounded once, in the current direction, to
963 * the destination's precision and range - including its subnormal range, which keeps fewer
964 * bits than its normal one. A NaN keeps its sign and as much of its payload as fits, and is
965 * quieted.
966 * @{
967 */
968
969 /// @brief A finite value rounded to a narrower binary format, see narrow().
970 struct narrowed {
971 uint64_t sig = 0; ///< Significand, below 2^P. Zero for a zero result.
972 int32_t lsb = 0; ///< Weight of the significand's lowest bit, as a power of two.
973 uint32_t sign = 0; ///< Sign of the result.
974 bool to_inf = false; ///< The value overflowed to infinity.
975 };
976
977 /**
978 * @brief Rounds this finite, non zero value to a narrower binary format.
979 *
980 * Overflow produces infinity, or the largest finite value in the two directions that round
981 * towards it, and raises the overflow and inexact flags. A result that is tiny after rounding
982 * and inexact raises underflow.
983 *
984 * @tparam P Precision of the destination, counting its leading bit whether stored or implicit.
985 * At most 64, so the significand fits a single word.
986 * @tparam EMIN Exponent of the destination's smallest normal value
987 * @tparam EMAX Exponent of its largest finite value
988 * @return The rounded significand and the weight of its lowest bit.
989 */
990 template <int32_t P, int32_t EMIN, int32_t EMAX> [[nodiscard]] FP128_INLINE constexpr narrowed narrow() const noexcept
991 {
992 static_assert(P >= 2 && P <= 64, "the significand has to fit in a QWORD");
993 constexpr uint64_t all_ones = (P == 64) ? UINT64_MAX : ((1ull << P) - 1);
994
995 narrowed res;
996 uint64_t l = 0, h = 0;
997 int32_t e = 0;
998 get_components(l, h, e, res.sign);
999 // Not const: a const local of enumeration type initialized from a constant expression is
1000 // usable in constant expressions, which makes its initializer manifestly constant evaluated
1001 // - std::is_constant_evaluated() would answer true there, and fix the direction to nearest.
1003
1004 // The lowest bit kept is P-1 places below the leading one, or the destination's subnormal
1005 // floor when that is higher. The 113 bit significand's own lowest bit weighs 2^(e-112).
1006 res.lsb = ((e < EMIN) ? EMIN : e) - (P - 1);
1007 const int32_t drop = res.lsb - (e - FRAC_BITS);
1008
1009 // Tininess is detected after rounding: a value just below the smallest normal one is not
1010 // tiny when rounding it to P bits with an unbounded exponent carries it up to there.
1011 bool tiny = e < EMIN;
1012 if (e == EMIN - 1) {
1013 uint64_t tl = l, th = h, textra = 0;
1014 shift_right_jam128_extra(tl, th, textra, FRAC_BITS + 1 - P);
1015 if (tl == all_ones && round_increment(mode, res.sign, textra))
1016 tiny = false;
1017 }
1018
1019 uint64_t extra = 0;
1020 shift_right_jam128_extra(l, h, extra, drop);
1021 res.sig = l; // at most P bits are left, and P is at most 64
1022 if (extra != 0) {
1023 detail::raise_flags(tiny ? (FE_INEXACT | FE_UNDERFLOW) : FE_INEXACT);
1024 if (round_increment(mode, res.sign, extra)) {
1025 ++res.sig;
1026 // A carry out of the top lands on the next power of two. It has to be read before
1027 // the tie is settled: for a 64 bit significand the carry shows as a wrap to zero,
1028 // and a tie that rounded zero up to one and back to even leaves a zero as well.
1029 const bool carry = (P == 64) ? (res.sig == 0) : ((res.sig >> (P % 64)) != 0);
1030 if (mode == detail::rounding::nearest_even && (extra << 1) == 0)
1031 res.sig &= ~1ull; // an exact tie goes to the even neighbour
1032 if (carry) {
1033 res.sig = 1ull << (P - 1);
1034 ++res.lsb;
1035 }
1036 }
1037 }
1038
1039 if (res.lsb + (P - 1) > EMAX) {
1040 detail::raise_flags(FE_OVERFLOW | FE_INEXACT);
1042 res.sig = all_ones;
1043 res.lsb = EMAX - (P - 1);
1044 }
1045 return res;
1046 }
1047
1048 /**
1049 * @brief The top of a NaN's payload, for a narrower format to carry.
1050 *
1051 * The payload is the fraction below the quiet bit, bits 110:0. A narrower format keeps its top
1052 * bits, which is where the conversion from that format puts them, so a payload survives the
1053 * round trip.
1054 *
1055 * @param shift FRAC_BITS - 1 less the payload width of the destination, at least 47
1056 * @return Bits 110:shift of the fraction, right aligned.
1057 */
1058 [[nodiscard]] FP128_FORCE_INLINE constexpr uint64_t nan_payload_top(int32_t shift) const noexcept
1059 {
1060 const uint64_t frac_high = get_fraction_bits() & (UPPER_FRAC_MASK >> 1);
1061 return (shift >= 64) ? (frac_high >> (shift - 64)) : ((frac_high << (64 - shift)) | (low >> shift));
1062 }
1063
1064 /**
1065 * @brief Operator double
1066 *
1067 * Correctly rounded in the current direction. Overflow keeps its sign, as does a value too small
1068 * for the subnormal range, and a NaN keeps its sign and the top 51 bits of its payload.
1069 */
1070 [[nodiscard]] FP128_INLINE constexpr operator double() const noexcept
1071 {
1072 const uint64_t sign = static_cast<uint64_t>(get_sign()) << 63;
1073 if (is_special()) {
1074 if (is_nan()) {
1075 if (is_signaling())
1076 detail::raise_flags(FE_INVALID);
1077 return std::bit_cast<double>(sign | (0x7FFull << 52) | (1ull << 51) | nan_payload_top(FRAC_BITS - 1 - 51));
1078 }
1079 return std::bit_cast<double>(sign | (0x7FFull << 52));
1080 }
1081 if (is_zero())
1082 return std::bit_cast<double>(sign);
1083
1084 const narrowed n = narrow<53, -1022, 1023>();
1085 if (n.to_inf)
1086 return std::bit_cast<double>(sign | (0x7FFull << 52));
1087 // A normal significand's leading one adds the last unit to the exponent field, which is
1088 // why the field is written one short; a subnormal one has no leading one and no exponent.
1089 if (n.sig >> 52)
1090 return std::bit_cast<double>(sign + (static_cast<uint64_t>(n.lsb + 52 + 1023 - 1) << 52) + n.sig);
1091 return std::bit_cast<double>(sign | n.sig);
1092 }
1093 /**
1094 * @brief operator float converts to a float
1095 *
1096 * Rounded once, straight to single precision. Going through double, as this used to, rounds
1097 * twice: 1 + 2^-24 + 2^-82 became 1 + 2^-24 in double, a tie, which then went to 1.0f.
1098 */
1099 [[nodiscard]] FP128_INLINE constexpr operator float() const noexcept
1100 {
1101 const uint32_t sign = get_sign() << 31;
1102 if (is_special()) {
1103 if (is_nan()) {
1104 if (is_signaling())
1105 detail::raise_flags(FE_INVALID);
1106 return std::bit_cast<float>(sign | 0x7F800000u | 0x00400000u | static_cast<uint32_t>(nan_payload_top(FRAC_BITS - 1 - 22)));
1107 }
1108 return std::bit_cast<float>(sign | 0x7F800000u);
1109 }
1110 if (is_zero())
1111 return std::bit_cast<float>(sign);
1112
1113 const narrowed n = narrow<24, -126, 127>();
1114 if (n.to_inf)
1115 return std::bit_cast<float>(sign | 0x7F800000u);
1116 const uint32_t sig = static_cast<uint32_t>(n.sig);
1117 if (sig >> 23)
1118 return std::bit_cast<float>(sign + (static_cast<uint32_t>(n.lsb + 23 + 127 - 1) << 23) + sig);
1119 return std::bit_cast<float>(sign | sig);
1120 }
1121 /// @}
1122
1123 /**
1124 * @name Conversion to integers
1125 *
1126 * The C++ conversions truncate towards zero, which is IEEE 754-2008's
1127 * convertToIntegerTowardZero. They used to round to nearest for a magnitude of one or more and
1128 * truncate below it, which agreed with neither: 0.75 became 0 but 1.75 became 2.
1129 *
1130 * A value outside the range of the integer type, or a NaN, is the invalid operation. The result
1131 * is then defined rather than left undefined as it is for the builtin types: an out of range
1132 * value saturates at the nearest limit, and a NaN converts to zero.
1133 * @{
1134 */
1135
1136 /**
1137 * @brief The integer part of |x|, truncated towards zero.
1138 * @param overflow Set when |x| is 2^64 or more, an infinity included
1139 * @return The truncated magnitude, or UINT64_MAX on overflow.
1140 */
1141 [[nodiscard]] FP128_INLINE constexpr uint64_t truncated_magnitude(bool& overflow) const noexcept
1142 {
1143 uint64_t l = 0, h = 0;
1144 int32_t e = 0;
1145 uint32_t s = 0;
1146 get_components(l, h, e, s);
1147 overflow = e > 63;
1148 if (overflow)
1149 return UINT64_MAX;
1150 if (e < 0)
1151 return 0;
1152 // The units bit is bit 112 - e of the significand, which is between 49 and 112.
1153 const int32_t shift = FRAC_BITS - e;
1154 return (shift >= 64) ? (h >> (shift - 64)) : ((l >> shift) | (h << (64 - shift)));
1155 }
1156
1157 /**
1158 * @brief Converts to an integer type, truncating towards zero.
1159 * @tparam I The integer type
1160 * @return The converted value, saturated when out of range, zero for a NaN.
1161 */
1162 template <typename I> [[nodiscard]] FP128_INLINE constexpr I to_integer() const noexcept
1163 {
1164 if (is_nan()) {
1165 detail::raise_flags(FE_INVALID);
1166 return 0;
1167 }
1168
1169 const bool negative = get_sign() != 0;
1170 bool overflow = false;
1171 const uint64_t magnitude = truncated_magnitude(overflow);
1172 if constexpr (std::is_signed_v<I>) {
1173 // The negative range reaches one further than the positive one.
1174 const uint64_t limit = static_cast<uint64_t>(std::numeric_limits<I>::max()) + (negative ? 1u : 0u);
1175 if (overflow || magnitude > limit) {
1176 detail::raise_flags(FE_INVALID);
1177 return negative ? std::numeric_limits<I>::min() : std::numeric_limits<I>::max();
1178 }
1179 // Negated in the unsigned domain, which also covers the most negative value.
1180 return static_cast<I>(negative ? (0ull - magnitude) : magnitude);
1181 } else {
1182 // A negative value that truncates to zero converts fine; anything below that does not.
1183 if (negative && magnitude != 0) {
1184 detail::raise_flags(FE_INVALID);
1185 return 0;
1186 }
1187 if (overflow || magnitude > std::numeric_limits<I>::max()) {
1188 detail::raise_flags(FE_INVALID);
1189 return std::numeric_limits<I>::max();
1190 }
1191 return static_cast<I>(magnitude);
1192 }
1193 }
1194
1195 /**
1196 * @brief operator uint64_t converts to a uint64_t, truncating towards zero
1197 */
1198 [[nodiscard]] FP128_INLINE constexpr operator uint64_t() const noexcept { return to_integer<uint64_t>(); }
1199 /**
1200 * @brief operator int64_t converts to a int64_t, truncating towards zero
1201 */
1202 [[nodiscard]] FP128_INLINE constexpr operator int64_t() const noexcept { return to_integer<int64_t>(); }
1203 /**
1204 * @brief operator uint32_t converts to a uint32_t, truncating towards zero
1205 */
1206 [[nodiscard]] FP128_INLINE constexpr operator uint32_t() const noexcept { return to_integer<uint32_t>(); }
1207 /**
1208 * @brief operator int32_t converts to a int32_t, truncating towards zero
1209 */
1210 [[nodiscard]] FP128_INLINE constexpr operator int32_t() const noexcept { return to_integer<int32_t>(); }
1211 /// @}
1212
1213 /**
1214 * @name long double
1215 *
1216 * What a long double is depends on the platform: a plain double under MSVC, the x87 80 bit
1217 * extended format on x86 under GCC and Clang, and binary128 itself on AArch64 Linux. The two
1218 * wider ones are converted through their encoding rather than through double, which would
1219 * round away the bits they have over it.
1220 * @{
1221 */
1222#if LDBL_MANT_DIG == 64
1223 /// @brief The x87 extended format: an explicit 64 bit significand, then sign and exponent.
1224 struct x87_bits {
1225 uint64_t mantissa; ///< Significand, its leading bit stored
1226 uint16_t sign_exponent; ///< Sign in bit 15, biased exponent below it
1227 unsigned char padding[sizeof(long double) - 10]; ///< Unused, outside the value representation
1228 };
1229 static_assert(sizeof(x87_bits) == sizeof(long double), "unexpected x87 long double layout");
1230#elif LDBL_MANT_DIG == 113
1231 /// @brief long double is binary128: the same encoding, in two QWORDs.
1232 struct binary128_bits {
1233 uint64_t low; ///< Low QWORD of the encoding
1234 uint64_t high; ///< High QWORD of the encoding
1235 };
1236 static_assert(sizeof(binary128_bits) == sizeof(long double), "unexpected binary128 long double layout");
1237#endif
1238
1239 /**
1240 * @brief Converts a long double wider than a double, exactly.
1241 * @param x Value to convert
1242 * @return The same value. A signaling NaN is quieted, the conversion being an operation.
1243 */
1244 [[nodiscard]] static FP128_INLINE constexpr float128 from_long_double(long double x) noexcept
1245 {
1246#if LDBL_MANT_DIG == 64
1247 const x87_bits bits = std::bit_cast<x87_bits>(x);
1248 const uint32_t sign = static_cast<uint32_t>(bits.sign_exponent >> 15);
1249 const int32_t biased = bits.sign_exponent & 0x7FFF;
1250 if (biased == 0x7FFF) {
1251 // An infinity has nothing but its leading bit set. Anything else is a NaN, whose
1252 // payload and quiet bit move to the top of the fraction.
1253 const uint64_t fraction = bits.mantissa & ~(1ull << 63);
1254 float128 res(fraction << 49, (static_cast<uint64_t>(sign) << 63) | (static_cast<uint64_t>(INF_EXP_BIASED) << EXP_SHIFT) | (fraction >> 15));
1255 if (res.is_signaling()) {
1256 detail::raise_flags(FE_INVALID);
1257 res = quiet_nan(res);
1258 }
1259 return res;
1260 }
1261 // A denormal is scaled like the smallest normal value, it only lacks the leading bit.
1262 return norm_round_pack(sign, ((biased == 0) ? 1 : biased) - EXP_BIAS - 63 + FRAC_BITS, bits.mantissa, 0, false);
1263#elif LDBL_MANT_DIG == 113
1264 const binary128_bits bits = std::bit_cast<binary128_bits>(x);
1265 return float128(bits.low, bits.high);
1266#else
1267 // A format this code does not know, such as the double-double of PowerPC: only the double
1268 // nearest to it is converted.
1269 return float128(static_cast<double>(x));
1270#endif
1271 }
1272
1273 /**
1274 * @brief operator long double
1275 *
1276 * The same as the conversion to double where long double is one. Elsewhere correctly rounded to
1277 * the wider format, or exact where long double is binary128.
1278 *
1279 * @return Object value.
1280 */
1281 [[nodiscard]] FP128_INLINE constexpr operator long double() const noexcept
1282 {
1283#if LDBL_MANT_DIG == 64
1284 x87_bits bits {};
1285 const uint16_t sign = static_cast<uint16_t>(get_sign() << 15);
1286 if (is_special()) {
1287 bits.sign_exponent = static_cast<uint16_t>(sign | 0x7FFF);
1288 bits.mantissa = 1ull << 63;
1289 if (is_nan()) {
1290 if (is_signaling())
1291 detail::raise_flags(FE_INVALID);
1292 bits.mantissa |= (1ull << 62) | nan_payload_top(FRAC_BITS - 1 - 62);
1293 }
1294 } else if (is_zero()) {
1295 bits.sign_exponent = sign;
1296 } else {
1297 // The exponent range is binary128's own, so only rounding the largest values up can
1298 // overflow; the subnormal range is narrower, its last bit being worth 2^-16445.
1299 const narrowed n = narrow<64, -16382, 16383>();
1300 if (n.to_inf) {
1301 bits.sign_exponent = static_cast<uint16_t>(sign | 0x7FFF);
1302 bits.mantissa = 1ull << 63;
1303 } else {
1304 bits.mantissa = n.sig;
1305 const int32_t biased = (n.sig >> 63) ? (n.lsb + 63 + EXP_BIAS) : 0;
1306 bits.sign_exponent = static_cast<uint16_t>(sign | static_cast<uint16_t>(biased));
1307 }
1308 }
1309 return std::bit_cast<long double>(bits);
1310#elif LDBL_MANT_DIG == 113
1311 return std::bit_cast<long double>(binary128_bits {low, high});
1312#else
1313 return operator double();
1314#endif
1315 }
1316 /// @}
1317 /**
1318 * @brief Converts to a std::string (slow) string holds all meaningful fraction bits.
1319 * @return object string representation
1320 */
1321 [[nodiscard]] FP128_INLINE operator std::string() const noexcept { return operator char*(); }
1322 /**
1323 * @brief Converts to a C string (slow) string holds all meaningful fraction bits.
1324 * @return object string representation
1325 */
1326 [[nodiscard]] explicit FP128_INLINE operator char*() const noexcept
1327 {
1328 // The buffer is thread local so that the pointer stays valid after the call returns, which
1329 // is what an implicit conversion to char* has to provide. It is large enough for the
1330 // longest shortest-form string: a sign, 36 digits, a point and a five digit exponent.
1331 static thread_local char str[64];
1332 const std::string text = detail::render(*this, '\0', -1, false, false, '-');
1333 const size_t length = (text.size() < sizeof(str) - 1) ? text.size() : sizeof(str) - 1;
1334 for (size_t i = 0; i < length; ++i)
1335 str[i] = text[i];
1336 str[length] = '\0';
1337 return str;
1338 }
1339 /**
1340 * @brief Writes the value in scientific notation into a caller supplied buffer.
1341 *
1342 * Kept for the callers that predate std::format support. Everything it does is also reachable
1343 * as fp128::to_chars(..., std::chars_format::scientific) or as std::format("{:e}", value),
1344 * both of which say what they produce more clearly.
1345 *
1346 * @param str Output buffer
1347 * @param buff_size Output buffer size in bytes
1348 */
1349 void to_e_format(char* str, int32_t buff_size) const
1350 {
1351 if (str == nullptr || buff_size < 1)
1352 return;
1353
1354 const std::string text = detail::render(*this, 'e', -1, false, false, '-');
1355 const size_t length = (text.size() < static_cast<size_t>(buff_size) - 1) ? text.size() : static_cast<size_t>(buff_size) - 1;
1356 for (size_t i = 0; i < length; ++i)
1357 str[i] = text[i];
1358 str[length] = '\0';
1359 }
1360
1361 //
1362 // math operators
1363 //
1364 /// @brief Largest scaling a shift or ldexp() ever needs: enough to take the largest finite value
1365 /// below half the smallest subnormal, or the smallest subnormal above the largest finite
1366 /// value. Larger counts are clamped to it, which keeps the exponent arithmetic in range.
1367 static constexpr int32_t SCALE_LIMIT = 2 * (EXP_BIAS + FRAC_BITS + 1);
1368
1369 /**
1370 * @brief Shift right this object, dividing it by a power of two.
1371 * @param shift Bits to shift. Values less than 1 do nothing, high values can cause the value to reach zero.
1372 * @return This object.
1373 */
1374 FP128_INLINE constexpr float128& operator>>=(int32_t shift) noexcept
1375 {
1376 if (shift < 1)
1377 return *this;
1378 if (is_special()) {
1379 if (is_nan())
1380 *this = propagate_nan(*this);
1381 return *this;
1382 }
1383
1384 uint64_t l, h;
1385 int32_t e;
1386 uint32_t s;
1387 get_components(l, h, e, s);
1388 e -= (shift < SCALE_LIMIT) ? shift : SCALE_LIMIT;
1389 // A subnormal or zero result is rounded once, here, in the current direction.
1390 set_components(l, h, e, s);
1391 return *this;
1392 }
1393 /**
1394 * @brief Shift left this object, multiplying it by a power of two.
1395 * @param shift Bits to shift. Values less than 1 do nothing, high values can cause the value to reach infinity.
1396 * @return This object.
1397 */
1398 FP128_INLINE constexpr float128& operator<<=(int32_t shift) noexcept
1399 {
1400 if (shift < 1)
1401 return *this;
1402 if (is_special()) {
1403 if (is_nan())
1404 *this = propagate_nan(*this);
1405 return *this;
1406 }
1407
1408 uint64_t l, h;
1409 int32_t e;
1410 uint32_t s;
1411 get_components(l, h, e, s);
1412 e += (shift < SCALE_LIMIT) ? shift : SCALE_LIMIT;
1413 set_components(l, h, e, s);
1414 return *this;
1415 }
1416 /**
1417 * @brief Performs right shift operation.
1418 *
1419 * Hinted rather than forced, unlike the other one line forwarders (see FP128_FORCE_INLINE).
1420 * What it forwards to is not cheap: operator>>= splits the value into components and
1421 * reassembles it, which brings the subnormal handling of get_components() and
1422 * set_components() along with it. Forcing this pair open cost ~9% of the float128 Mandelbrot
1423 * benchmark, which shifts inside a loop that already inlines an add, a multiply and two
1424 * squares. Left as a hint, the shift is still inlined wherever the caller has room for it.
1425 *
1426 * @param shift bits to shift
1427 * @return Temporary object with the result of the operation
1428 */
1429 template <typename T> FP128_INLINE constexpr float128 operator>>(T shift) const noexcept
1430 {
1431 float128 temp(*this);
1432 return temp >>= static_cast<int32_t>(shift);
1433 }
1434 /**
1435 * @brief Performs left shift operation.
1436 * Hinted rather than forced, see operator>> above.
1437 * @param shift bits to shift
1438 * @return Temporary object with the result of the operation
1439 */
1440 template <typename T> FP128_INLINE constexpr float128 operator<<(T shift) const noexcept
1441 {
1442 float128 temp(*this);
1443 return temp <<= static_cast<int32_t>(shift);
1444 }
1445
1446 /**
1447 * @brief Add a value to this object
1448 * @param rhs Right hand side operand
1449 * @return This object.
1450 */
1451 FP128_INLINE constexpr float128& operator+=(const float128& rhs) noexcept
1452 {
1453 // check trivial cases
1454 if (is_special() || rhs.is_special()) {
1455 // A NaN operand propagates. Adding infinities of opposite signs is the invalid
1456 // operation and produces a NaN as well.
1457 if (is_nan() || rhs.is_nan()) {
1458 *this = propagate_nan(*this, rhs);
1459 return *this;
1460 }
1461 if (is_inf() && rhs.is_inf() && get_sign() != rhs.get_sign()) {
1462 *this = invalid_operation();
1463 return *this;
1464 }
1465
1466 // Either a single operand is infinite, or both are infinite with the same sign.
1467 // In both cases the result is that infinity, keeping its own sign.
1468 if (rhs.is_inf())
1469 *this = rhs;
1470 return *this;
1471 }
1472
1473 // A zero operand leaves the other one exactly. Two zeros of opposite sign make an exact
1474 // zero sum, which IEEE 754 makes positive in every rounding direction but downward.
1475 if (rhs.is_zero()) {
1476 if (is_zero() && get_sign() != rhs.get_sign())
1478 return *this;
1479 }
1480 if (is_zero()) {
1481 *this = rhs;
1482 return *this;
1483 }
1484
1485 uint32_t sign, rhs_sign;
1486 int32_t expo, rhs_expo;
1487 uint64_t l1, h1, l2, h2;
1488 get_components(l1, h1, expo, sign);
1489 rhs.get_components(l2, h2, rhs_expo, rhs_sign);
1490
1491 // Both mantissas are moved up so their leading one sits at bit 125. That leaves the
1492 // alignment thirteen bits to shift the smaller operand into before anything falls off,
1493 // a bit above for the carry of an addition, and the top bit clear.
1494 constexpr int32_t room = 127 - 2 - FRAC_BITS;
1495
1496 // Exponents this far apart leave the smaller operand below a quarter of the larger one's
1497 // last place, so rounding to nearest returns the larger one unchanged. The other
1498 // directions can still move the result by one place, so they take the full path.
1500 if (expo - rhs_expo > FRAC_BITS + room) {
1501 detail::raise_flags(FE_INEXACT);
1502 return *this;
1503 }
1504 if (rhs_expo - expo > FRAC_BITS + room) {
1505 detail::raise_flags(FE_INEXACT);
1506 *this = rhs;
1507 return *this;
1508 }
1509 }
1510
1511 // Make the first operand the one with the larger exponent, so only the second one is
1512 // ever shifted right.
1513 if (expo < rhs_expo) {
1514 std::swap(l1, l2);
1515 std::swap(h1, h2);
1516 std::swap(expo, rhs_expo);
1517 std::swap(sign, rhs_sign);
1518 }
1519
1520 const int32_t diff = expo - rhs_expo;
1521 shift_left128_inplace_safe(l1, h1, room);
1522 if (diff <= room) {
1523 shift_left128_inplace_safe(l2, h2, room - diff);
1524 } else {
1525 // What is shifted out is jammed into the lowest bit rather than rounded away. Rounding
1526 // here and again after the sum, as this used to, decided the direction from a window
1527 // of three bits and misjudged every case the bits further down would have settled.
1528 // The jammed bit lands at least eleven places under the guard bit of the sum, which
1529 // is enough for it to stand in for everything it replaced.
1530 shift_right_jam128(l2, h2, diff - room);
1531 }
1532
1533 if (sign == rhs_sign) {
1534 const uint8_t carry = addcarryx_u64(0, l1, l2, &l1);
1535 addcarryx_u64(carry, h1, h2, &h1);
1536 } else {
1537 uint8_t borrow = subborrow_u64(0, l1, l2, &l1);
1538 borrow = subborrow_u64(borrow, h1, h2, &h1);
1539 // Only operands with equal exponents can leave a negative difference, in which case
1540 // the second operand was the larger and its sign wins.
1541 if (borrow != 0) {
1542 twos_complement128(l1, h1);
1543 sign = rhs_sign;
1544 }
1545 if ((l1 | h1) == 0) {
1546 *this = float128(0, static_cast<uint64_t>(exact_zero_sign()) << 63);
1547 return *this;
1548 }
1549 }
1550
1551 *this = norm_round_pack(sign, expo - room, l1, h1, false);
1552 return *this;
1553 }
1554 /**
1555 * @brief Add a value to this object
1556 * @param rhs Right hand side operand
1557 * @return This object.
1558 */
1559 template <typename T> FP128_FORCE_INLINE constexpr float128& operator+=(const T& rhs) { return operator+=(float128(rhs)); }
1560 /**
1561 * @brief Subtract a value from this object
1562 * @param rhs Right hand side operand
1563 * @return This object.
1564 */
1565 FP128_FORCE_INLINE constexpr float128& operator-=(const float128& rhs) noexcept { return *this += (-rhs); }
1566 /**
1567 * @brief Subtract a value from this object
1568 * @param rhs Right hand side operand
1569 * @return This object.
1570 */
1571 template <typename T> FP128_FORCE_INLINE constexpr float128& operator-=(const T& rhs) { return operator+=(-float128(rhs)); }
1572 /**
1573 * @brief Multiply a value to this object
1574 * @param rhs Right hand side operand
1575 * @return This object.
1576 */
1577 FP128_INLINE constexpr float128& operator*=(const float128& rhs) noexcept
1578 {
1579 // check trivial cases
1580 if (is_special() || rhs.is_special()) {
1581 // A NaN operand propagates, and inf * zero is the invalid operation.
1582 // Note the zero tests are only reachable for the operand that is not special.
1583 if (is_nan() || rhs.is_nan()) {
1584 *this = propagate_nan(*this, rhs);
1585 return *this;
1586 }
1587 if ((is_inf() && rhs.is_zero()) || (is_zero() && rhs.is_inf())) {
1588 *this = invalid_operation();
1589 return *this;
1590 }
1591
1592 // at least one operand is infinite, the result is infinite with the combined sign
1593 const uint32_t res_sign = get_sign() ^ rhs.get_sign();
1594 *this = inf();
1595 set_sign(res_sign);
1596 return *this;
1597 } else if (is_zero() || rhs.is_zero()) {
1598 // the sign of a zero product is the combination of both operand signs
1599 const uint32_t res_sign = get_sign() ^ rhs.get_sign();
1600 *this = 0;
1601 set_sign(res_sign);
1602 return *this;
1603 }
1604 // extract fractions and exponents
1605 uint32_t sign, rhs_sign;
1606 int32_t expo, rhs_expo;
1607 uint64_t l1, h1, l2, h2;
1608 get_components(l1, h1, expo, sign);
1609 rhs.get_components(l2, h2, rhs_expo, rhs_sign);
1610 // Deliberately asked of the objects rather than derived from the mantissas above, even
1611 // though get_components() has just produced the bits this needs. Testing the raw value
1612 // leaves the question independent of the extraction, so it can be answered alongside it;
1613 // phrasing it as (h1 == FRAC_UNITY && l1 == 0) chains it behind instead and costs Clang
1614 // 15% of the multiply benchmark, against no gain on MSVC.
1615 bool is_exp2 = is_exponent_of_2();
1616 bool rhs_is_exp2 = rhs.is_exponent_of_2();
1617
1618 // add the exponents
1619 expo += rhs_expo;
1620
1621 // optimize for exponents of 2
1622 if (is_exp2 || rhs_is_exp2) {
1623 // copy the fraction as needed
1624 if (is_exp2) {
1625 l1 = l2;
1626 h1 = h2;
1627 }
1628
1629 set_components(l1, h1, expo, sign ^ rhs_sign);
1630 return *this;
1631 }
1632
1633 // multiply the fractions
1634 // the fractions are in u16.112 precision
1635 // the result will be u32.224 precision and will be shifted-right by 112 bit
1636 uint64_t res[4]; // 256 bit of result
1637 uint64_t temp1[2], temp2[2];
1638
1639 // multiply low QWORDs
1640 res[0] = mulx_u64(l1, l2, &res[1]);
1641
1642 // multiply high QWORDs (overflow can happen)
1643 res[2] = mulx_u64(h1, h2, &res[3]);
1644
1645 // multiply low this and high rhs
1646 temp1[0] = mulx_u64(l1, h2, &temp1[1]);
1647 uint8_t carry = addcarryx_u64(0, res[1], temp1[0], &res[1]);
1648 res[3] += addcarryx_u64(carry, res[2], temp1[1], &res[2]);
1649
1650 // multiply high this and low rhs
1651 temp2[0] = mulx_u64(h1, l2, &temp2[1]);
1652 carry = addcarryx_u64(0, res[1], temp2[0], &res[1]);
1653 res[3] += addcarryx_u64(carry, res[2], temp2[1], &res[2]);
1654
1655 // extract the bits from res[] keeping the precision the same as this object
1656 // shift result by F
1657 constexpr int32_t index = 1;
1658 constexpr int32_t lsb = (FRAC_BITS & 63) - 1; // bit within the 64bit data pointed by res[index], one short so the guard bit stays
1659
1660 const uint64_t sticky_bits = res[0] | (res[1] & FP128_MAX_VALUE_64(lsb));
1661 l1 = shift_right128(res[index], res[index + 1], lsb); // custom function is 20% faster in Mandelbrot than the intrinsic
1662 h1 = shift_right128(res[index + 1], res[index + 2], lsb);
1663 --expo;
1664
1665 const uint64_t extra = norm_product(l1, h1, expo, sticky_bits != 0);
1666 *this = round_pack(sign ^ rhs_sign, expo, l1, h1, extra);
1667 return *this;
1668 }
1669 /**
1670 * @brief Squares this object in place.
1671 *
1672 * Cheaper than operator*=(*this) on several counts:
1673 * - a square is symmetric, so the two cross products of the fraction multiply are the
1674 * same value and only three 64x64->128 bit multiplies are needed instead of four
1675 * - the result sign is always positive, so no sign combining is needed
1676 * - only one operand has to be tested for the special cases and for being an exponent
1677 * of 2, and in the exponent of 2 case the fraction does not have to be copied
1678 * - the exponents are added to each other, which is a doubling
1679 *
1680 * The result is identical to (*this) * (*this) for every value, specials included.
1681 *
1682 * @return This object.
1683 */
1684 FP128_INLINE constexpr float128& square() noexcept
1685 {
1686 // check trivial cases
1687 if (is_special()) {
1688 // a NaN stays a NaN, +/-inf squared is +inf
1689 *this = is_nan() ? propagate_nan(*this) : inf();
1690 return *this;
1691 } else if (is_zero()) {
1692 *this = 0;
1693 return *this;
1694 }
1695 // extract the fraction and exponent, the sign of a square is always positive
1696 uint32_t sign;
1697 int32_t expo;
1698 uint64_t l, h;
1699 get_components(l, h, expo, sign);
1700
1701 // add the exponent to itself
1702 expo += expo;
1703
1704 // optimize for exponents of 2, the fraction is unchanged by the multiply
1705 if (is_exponent_of_2()) {
1706 set_components(l, h, expo, 0);
1707 return *this;
1708 }
1709
1710 // square the fraction
1711 // the fraction is in u16.112 precision
1712 // the result will be u32.224 precision and will be shifted-right by 112 bit
1713 uint64_t res[4]; // 256 bit of result
1714 uint64_t cross[2];
1715
1716 // multiply the low QWORD by itself
1717 res[0] = mulx_u64(l, l, &res[1]);
1718
1719 // multiply the high QWORD by itself (overflow can happen)
1720 res[2] = mulx_u64(h, h, &res[3]);
1721
1722 // the low * high cross product, which appears twice in the sum
1723 cross[0] = mulx_u64(l, h, &cross[1]);
1724
1725 uint8_t carry = addcarryx_u64(0, res[1], cross[0], &res[1]);
1726 res[3] += addcarryx_u64(carry, res[2], cross[1], &res[2]);
1727
1728 carry = addcarryx_u64(0, res[1], cross[0], &res[1]);
1729 res[3] += addcarryx_u64(carry, res[2], cross[1], &res[2]);
1730
1731 // extract the bits from res[] keeping the precision the same as this object
1732 constexpr int32_t index = 1;
1733 constexpr int32_t lsb = (FRAC_BITS & 63) - 1; // bit within the 64bit data pointed by res[index] minus 1 to improve rounding
1734
1735 const uint64_t sticky_bits = res[0] | (res[1] & FP128_MAX_VALUE_64(lsb));
1736 l = shift_right128(res[index], res[index + 1], lsb);
1737 h = shift_right128(res[index + 1], res[index + 2], lsb);
1738 --expo;
1739
1740 const uint64_t extra = norm_product(l, h, expo, sticky_bits != 0);
1741 *this = round_pack(0, expo, l, h, extra);
1742 return *this;
1743 }
1744 /**
1745 * @brief Multiply a value to this object
1746 * @param rhs Right hand side operand
1747 * @return This object.
1748 */
1749 template <typename T> FP128_FORCE_INLINE constexpr float128& operator*=(const T& rhs) { return operator*=(float128(rhs)); }
1750 /**
1751 * @brief Divide this object by a value
1752 * @param rhs Right hand side operand
1753 * @return This object.
1754 */
1756 {
1757 // check trivial cases
1758 // A NaN operand propagates, and zero / zero and inf / inf are the invalid operation.
1759 if (is_nan() || rhs.is_nan()) {
1760 *this = propagate_nan(*this, rhs);
1761 return *this;
1762 }
1763 if ((is_zero() && rhs.is_zero()) || (is_inf() && rhs.is_inf())) {
1764 *this = invalid_operation();
1765 return *this;
1766 }
1767
1768 // the sign of any of the results below is the combination of both operand signs
1769 const uint32_t res_sign = get_sign() ^ rhs.get_sign();
1770
1771 // An infinite dividend or a zero divisor produce an infinity, a zero dividend or an
1772 // infinite divisor produce a zero. The combinations where both apply, which are the
1773 // two invalid operations, were already handled above. Only a finite dividend over a zero
1774 // is the division by zero exception; an infinite one is exact.
1775 if (is_inf() || rhs.is_zero()) {
1776 if (!is_inf())
1777 detail::raise_flags(FE_DIVBYZERO);
1778 *this = inf();
1779 set_sign(res_sign);
1780 return *this;
1781 } else if (is_zero() || rhs.is_inf()) {
1782 *this = 0;
1783 set_sign(res_sign);
1784 return *this;
1785 }
1786
1787 // extract fractions and exponents
1788 uint32_t sign, rhs_sign;
1789 int32_t expo, rhs_expo;
1790 uint64_t l1, h1, l2, h2;
1791 get_components(l1, h1, expo, sign);
1792 rhs.get_components(l2, h2, rhs_expo, rhs_sign);
1793
1794 // subtract the exponents
1795 expo -= rhs_expo;
1796
1797 // optimize for rhs value is an exponent of 2
1798 if (rhs.is_exponent_of_2()) {
1799 set_components(l1, h1, expo, sign ^ rhs_sign);
1800 return *this;
1801 }
1802
1803 // divide the fractions
1804 uint64_t q[4] {};
1805 const uint64_t nom[4] = {0, 0, l1, h1};
1806 const uint64_t denom[2] = {l2, h2};
1807
1808 uint64_t rem[2] {};
1809 // get_components() normalizes even a subnormal, so the divisor's fraction always carries the
1810 // unity bit at bit 112 and its high QWORD is never zero. div_128bit's precondition therefore
1811 // holds unconditionally here, unlike in fixed_point128 where a tiny divisor has to be routed
1812 // to div_64bit instead.
1813 if (div_128bit<array_length(nom)>(q, rem, nom, denom)) {
1814 // The dividend was scaled by 2^128 and both mantissas are in [2^112, 2^113), so the
1815 // quotient is in (2^127, 2^129): its leading one is at bit 128 when the dividend's
1816 // mantissa is the larger and at bit 127 otherwise. Keeping 113 bits means shifting out
1817 // 16 or 15 of them.
1818 //
1819 // The shift has to follow the quotient. A fixed shift of 15, as this used to have,
1820 // left a quotient that led at bit 127 already in place, and the normalization after it
1821 // took that as nothing to round: every such quotient was truncated, which made close
1822 // to half of all divisions with the smaller mantissa on top come out one place low.
1823 const int32_t top = static_cast<int32_t>(q[2] & 1);
1824 const int32_t shift = (127 - FRAC_BITS) + top;
1825 // What is shifted out leads the extra word; a non zero remainder means the quotient
1826 // continues below it and only has to register as a sticky bit.
1827 const uint64_t extra = (q[0] << (64 - shift)) | (((rem[0] | rem[1]) != 0) ? 1 : 0);
1828 l1 = shift_right128(q[0], q[1], shift);
1829 h1 = shift_right128(q[1], q[2], shift);
1830 expo += top - 1;
1831 *this = round_pack(sign ^ rhs_sign, expo, l1, h1, extra);
1832 } else { // error
1833 *this = inf();
1834 }
1835 return *this;
1836 }
1837 /**
1838 * @brief Divide this object by a value
1839 * @param rhs Right hand side operand
1840 * @return This object.
1841 */
1842 template <typename T> FP128_FORCE_INLINE float128& operator/=(const T& rhs) { return operator/=(float128(rhs)); }
1843
1844 //
1845 // unary operations
1846 //
1847 /**
1848 * @brief Convert to bool
1849 */
1850 [[nodiscard]] FP128_FORCE_INLINE constexpr operator bool() const noexcept { return !is_zero(); }
1851 /**
1852 * @brief Logical not (!). Opposite of operator bool.
1853 * Uses is_zero() rather than testing the raw words: negative zero has its sign bit set and
1854 * would otherwise be reported as a non zero value.
1855 */
1856 [[nodiscard]] FP128_FORCE_INLINE constexpr bool operator!() const noexcept { return is_zero(); }
1857 /**
1858 * @brief Unary +. Returns a copy of the object.
1859 */
1860 [[nodiscard]] FP128_FORCE_INLINE constexpr float128 operator+() const noexcept { return *this; }
1861 /**
1862 * @brief Unary -. Returns a copy of the object with sign inverted.
1863 */
1864 [[nodiscard]] FP128_FORCE_INLINE constexpr float128 operator-() const noexcept { return float128(low, high ^ SIGN_MASK); }
1865
1866 //
1867 // useful public functions
1868 //
1869 /**
1870 * @brief Returns true if the value is positive (including zero and NaN)
1871 * @return True when the sign is 0
1872 */
1873 [[nodiscard]] FP128_FORCE_INLINE constexpr bool is_positive() const noexcept { return 0 == (high & SIGN_MASK); }
1874 /**
1875 * @brief Returns true if the value is negative (including zero and NaN).
1876 * @return True when the sign is 1
1877 */
1878 [[nodiscard]] FP128_FORCE_INLINE constexpr bool is_negative() const noexcept { return 0 != (high & SIGN_MASK); }
1879 /**
1880 * @brief Returns true if and only if the value is ±0.
1881 * @return Returns true if the value is zero
1882 */
1883 [[nodiscard]] FP128_FORCE_INLINE constexpr bool is_zero() const noexcept { return 0 == low && 0 == (high & ~SIGN_MASK); }
1884 /**
1885 * @brief Returns true if and only if x is zero, subnormal or normal (not infinite or NaN).
1886 * @return True if and only if x is zero, subnormal or normal (not infinite or NaN).
1887 */
1888 [[nodiscard]] FP128_FORCE_INLINE constexpr bool is_finite() const noexcept { return !is_special(); }
1889 /**
1890 * @brief Tests if the value is subnormal: non zero, and below the smallest normal magnitude.
1891 *
1892 * A zero shares the exponent field of the subnormals but is not one of them, as IEEE 754's
1893 * isSubnormal has it. The arithmetic itself tests the raw field (see get_components()), where
1894 * treating a zero alike is harmless and saves the test of the fraction.
1895 *
1896 * @return True when the value is subnormal, false for a zero.
1897 */
1898 [[nodiscard]] FP128_FORCE_INLINE constexpr bool is_subnormal() const noexcept { return get_exponent_bits() == 0 && (low | get_fraction_bits()) != 0; }
1899 /**
1900 * @brief Tests if the value is normal (not zero, subnormal, infinite, or NaN)
1901 * @return True if and only if the value is normal
1902 */
1903 [[nodiscard]] FP128_FORCE_INLINE constexpr bool is_normal() const noexcept { return get_exponent_bits() != 0 && get_exponent_bits() != INF_EXP_BIASED; }
1904 /**
1905 * @brief Tests if this value is a NaN
1906 * @return True when the value is a NaN
1907 */
1908 [[nodiscard]] FP128_FORCE_INLINE constexpr bool is_nan() const
1909 {
1910 // fraction is zero for +- INF, non-zero for NaN
1911 return get_exponent_bits() == INF_EXP_BIASED && (get_fraction_bits() != 0 || low != 0);
1912 }
1913 /**
1914 * @brief Tests if this value is a signaling NaN
1915 * @return True if this value is a signaling NaN
1916 */
1917 [[nodiscard]] FP128_FORCE_INLINE constexpr bool is_signaling() const
1918 {
1919 // A NaN is quiet when the leading fraction bit is set and signaling when it is clear,
1920 // which is what every binary interchange format in IEEE 754-2008 uses.
1921 return is_nan() && (high & QUIET_NAN_BIT) == 0;
1922 }
1923 /**
1924 * @brief Tests if this value is an Infinite (negative or positive)
1925 * @return True when the value is an Infinite
1926 */
1927 [[nodiscard]] FP128_FORCE_INLINE constexpr bool is_inf() const
1928 {
1929 // fraction is zero for +- INF, non-zero for NaN
1930 return get_exponent_bits() == INF_EXP_BIASED && get_fraction_bits() == 0;
1931 }
1932 /**
1933 * @brief Tests if the value is an exponent of 2 (fraction part is zero)
1934 * @return True when the value is an exponent of 2
1935 */
1936 [[nodiscard]] FP128_FORCE_INLINE constexpr bool is_exponent_of_2() const
1937 {
1938 // fraction is zero for +- INF, non-zero for NaN
1939 return get_fraction_bits() == 0 && low == 0;
1940 }
1941 /**
1942 * @brief return true when the value is either an inf or nan
1943 * @return true for inf and nan
1944 */
1945 [[nodiscard]] FP128_FORCE_INLINE constexpr bool is_special() const
1946 {
1947 // fraction is zero for +- INF, non-zero for NaN
1948 return get_exponent_bits() == INF_EXP_BIASED;
1949 }
1950 /**
1951 * @brief Returns if the value is an integer (fraction is zero).
1952 * @return True when the value is an integer, either zero included; false for an infinity or a NaN.
1953 */
1954 [[nodiscard]] FP128_FORCE_INLINE constexpr bool is_int() const
1955 {
1956 // An infinity or a NaN has an exponent beyond every integer's, but is not one.
1957 if (is_special())
1958 return false;
1959 // A zero's exponent field reads as the lowest exponent of all, which the test below would
1960 // take for a value under one.
1961 if (is_zero())
1962 return true;
1963 int32_t expo = get_exponent();
1964 if (expo < 0)
1965 return false;
1966 if (expo >= FRAC_BITS)
1967 return true;
1968 return get_fraction().is_zero();
1969 }
1970 /**
1971 * @brief get a specific bit within the float128 data
1972 * @param bit bit to get [0,127]
1973 * @return 0 or 1. Undefined when bit > 127
1974 */
1975 [[nodiscard]] FP128_FORCE_INLINE constexpr int32_t get_bit(uint32_t bit) const noexcept
1976 {
1977 if (bit < 64) {
1978 return FP128_GET_BIT(low, bit);
1979 }
1980 return FP128_GET_BIT(high, bit - 64);
1981 }
1982 /**
1983 * @brief Return the fraction part as a float128
1984 */
1985 [[nodiscard]] FP128_INLINE constexpr float128 get_fraction() const
1986 {
1987 auto expo = get_exponent();
1988 int32_t frac_bits = static_cast<int32_t>(FRAC_BITS) - expo;
1989 // all the bits are fraction
1990 if (frac_bits > FRAC_BITS)
1991 return *this;
1992 // the exponent is too large to hold a fraction
1993 if (frac_bits <= 0)
1994 return 0;
1995
1996 uint64_t l = low, h = get_fraction_bits();
1997 if (frac_bits <= 64) {
1998 h = 0;
1999 l &= FP128_MAX_VALUE_64(frac_bits);
2000 } else {
2001 h &= FP128_MAX_VALUE_64(frac_bits - 64);
2002 }
2003
2004 // no fraction bits are high
2005 if (l == 0 && h == 0) {
2006 return 0;
2007 }
2008
2009 // find the msb and shift to bit 112
2010 int32_t msb = static_cast<int32_t>(log2(l, h));
2011 int32_t shift = FRAC_BITS - msb; // how many bits to shift left
2012 shift_left128_inplace_safe(l, h, shift);
2013 expo -= shift;
2014 float128 res(l, h, expo + EXP_BIAS, get_sign());
2015 return res;
2016 }
2017 /**
2018 * @brief Reads the biased exponent field out of the high QWORD.
2019 *
2020 * This accessor and the three below it are the only places that know where the fields sit
2021 * within the high QWORD, which is the same layout the (l, h, e, s) constructor assembles.
2022 * They deliberately shift and mask rather than going through the _float128_bits view: that
2023 * would be a read of the inactive member of a union, which constant evaluation rejects.
2024 *
2025 * @return The biased exponent, in [0, 0x7FFF].
2026 */
2027 [[nodiscard]] FP128_FORCE_INLINE constexpr uint64_t get_exponent_bits() const noexcept { return (high >> EXP_SHIFT) & EXP_MASK; }
2028 /**
2029 * @brief Sets the biased exponent field, leaving the fraction and the sign alone.
2030 * @param e Biased exponent. Bits above the 15 the field holds are dropped.
2031 */
2032 FP128_FORCE_INLINE constexpr void set_exponent_bits(uint64_t e) noexcept { high = (high & ~(EXP_MASK << EXP_SHIFT)) | ((e & EXP_MASK) << EXP_SHIFT); }
2033 /**
2034 * @brief Reads the upper 48 bits of the fraction out of the high QWORD.
2035 * @return Bits [111:64] of the fraction.
2036 */
2037 [[nodiscard]] FP128_FORCE_INLINE constexpr uint64_t get_fraction_bits() const noexcept { return high & UPPER_FRAC_MASK; }
2038 /**
2039 * @brief Sets the upper 48 bits of the fraction, leaving the exponent and the sign alone.
2040 * @param f Fraction bits. Bits above the 48 the field holds are dropped.
2041 */
2042 FP128_FORCE_INLINE constexpr void set_fraction_bits(uint64_t f) noexcept { high = (high & ~UPPER_FRAC_MASK) | (f & UPPER_FRAC_MASK); }
2043 /**
2044 * @brief Inverts the sign
2045 */
2046 FP128_FORCE_INLINE constexpr void invert_sign() noexcept { high ^= SIGN_MASK; }
2047 /**
2048 * @brief Sets the sign
2049 */
2050 FP128_FORCE_INLINE constexpr void set_sign(uint64_t s) noexcept { high = (high & ~SIGN_MASK) | ((s & 1) << 63); }
2051 /**
2052 * @brief Gets the sign
2053 */
2054 [[nodiscard]] FP128_FORCE_INLINE constexpr uint32_t get_sign() const noexcept { return static_cast<uint32_t>(high >> 63); }
2055 /**
2056 * @brief Reads the raw binary128 encoding.
2057 *
2058 * The counterpart of the float128(low, high) constructor: the two together are what a
2059 * std::bit_cast to and from the storage would be, without needing the layout to be spelled
2060 * out at the call site. Nothing is interpreted, so a NaN keeps its payload and a subnormal is
2061 * not normalized - use get_components() for the value the encoding stands for.
2062 *
2063 * @param l Receives the low QWORD (fraction bits 63:0)
2064 * @param h Receives the high QWORD (sign, exponent, fraction bits 111:64)
2065 */
2066 FP128_FORCE_INLINE constexpr void get_bits(uint64_t& l, uint64_t& h) const noexcept
2067 {
2068 l = low;
2069 h = high;
2070 }
2071 /**
2072 * @brief Classifies the float128 value according to IEEE 754.
2073 * @return The classification category (normal, subnormal, zero, inf, or NaN).
2074 */
2075 [[nodiscard]] FP128_INLINE constexpr float128_class_t get_class() const noexcept
2076 {
2077 // inf and Nan
2078 if (get_exponent_bits() == INF_EXP_BIASED) {
2079 if (is_nan())
2080 return is_signaling() ? signalingNaN : quietNaN;
2081 return is_positive() ? positiveInfinity : negativeInfinity;
2082 }
2083 if (is_zero()) {
2084 return is_positive() ? positiveZero : negativeZero;
2085 }
2086 if (is_subnormal()) {
2087 return is_positive() ? positiveSubnormal : negativeSubnormal;
2088 }
2089
2090 return is_positive() ? positiveNormal : negativeNormal;
2091 }
2092 /**
2093 * @brief Returns the exponent of the object - like the base 2 exponent of a floating point
2094 * A value of 2.1 would return 1, values in the range [0.5,1.0) would return -1.
2095 * @return Exponent of the number
2096 */
2097 [[nodiscard]] FP128_FORCE_INLINE constexpr int32_t get_exponent() const noexcept { return static_cast<int32_t>(get_exponent_bits()) - EXP_BIAS; }
2098 /**
2099 * @brief Set the exponent
2100 * @param e Exponent value
2101 */
2102 FP128_FORCE_INLINE constexpr void set_exponent(int32_t e) noexcept
2103 {
2104 e += EXP_BIAS;
2105 assert(e >= 0);
2106 assert(e <= INF_EXP_BIASED);
2107 set_exponent_bits(static_cast<uint64_t>(e));
2108 }
2109 /**
2110 * @brief break the float into its components.
2111 * Normalizes subnormal values
2112 *
2113 * Forced open rather than merely offered for inlining, which is an exception to the rule stated
2114 * on FP128_FORCE_INLINE: this has a body of its own, so it would otherwise be FP128_INLINE. The
2115 * body is a handful of shifts and masks off the object's own bits, and every arithmetic operator
2116 * and math function opens with two of these calls, so what the caller gains is not the call
2117 * itself but the constant folding across it - the exponent and sign arithmetic that follows
2118 * collapses only once the components are visible. Clang declined the invitation where MSVC
2119 * accepted it, which is what made this measurable rather than academic: on 2026-08-15 clang-cl
2120 * left this and the rounding step after the division (then norm_fraction_sticky(), now
2121 * round_pack(), which is forced open for the same reason) out of line in operator/=, and float128
2122 * division measured 13.0 M/s against MSVC's 20.9 M/s.
2123 *
2124 * @param l Reference to receive the low fraction
2125 * @param h Reference to receive the high fraction
2126 * @param e Reference to receive the unbiased exponent
2127 * @param s Reference to receive the sign
2128 */
2129 FP128_FORCE_INLINE constexpr void get_components(uint64_t& l, uint64_t& h, int32_t& e, uint32_t& s) const noexcept
2130 {
2131 l = low;
2132 h = get_fraction_bits();
2133 e = get_exponent();
2134 s = get_sign();
2135
2136 // The raw exponent field rather than is_subnormal(): a zero takes this branch too, which
2137 // leaves its components zero, and the test stays a single compare on the hot path.
2138 if (get_exponent_bits() == 0) {
2139 // shift the bits to the left so the msb is on bit 112
2140 auto shift = FRAC_BITS - static_cast<int32_t>(log2(l, h));
2141 shift_left128_inplace_safe(l, h, shift);
2142
2143 // A subnormal has no implicit leading one, so its stored exponent field says nothing
2144 // about its magnitude - every subnormal holds the same one. What the value is worth is
2145 // decided entirely by where its leading bit sits: the fraction is scaled by 2^-16494,
2146 // and normalizing it left by `shift` puts the exponent that many places below the
2147 // smallest normal one. Adding the shift to the stored exponent instead, as this used
2148 // to, put the smallest subnormal 223 binades above where it belongs and made every
2149 // operation on a subnormal operand return an unrelated value. set_components() has
2150 // always used this convention, which is why the two did not round trip.
2151 e = SUBNORM_EXP_UNBIASED + 1 - shift;
2152 }
2153 // normal numbers
2154 else if (is_normal()) {
2155 // add the unity value
2156 h |= FRAC_UNITY;
2157 }
2158 }
2159 /**
2160 * @brief Number of Mercator series terms log2() needs.
2161 *
2162 * The reduction leaves |z| <= 2^-6, so term n is bounded by 2^(-6n), and the series is cut off
2163 * once that is below the last bit of a 113 bit mantissa with eight bits to spare.
2164 */
2165 static constexpr int32_t LOG2_TERMS = (FRAC_BITS + 1 + 8 + log2_reduction_bits - 1) / log2_reduction_bits;
2166
2167 /**
2168 * @name Rounding
2169 *
2170 * Every operation whose exact result may not be representable ends in round_pack(), which is
2171 * the one place a result is rounded. IEEE 754 requires each operation to behave as if it first
2172 * computed the exact result and then rounded it once, to the destination format, in the
2173 * current rounding direction - and the destination format includes its subnormal range, where
2174 * fewer than 113 bits are kept. The operations used to round to 113 bits first and then let
2175 * set_components() round a second time when the result turned out to be subnormal, which gave
2176 * the wrong last bit for about one subnormal result in ten. They also decided the direction
2177 * from a window of three bits, which cannot tell a tie from a value just above one when the
2178 * bits that settle it lie further down.
2179 *
2180 * The shape follows Berkeley SoftFloat's roundPackToF128: the caller hands over a 113 bit
2181 * significand and a 64 bit word of the bits below it, left aligned, with anything further down
2182 * jammed into its lowest bit. The top bit of that word is the first bit dropped, and the word
2183 * being non zero means the result is inexact - which is all any rounding direction needs.
2184 * @{
2185 */
2186
2187 /**
2188 * @brief Shifts a significand and its extra word right, keeping a sticky record of what fell off.
2189 *
2190 * The bits shifted out of the significand move into the top of @p extra, and whatever drops
2191 * out of @p extra is jammed into its lowest bit rather than lost, so the word still tells an
2192 * exact result, a tie and a value above the tie apart.
2193 *
2194 * @param l Low QWORD of the significand
2195 * @param h High QWORD of the significand
2196 * @param extra Bits below the significand, left aligned
2197 * @param dist Bits to shift, at least one
2198 */
2199 FP128_FORCE_INLINE static constexpr void shift_right_jam128_extra(uint64_t& l, uint64_t& h, uint64_t& extra, int32_t dist) noexcept
2200 {
2201 FP128_ASSERT(dist >= 1);
2202 uint64_t sticky = extra;
2203 if (dist < 64) {
2204 extra = l << (64 - dist);
2205 l = (l >> dist) | (h << (64 - dist));
2206 h >>= dist;
2207 } else {
2208 if (dist == 64) {
2209 extra = l;
2210 l = h;
2211 } else {
2212 sticky |= l;
2213 if (dist < 128) {
2214 extra = h << (128 - dist);
2215 l = h >> (dist - 64);
2216 } else {
2217 // Everything is gone. At exactly 128 the top bit of h is the first bit dropped,
2218 // further out it is below it and only counts towards the sticky bit.
2219 extra = (dist == 128) ? h : ((h != 0) ? 1 : 0);
2220 l = 0;
2221 }
2222 }
2223 h = 0;
2224 }
2225 extra |= (sticky != 0) ? 1 : 0;
2226 }
2227
2228 /**
2229 * @brief Shifts a 128 bit value right, jamming any set bit that falls off into the lowest bit.
2230 *
2231 * The alignment step of an addition: the shifted operand only has to be accurate to the bit
2232 * below the guard bit of the sum, and a jammed lowest bit is enough to say there was more.
2233 *
2234 * Forced open, as are shift_right_jam128_extra() and norm_round_pack(), which addition reaches
2235 * through. Offered for inlining only, Clang kept all three out of line, the three outputs went
2236 * through memory on every call, and float128 addition measured 95 M/s against 174 M/s inlined
2237 * (P-core, 2026-10-05). MSVC inlined them either way.
2238 *
2239 * @param l Low QWORD
2240 * @param h High QWORD
2241 * @param dist Bits to shift, at least one
2242 */
2243 FP128_FORCE_INLINE static constexpr void shift_right_jam128(uint64_t& l, uint64_t& h, int32_t dist) noexcept
2244 {
2245 FP128_ASSERT(dist >= 1);
2246 if (dist < 64) {
2247 const uint64_t lost = l << (64 - dist);
2248 l = (l >> dist) | (h << (64 - dist)) | ((lost != 0) ? 1 : 0);
2249 h >>= dist;
2250 } else if (dist < 128) {
2251 const uint64_t lost = (dist == 64) ? l : (l | (h << (128 - dist)));
2252 l = ((dist == 64) ? h : (h >> (dist - 64))) | ((lost != 0) ? 1 : 0);
2253 h = 0;
2254 } else {
2255 l = ((l | h) != 0) ? 1 : 0;
2256 h = 0;
2257 }
2258 }
2259
2260 /**
2261 * @brief Whether rounding should add one unit in the last place.
2262 * @param mode Rounding direction
2263 * @param sign Sign of the result
2264 * @param extra Bits below the significand, left aligned and jammed
2265 * @return True when the magnitude has to be rounded up.
2266 */
2267 [[nodiscard]] FP128_FORCE_INLINE static constexpr bool round_increment(detail::rounding mode, uint32_t sign, uint64_t extra) noexcept
2268 {
2270 return extra >= (1ull << 63);
2272 return false;
2273 return extra != 0 && mode == ((sign != 0) ? detail::rounding::downward : detail::rounding::upward);
2274 }
2275
2276 /// @brief The largest finite magnitude's significand, high QWORD, with its leading one at bit 48.
2277 static constexpr uint64_t MAX_SIG_HIGH = FRAC_UNITY | UPPER_FRAC_MASK;
2278
2279 /**
2280 * @brief The slow half of round_pack(): results that overflow or are subnormal.
2281 * @param sign Sign of the result
2282 * @param exp Biased exponent less one, as round_pack() computes it
2283 * @param l Low QWORD of the significand
2284 * @param h High QWORD of the significand
2285 * @param extra Bits below the significand, left aligned and jammed
2286 * @param mode Rounding direction
2287 * @return The rounded result.
2288 */
2289 [[nodiscard]] FP128_INLINE static constexpr float128 round_pack_edge(uint32_t sign, int32_t exp, uint64_t l, uint64_t h, uint64_t extra,
2290 detail::rounding mode) noexcept
2291 {
2292 bool increment = round_increment(mode, sign, extra);
2293 if (exp < 0) {
2294 // Tininess is detected after rounding, the way x86 does it for double: the result is
2295 // tiny unless rounding it to 113 bits with an unbounded exponent would have carried it
2296 // up to the smallest normal value.
2297 const bool tiny = (exp < -1) || !increment || h != MAX_SIG_HIGH || l != UINT64_MAX;
2298 shift_right_jam128_extra(l, h, extra, -exp);
2299 exp = 0;
2300 if (tiny && extra != 0)
2301 detail::raise_flags(FE_UNDERFLOW);
2302 increment = round_increment(mode, sign, extra);
2303 } else if (exp > INF_EXP_BIASED - 2 || (exp == INF_EXP_BIASED - 2 && increment && h == MAX_SIG_HIGH && l == UINT64_MAX)) {
2304 detail::raise_flags(FE_OVERFLOW | FE_INEXACT);
2305 // Rounding to nearest and rounding away from zero overflow to infinity; the other two
2306 // directions stop at the largest finite value.
2308 return float128(0, (static_cast<uint64_t>(sign) << 63) | (static_cast<uint64_t>(INF_EXP_BIASED) << EXP_SHIFT));
2309 return float128(UINT64_MAX, (static_cast<uint64_t>(sign) << 63) | (static_cast<uint64_t>(INF_EXP_BIASED - 1) << EXP_SHIFT) | UPPER_FRAC_MASK);
2310 }
2311
2312 if (extra != 0)
2313 detail::raise_flags(FE_INEXACT);
2314 if (increment) {
2315 ++l;
2316 h += (l == 0) ? 1 : 0;
2317 if (mode == detail::rounding::nearest_even && (extra << 1) == 0)
2318 l &= ~1ull; // an exact tie goes to the even neighbour
2319 } else if ((l | h) == 0) {
2320 exp = 0;
2321 }
2322 return float128(l, (static_cast<uint64_t>(sign) << 63) + (static_cast<uint64_t>(exp) << EXP_SHIFT) + h);
2323 }
2324
2325 /**
2326 * @brief Rounds an exact result once, in the current rounding direction, and encodes it.
2327 *
2328 * The significand is added to the exponent field rather than merged into it: its leading one
2329 * sits on the lowest exponent bit, which is why the exponent is passed in less one. That makes
2330 * the carry of a significand that rounds up to the next power of two land in the exponent on
2331 * its own, and the carry out of the largest finite value land on infinity.
2332 *
2333 * @param sign Sign of the result
2334 * @param e Unbiased exponent of bit 112 of the significand
2335 * @param l Low QWORD of the significand
2336 * @param h High QWORD of the significand. The leading one must be at bit 48: a zero significand
2337 * is not accepted, the callers deal with an exact zero themselves.
2338 * @param extra Bits below the significand, left aligned, with anything further down jammed into
2339 * bit 0. Zero when the significand is exact.
2340 * @return The correctly rounded result, including its subnormal and overflow cases.
2341 */
2342 [[nodiscard]] FP128_FORCE_INLINE static constexpr float128 round_pack(uint32_t sign, int32_t e, uint64_t l, uint64_t h, uint64_t extra) noexcept
2343 {
2344 return round_pack(sign, e, l, h, extra, detail::current_rounding());
2345 }
2346 /// @overload
2347 /// @param sign Sign of the result
2348 /// @param e Unbiased exponent of bit 112 of the significand
2349 /// @param l Low QWORD of the significand
2350 /// @param h High QWORD of the significand, its leading one at bit 48
2351 /// @param extra Bits below the significand, left aligned, the rest jammed into bit 0
2352 /// @param mode Rounding direction to use instead of the current one
2353 /// @return The correctly rounded result, including its subnormal and overflow cases.
2354 [[nodiscard]] FP128_FORCE_INLINE static constexpr float128 round_pack(uint32_t sign, int32_t e, uint64_t l, uint64_t h, uint64_t extra,
2355 detail::rounding mode) noexcept
2356 {
2357 const int32_t exp = e + (EXP_BIAS - 1);
2358 // One unsigned comparison catches both a subnormal result (negative) and one that may
2359 // overflow (the top two exponents).
2360 if (static_cast<uint32_t>(exp) >= static_cast<uint32_t>(INF_EXP_BIASED - 2))
2361 return round_pack_edge(sign, exp, l, h, extra, mode);
2362
2363 if (extra != 0)
2364 detail::raise_flags(FE_INEXACT);
2365 // Without a branch: whether to round up depends on the bits being dropped, which is as good
2366 // as random, and a mispredicted branch here costs more than the arithmetic it would skip.
2367 const uint64_t increment = round_increment(mode, sign, extra) ? 1 : 0;
2368 h += addcarryx_u64(0, l, increment, &l);
2369 // an exact tie that was rounded up goes back down to the even neighbour
2371 l &= ~(((extra << 1) == 0) ? increment : 0);
2372 return float128(l, (static_cast<uint64_t>(sign) << 63) + (static_cast<uint64_t>(exp) << EXP_SHIFT) + h);
2373 }
2374
2375 /**
2376 * @brief Normalizes an exact non negative 128 bit significand and rounds it once.
2377 *
2378 * For results whose leading one can be anywhere: a sum after cancellation, a remainder, a
2379 * fraction. The value is (h:l) * 2^(e - 112).
2380 *
2381 * @param sign Sign of the result
2382 * @param e Exponent the value would have if its leading one were at bit 112
2383 * @param l Low QWORD
2384 * @param h High QWORD
2385 * @param sticky True when set bits below (h:l) were already dropped
2386 * @return The correctly rounded result.
2387 */
2388 [[nodiscard]] FP128_FORCE_INLINE static constexpr float128 norm_round_pack(uint32_t sign, int32_t e, uint64_t l, uint64_t h, bool sticky) noexcept
2389 {
2390 if ((l | h) == 0)
2391 return float128(0, static_cast<uint64_t>(sign) << 63);
2392
2393 const int32_t msb = static_cast<int32_t>(log2(l, h));
2394 uint64_t extra = sticky ? 1 : 0;
2395 if (msb > FRAC_BITS) {
2396 shift_right_jam128_extra(l, h, extra, msb - FRAC_BITS);
2397 } else if (msb < FRAC_BITS) {
2398 shift_left128_inplace_safe(l, h, FRAC_BITS - msb);
2399 }
2400 return round_pack(sign, e + msb - FRAC_BITS, l, h, extra);
2401 }
2402
2403 /**
2404 * @brief Builds a float128 from a 128 bit fraction, a value in [0,1).
2405 *
2406 * The counterpart of reading a mantissa out with get_components(): log2() does its argument
2407 * reduction and series on plain 128 bit fractions, and this is how the two results it ends up
2408 * with re-enter floating point.
2409 *
2410 * @param low Low QWORD of the fraction.
2411 * @param high High QWORD of the fraction.
2412 * @return The value the fraction stands for, correctly rounded, or zero if it is zero.
2413 */
2414 [[nodiscard]] static FP128_INLINE constexpr float128 from_fraction128(uint64_t low, uint64_t high) noexcept
2415 {
2416 // Bit 127 of the fraction is worth 2^-1, so a leading one at bit 112 would be worth 2^-16.
2417 return norm_round_pack(0, -16, low, high, false);
2418 }
2419
2420 /**
2421 * @brief Stores a significand and exponent, rounding when the value is subnormal.
2422 *
2423 * @param l Low part of the significand
2424 * @param h High part of the significand, which must have its leading one at bit 48 (bit 112 of
2425 * the whole) unless the significand is zero
2426 * @param e Unbiased exponent, can be any value: one past the format's range produces an
2427 * infinity, one below it a subnormal or a zero, rounded once in the current direction.
2428 * @param s Sign (1 is negative)
2429 */
2430 FP128_INLINE constexpr void set_components(uint64_t l, uint64_t h, int32_t e, uint32_t s) noexcept
2431 {
2432 if ((l | h) == 0) {
2433 *this = float128(0, static_cast<uint64_t>(s != 0) << 63);
2434 return;
2435 }
2436 *this = round_pack((s != 0) ? 1u : 0u, e, l, h, 0);
2437 }
2438 /// @}
2439
2440 /**
2441 * @name NaN results
2442 * @{
2443 */
2444 /// @brief x with its quiet bit set. The payload, and the sign, are kept.
2445 [[nodiscard]] FP128_FORCE_INLINE static constexpr float128 quiet_nan(const float128& x) noexcept { return float128(x.low, x.high | QUIET_NAN_BIT); }
2446
2447 /**
2448 * @brief The result of an operation with a NaN operand (IEEE 754-2008 6.2).
2449 *
2450 * A signaling NaN operand is the invalid operation. Either way the result is a quiet NaN, and
2451 * the standard recommends it be one of the inputs so that a payload survives the computation:
2452 * the first NaN operand is returned, quieted.
2453 *
2454 * @param a First operand
2455 * @param b Second operand
2456 * @return The quiet NaN to deliver.
2457 */
2458 [[nodiscard]] FP128_INLINE static constexpr float128 propagate_nan(const float128& a, const float128& b) noexcept
2459 {
2460 if (a.is_signaling() || b.is_signaling())
2461 detail::raise_flags(FE_INVALID);
2462 return quiet_nan(a.is_nan() ? a : b);
2463 }
2464 /// @overload
2465 [[nodiscard]] FP128_INLINE static constexpr float128 propagate_nan(const float128& a, const float128& b, const float128& c) noexcept
2466 {
2467 if (a.is_signaling() || b.is_signaling() || c.is_signaling())
2468 detail::raise_flags(FE_INVALID);
2469 return quiet_nan(a.is_nan() ? a : (b.is_nan() ? b : c));
2470 }
2471 /// @overload
2472 [[nodiscard]] FP128_INLINE static constexpr float128 propagate_nan(const float128& a) noexcept
2473 {
2474 if (a.is_signaling())
2475 detail::raise_flags(FE_INVALID);
2476 return quiet_nan(a);
2477 }
2478
2479 /**
2480 * @brief The result of an invalid operation on non NaN operands, such as inf - inf or 0 / 0.
2481 * @return The default quiet NaN, after raising the invalid flag.
2482 */
2483 [[nodiscard]] FP128_FORCE_INLINE static constexpr float128 invalid_operation() noexcept
2484 {
2485 detail::raise_flags(FE_INVALID);
2486 return nan();
2487 }
2488
2489 /**
2490 * @brief The sign of an exact zero sum of two operands of opposite sign (IEEE 754-2008 6.3).
2491 * @return 1 (negative) when rounding downward, 0 in every other direction.
2492 */
2493 [[nodiscard]] FP128_FORCE_INLINE static constexpr uint32_t exact_zero_sign() noexcept
2494 {
2496 }
2497 /// @}
2498 /**
2499 * @brief Normalize the fraction so the msb (unity bit) is on bit 112.
2500 * The fraction value must contain the unity value
2501 * The exponent component is adjusted based on the bit shift direction required.
2502 * @param l Low part of the fraction
2503 * @param h High part of the fraction
2504 * @param e Unbiased exponent, can be any value.
2505 */
2506 /// @brief Word count of the fixed point expansion used to print the fraction digits.
2507 static constexpr int32_t FIXED_WORDS = 4;
2508
2509 /**
2510 * @brief Expands the fraction part of this value into an exact fixed point number.
2511 *
2512 * The result is the fraction scaled by 2^256 and held in four words, frac[0] being the least
2513 * significant. Nothing is lost: a fraction bit of a binary128 has weight 2^(e-112) with e no
2514 * smaller than -111 on the path that calls this, so scaling by 2^256 always lands on an
2515 * integer, and the fraction is below one so the product stays under 2^256.
2516 *
2517 * Printing the digits from this expansion is exact. Deriving them by repeatedly multiplying a
2518 * float128 by 100000 instead, as this used to, rounds once per group and the error compounds
2519 * over the eight or so groups that a full precision value needs.
2520 *
2521 * @param frac Output, four words holding the fraction scaled by 2^256
2522 * @return True when a fraction exists, false when the value is an integer
2523 */
2524 [[nodiscard]] FP128_INLINE constexpr bool fraction_to_fixed(uint64_t frac[FIXED_WORDS]) const noexcept
2525 {
2526 for (int32_t i = 0; i < FIXED_WORDS; ++i)
2527 frac[i] = 0;
2528
2529 uint64_t l, h;
2530 int32_t e;
2531 uint32_t s;
2532 get_components(l, h, e, s);
2533
2534 // no bits sit below the binary point
2535 if (e >= FRAC_BITS)
2536 return false;
2537
2538 // keep only the bits whose weight is below one. A value under one contributes all of them.
2539 if (e >= 0) {
2540 const int32_t keep = FRAC_BITS - e; // 1 - 112
2541 if (keep <= 64) {
2542 l &= FP128_MAX_VALUE_64(keep);
2543 h = 0;
2544 } else {
2545 h &= FP128_MAX_VALUE_64(keep - 64);
2546 }
2547 }
2548
2549 if (l == 0 && h == 0)
2550 return false;
2551
2552 // bit i of the surviving fraction has weight 2^(e-112+i), which scaled by 2^256 lands on
2553 // bit e+144+i. The shift is non negative for every exponent that reaches this function.
2554 const int32_t shift = e + 2 * 64 + (FIXED_WORDS * 64 - 2 * 64) - FRAC_BITS; // e + 144
2555 FP128_ASSERT(shift >= 0 && shift < FIXED_WORDS * 64);
2556 const int32_t word = shift >> 6;
2557 const int32_t bit = shift & 63;
2558
2559 if (bit == 0) {
2560 frac[word] = l;
2561 if (word + 1 < FIXED_WORDS)
2562 frac[word + 1] = h;
2563 } else {
2564 frac[word] = l << bit;
2565 if (word + 1 < FIXED_WORDS)
2566 frac[word + 1] = (l >> (64 - bit)) | (h << bit);
2567 if (word + 2 < FIXED_WORDS)
2568 frac[word + 2] = h >> (64 - bit);
2569 }
2570 return true;
2571 }
2572 /**
2573 * @brief Multiplies the fixed point fraction by a small value and returns the part that
2574 * crossed the binary point.
2575 * @param frac Fraction scaled by 2^256, updated in place to hold the new fraction
2576 * @param mul Multiplier, small enough that the result stays below 2^64
2577 * @return The integer part produced by the multiply, which is the next group of digits
2578 */
2579 [[nodiscard]] FP128_INLINE static constexpr uint64_t fixed_mul_extract(uint64_t frac[FIXED_WORDS], uint64_t mul) noexcept
2580 {
2581 uint64_t carry = 0;
2582 for (int32_t i = 0; i < FIXED_WORDS; ++i) {
2583 uint64_t hi;
2584 const uint64_t lo = mulx_u64(frac[i], mul, &hi);
2585 const uint8_t c = addcarryx_u64(0, lo, carry, &frac[i]);
2586 carry = hi + c;
2587 }
2588 // the fraction was below one, so the overflow is below mul and fits in a single word
2589 return carry;
2590 }
2591 /// @brief True when every word of the fixed point fraction is zero.
2592 [[nodiscard]] FP128_INLINE static constexpr bool fixed_is_zero(const uint64_t frac[FIXED_WORDS]) noexcept
2593 {
2594 uint64_t acc = 0;
2595 for (int32_t i = 0; i < FIXED_WORDS; ++i)
2596 acc |= frac[i];
2597 return acc == 0;
2598 }
2599
2600 /**
2601 * @name Wide accumulator
2602 *
2603 * A fixed 384 bit unsigned integer, used by fma() to hold the exact sum of a 226 bit product
2604 * and a 113 bit addend before a single rounding is applied to it. The width is what the two
2605 * together need in the worst case: whichever of them is larger is placed with its leading bit
2606 * at the top of the accumulator, which leaves 383-225 = 158 bits below the product and
2607 * 383-112 = 271 bits below the addend. An operand that does not fit under the other one is
2608 * more than 158 bits smaller than it, so it cannot influence anything but the sticky bit, and
2609 * is folded into that instead of being placed.
2610 *
2611 * These are implementation details of fma() rather than part of the interface.
2612 * @{
2613 */
2614 static constexpr int32_t WIDE_WORDS = 6; ///< Words in the accumulator.
2615 static constexpr int32_t WIDE_BITS = WIDE_WORDS * 64; ///< Bits in the accumulator.
2616 /// @brief Bit the leading one of the larger operand is placed on.
2617 ///
2618 /// One below the top, so that adding two operands of the same magnitude cannot carry out of
2619 /// the accumulator.
2620 static constexpr int32_t WIDE_TOP = WIDE_BITS - 2;
2621
2622 /**
2623 * @brief Full 256 bit product of two 128 bit values.
2624 * @param al Low QWORD of the first operand
2625 * @param ah High QWORD of the first operand
2626 * @param bl Low QWORD of the second operand
2627 * @param bh High QWORD of the second operand
2628 * @param res Output, four words with res[0] the least significant
2629 */
2630 FP128_INLINE static constexpr void mul128to256(uint64_t al, uint64_t ah, uint64_t bl, uint64_t bh, uint64_t res[4]) noexcept
2631 {
2632 uint64_t hi = 0;
2633 res[0] = mulx_u64(al, bl, &hi);
2634 res[1] = hi;
2635 res[2] = 0;
2636 res[3] = 0;
2637
2638 uint64_t lo = mulx_u64(al, bh, &hi);
2639 unsigned char c = addcarryx_u64(0, res[1], lo, &res[1]);
2640 c = addcarryx_u64(c, res[2], hi, &res[2]);
2641 res[3] += c;
2642
2643 lo = mulx_u64(ah, bl, &hi);
2644 c = addcarryx_u64(0, res[1], lo, &res[1]);
2645 c = addcarryx_u64(c, res[2], hi, &res[2]);
2646 res[3] += c;
2647
2648 lo = mulx_u64(ah, bh, &hi);
2649 c = addcarryx_u64(0, res[2], lo, &res[2]);
2650 res[3] += hi + c;
2651 }
2652
2653 /**
2654 * @brief Index of the highest set bit of a multi word value, or -1 when it is zero.
2655 * @param a Words, a[0] the least significant
2656 * @param words Word count
2657 */
2658 [[nodiscard]] FP128_INLINE static constexpr int32_t wide_msb(const uint64_t* a, int32_t words) noexcept
2659 {
2660 for (int32_t i = words - 1; i >= 0; --i) {
2661 if (a[i] != 0)
2662 return i * 64 + 63 - static_cast<int32_t>(lzcnt64(a[i]));
2663 }
2664 return -1;
2665 }
2666
2667 /**
2668 * @brief Writes a value into a zeroed accumulator, shifted to a given bit position.
2669 *
2670 * A negative offset puts part or all of the value below the accumulator's least significant
2671 * bit. Those bits are not representable there but still decide the rounding, so whether any of
2672 * them was set is reported back rather than dropped.
2673 *
2674 * @param acc Accumulator, must be zero on entry
2675 * @param src Value to place, src[0] the least significant word
2676 * @param words Word count of src
2677 * @param offset Bit position the least significant bit of src lands on, may be negative
2678 * @return True when a set bit fell below the accumulator.
2679 */
2680 [[nodiscard]] FP128_INLINE static constexpr bool wide_place(uint64_t* acc, const uint64_t* src, int32_t words, int32_t offset) noexcept
2681 {
2682 if (offset >= 0) {
2683 const int32_t word = offset >> 6;
2684 const int32_t bit = offset & 63;
2685 for (int32_t i = 0; i < words; ++i) {
2686 const int32_t dst = i + word;
2687 if (dst >= WIDE_WORDS)
2688 break;
2689 acc[dst] |= src[i] << bit;
2690 if (bit != 0 && dst + 1 < WIDE_WORDS)
2691 acc[dst + 1] |= src[i] >> (64 - bit);
2692 }
2693 return false;
2694 }
2695
2696 const int32_t drop = -offset;
2697 if (drop >= words * 64) {
2698 uint64_t any = 0;
2699 for (int32_t i = 0; i < words; ++i)
2700 any |= src[i];
2701 return any != 0;
2702 }
2703
2704 const int32_t word = drop >> 6;
2705 const int32_t bit = drop & 63;
2706 uint64_t lost = 0;
2707 for (int32_t i = 0; i < word; ++i)
2708 lost |= src[i];
2709 if (bit != 0)
2710 lost |= src[word] & FP128_MAX_VALUE_64(bit);
2711
2712 for (int32_t i = 0; word + i < words; ++i) {
2713 uint64_t value = src[word + i] >> bit;
2714 if (bit != 0 && word + i + 1 < words)
2715 value |= src[word + i + 1] << (64 - bit);
2716 if (i < WIDE_WORDS)
2717 acc[i] |= value;
2718 }
2719 return lost != 0;
2720 }
2721
2722 /// @brief Adds b into a. The accumulator is wide enough that the sum cannot carry out.
2723 FP128_INLINE static constexpr void wide_add(uint64_t* a, const uint64_t* b) noexcept
2724 {
2725 unsigned char c = 0;
2726 for (int32_t i = 0; i < WIDE_WORDS; ++i)
2727 c = addcarryx_u64(c, a[i], b[i], &a[i]);
2728 }
2729
2730 /// @brief Subtracts b from a, which must not be smaller.
2731 FP128_INLINE static constexpr void wide_sub(uint64_t* a, const uint64_t* b) noexcept
2732 {
2733 unsigned char borrow = 0;
2734 for (int32_t i = 0; i < WIDE_WORDS; ++i) {
2735 const uint64_t rhs = b[i];
2736 const uint64_t diff = a[i] - rhs - borrow;
2737 borrow = (a[i] < rhs || (borrow && a[i] == rhs)) ? 1 : 0;
2738 a[i] = diff;
2739 }
2740 }
2741
2742 /// @brief Subtracts one from the accumulator, which must not be zero.
2743 FP128_INLINE static constexpr void wide_dec(uint64_t* a) noexcept
2744 {
2745 for (int32_t i = 0; i < WIDE_WORDS; ++i) {
2746 if (a[i]-- != 0)
2747 break;
2748 }
2749 }
2750
2751 /// @brief Three way comparison of two accumulators.
2752 [[nodiscard]] FP128_INLINE static constexpr int32_t wide_cmp(const uint64_t* a, const uint64_t* b) noexcept
2753 {
2754 for (int32_t i = WIDE_WORDS - 1; i >= 0; --i) {
2755 if (a[i] != b[i])
2756 return (a[i] > b[i]) ? 1 : -1;
2757 }
2758 return 0;
2759 }
2760 /// @}
2761 /**
2762 * @brief Normalizes the product of two mantissas to bit 112, handing back the bits it drops.
2763 *
2764 * The multiply and the square both arrive here with (h:l) equal to their 256 bit product shifted
2765 * right by 111. Both operands were normalized to [2^112, 2^113), so the product is in [2^224, 2^226)
2766 * and (h:l) is in [2^113, 2^115): its leading one is at bit 113 or bit 114 and nowhere else, which
2767 * makes the remaining shift 1 or 2 and the choice a single bit test.
2768 *
2769 * Nothing is rounded here. The bits shifted out, and the sticky bit for everything the caller
2770 * dropped before them, are returned in the form round_pack() takes, so that the result is
2771 * rounded once and to its final width - which for a subnormal product is narrower than 113 bits.
2772 *
2773 * @param l Low part of the shifted product, replaced by the normalized fraction
2774 * @param h High part of the shifted product, replaced by the normalized fraction
2775 * @param e Unbiased exponent, adjusted to match the normalized fraction
2776 * @param sticky True when the caller already dropped one or more set bits below l
2777 * @return The extra word for round_pack(): the dropped bits left aligned, the sticky bit in bit 0.
2778 */
2779 [[nodiscard]] FP128_FORCE_INLINE static constexpr uint64_t norm_product(uint64_t& l, uint64_t& h, int32_t& e, bool sticky) noexcept
2780 {
2781 // bit 114 of the product decides between the two, and it is bit 50 of the high QWORD
2782 const int32_t shift = 1 + static_cast<int32_t>(h >> 50);
2783 e += shift;
2784
2785 const uint64_t extra = (l << (64 - shift)) | (sticky ? 1 : 0);
2786 l = shift_right128(l, h, shift);
2787 h >>= shift;
2788 return extra;
2789 }
2790 /**
2791 * @brief Produces the closest value larger than x
2792 * nextUp(x) is the least floating-point number in the format of x that compares greater than x.
2793 * If x is the negative number of least magnitude in x’s format, nextUp(x) is −0.
2794 * nextUp(±0) is the positive number of least magnitude in x’s format.
2795 * nextUp(+∞) is +∞, and nextUp(−∞) is the finite negative number largest in magnitude.
2796 * When x is NaN, then the result is according to 6.2. nextUp(x) is quiet except for sNaNs.
2797 * @param x Source value
2798 * @return Higher value closest to x
2799 */
2800 [[nodiscard]] FP128_INLINE static constexpr float128 nextUp(float128 x)
2801 {
2802 switch (x.get_class()) {
2803 case quietNaN:
2804 case signalingNaN:
2805 return propagate_nan(x);
2806 case positiveInfinity:
2807 break;
2808 case negativeInfinity:
2809 return float128(UINT64_MAX, UINT64_MAX, EXP_MASK - 1, 1);
2810 case negativeZero:
2811 case positiveZero:
2812 x.low = 1;
2813 x.set_sign(0);
2814 break;
2815 case positiveSubnormal:
2816 case positiveNormal:
2817 ++x.low;
2818 if (x.low == 0) {
2819 ++x.high; // takes care of raising the exponent if needed as well
2820 }
2821 break;
2822 case negativeSubnormal:
2823 case negativeNormal:
2824 --x.low;
2825 if (x.low == UINT64_MAX) {
2826 --x.high; // takes care of decreasing the exponent if needed as well
2827 }
2828 break;
2829 }
2830 return x;
2831 }
2832 /**
2833 * @brief Produces the closest value smaller than x
2834 * @param x Source value
2835 * @return Lower value closest to x
2836 */
2837 [[nodiscard]] FP128_INLINE static constexpr float128 nextDown(float128 x)
2838 {
2839 switch (x.get_class()) {
2840 case quietNaN:
2841 case signalingNaN:
2842 return propagate_nan(x);
2843 case negativeInfinity:
2844 break;
2845 case positiveInfinity:
2846 return float128(UINT64_MAX, UINT64_MAX, EXP_MASK - 1, 0);
2847 case negativeZero:
2848 case positiveZero:
2849 x.low = 1;
2850 x.set_sign(1);
2851 break;
2852 case negativeSubnormal:
2853 case negativeNormal:
2854 ++x.low;
2855 if (x.low == 0) {
2856 ++x.high; // takes care of raising the exponent if needed as well
2857 }
2858 break;
2859 case positiveSubnormal:
2860 case positiveNormal:
2861 --x.low;
2862 if (x.low == UINT64_MAX) {
2863 --x.high; // takes care of decreasing the exponent if needed as well
2864 }
2865 break;
2866 }
2867 return x;
2868 }
2869
2870 /**
2871 * @brief Return the infinite constant
2872 * @return INF
2873 */
2874 [[nodiscard]] FP128_FORCE_INLINE static constexpr float128 inf() { return float128(0, 0, INF_EXP_BIASED, 0); }
2875 /**
2876 * @brief Return the quiet (non-signaling) NaN constant
2877 * @return NaN
2878 */
2879 [[nodiscard]] FP128_FORCE_INLINE static constexpr float128 nan() { return float128(0, QUIET_NAN_BIT, INF_EXP_BIASED, 0); }
2880 /**
2881 * @brief Return a signaling NaN
2882 *
2883 * Nothing in the library raises an exception on encountering one - there is no floating point
2884 * status to raise it in - but the encoding is distinguishable, which is what
2885 * numeric_limits::signaling_NaN() and is_signaling() need.
2886 * @return A signaling NaN
2887 */
2888 [[nodiscard]] FP128_FORCE_INLINE static constexpr float128 signaling_nan() { return float128(1, 0, INF_EXP_BIASED, 0); }
2889 /**
2890 * @brief Return the value of pi
2891 * @return pi
2892 */
2893 [[nodiscard]] FP128_FORCE_INLINE static constexpr float128 pi() { return float128(0x8469898CC51701B8, 0x921FB54442D1, 0x4000, 0); }
2894 /**
2895 * @brief Return the value of pi / 2
2896 * @return pi / 2
2897 */
2898 [[nodiscard]] FP128_FORCE_INLINE static constexpr float128 half_pi() { return float128(0x8469898CC51701B8, 0x921FB54442D1, 0x3FFF, 0); }
2899 /**
2900 * @brief Return the value of pi / 4
2901 * @return pi / 4
2902 */
2903 [[nodiscard]] FP128_FORCE_INLINE static constexpr float128 quarter_pi() { return float128(0x8469898CC51701B8, 0x921FB54442D1, 0x3FFE, 0); }
2904 /**
2905 * @brief Return the value of e
2906 * @return e
2907 */
2908 [[nodiscard]] FP128_FORCE_INLINE static constexpr float128 e()
2909 {
2910 // static const float128 e = "2.71828182845904523536028747135266249775724709369"; // 50 first digits of e
2911 // return e;
2912 return float128(0x95355FB8AC404E7A, 0x5BF0A8B14576, 0x4000, 0);
2913 }
2914 /**
2915 * @brief Returns a value of sqrt(2)
2916 * @return
2917 */
2918 [[nodiscard]] FP128_FORCE_INLINE static constexpr float128 sqrt_2() noexcept
2919 {
2920 // static const float128 sqrt_2 = "1.41421356237309504880168872420969807856967187537"; // 50 first digits of sqrt(2)
2921 // return sqrt_2;
2922 return float128(0xC908B2FB1366EA95, 0x00006A09E667F3BC, 0x3FFF, 0);
2923 }
2924 /**
2925 * @brief Returns a value of 1
2926 * @return 1
2927 */
2928 [[nodiscard]] FP128_FORCE_INLINE static constexpr float128 one() noexcept { return float128(0, 0, 0x3FFF, 0); }
2929 /**
2930 * @brief Returns a value of 0.5
2931 * @return 0.5
2932 */
2933 [[nodiscard]] FP128_FORCE_INLINE static constexpr float128 half() noexcept { return float128(0, 0, 0x3FFE, 0); }
2934 /**
2935 * @brief Return 0.1 using maximum precision
2936 * @return
2937 */
2938 [[nodiscard]] FP128_FORCE_INLINE static constexpr float128 tenth() noexcept
2939 {
2940 // 0.1 using maximum precision
2941 return float128(0x999999999999999A, 0x999999999999, EXP_BIAS - 4, 0u);
2942 }
2943
2944 /**
2945 * @name Mathematical constants
2946 *
2947 * The binary128 nearest each constant, given as the encoding rather than parsed from a decimal
2948 * string: the string constructor is accurate to about an ulp, which is one bit too few to
2949 * define a constant the rest of the library computes from. The set mirrors `<numbers>`, so a
2950 * generic function template written against std::numbers has the same names available here.
2951 * @{
2952 */
2953 /// @brief 2*pi
2954 [[nodiscard]] FP128_FORCE_INLINE static constexpr float128 two_pi() noexcept { return float128(0x8469898CC51701B8, 0x921FB54442D1, 0x4001, 0); }
2955 /// @brief 1/pi
2956 [[nodiscard]] FP128_FORCE_INLINE static constexpr float128 inv_pi() noexcept { return float128(0x2A53F84EAFA3EA6A, 0x45F306DC9C88, 0x3FFD, 0); }
2957 /// @brief 1/sqrt(pi)
2958 [[nodiscard]] FP128_FORCE_INLINE static constexpr float128 inv_sqrt_pi() noexcept { return float128(0xD11AE3A914FED7FE, 0x20DD750429B6, 0x3FFE, 0); }
2959 /// @brief Natural logarithm of 2
2960 [[nodiscard]] FP128_FORCE_INLINE static constexpr float128 ln2() noexcept { return float128(0xF35793C7673007E6, 0x62E42FEFA39E, 0x3FFE, 0); }
2961 /// @brief Natural logarithm of 10
2962 [[nodiscard]] FP128_FORCE_INLINE static constexpr float128 ln10() noexcept { return float128(0x582DD4ADAC5705A6, 0x26BB1BBB5551, 0x4000, 0); }
2963 /// @brief Base 2 logarithm of e
2964 [[nodiscard]] FP128_FORCE_INLINE static constexpr float128 log2_e() noexcept { return float128(0xE1777D0FFDA0D23A, 0x71547652B82F, 0x3FFF, 0); }
2965 /// @brief Base 10 logarithm of e
2966 [[nodiscard]] FP128_FORCE_INLINE static constexpr float128 log10_e() noexcept { return float128(0xE32A6AB7555F5A68, 0xBCB7B1526E50, 0x3FFD, 0); }
2967 /// @brief Base 10 logarithm of 2
2968 [[nodiscard]] FP128_FORCE_INLINE static constexpr float128 log10_2() noexcept { return float128(0xEF311F12B35816F9, 0x34413509F79F, 0x3FFD, 0); }
2969 /// @brief Square root of 3
2970 [[nodiscard]] FP128_FORCE_INLINE static constexpr float128 sqrt_3() noexcept { return float128(0xA73B25742D7078B8, 0xBB67AE8584CA, 0x3FFF, 0); }
2971 /// @brief 1/sqrt(3)
2972 [[nodiscard]] FP128_FORCE_INLINE static constexpr float128 inv_sqrt_3() noexcept { return float128(0xC4D218F81E4AFB25, 0x279A74590331, 0x3FFE, 0); }
2973 /// @brief The Euler-Mascheroni constant
2974 [[nodiscard]] FP128_FORCE_INLINE static constexpr float128 egamma() noexcept { return float128(0x8F49A37C7F0202A6, 0x2788CFC6FB61, 0x3FFE, 0); }
2975 /// @brief The golden ratio
2976 [[nodiscard]] FP128_FORCE_INLINE static constexpr float128 phi() noexcept { return float128(0x7C15F39CC0605CEE, 0x9E3779B97F4A, 0x3FFF, 0); }
2977 /// @}
2978 /**
2979 * @brief Calculates 10^e.
2980 *
2981 * Exact for 0 <= e <= 48, where 10^e is representable. Otherwise the power is formed in double
2982 * word arithmetic - a pair (hi, lo) whose sum carries about 226 bits, the error of each product
2983 * recovered exactly with fma() - and rounded once, at the end, in the current direction.
2984 *
2985 * Measured against exact rationals for every e from -4970 to 4935 in all four rounding
2986 * directions (2026-10-10): correctly rounded, with exactly the exception flags of a single
2987 * rounding, everywhere except exp10(-4931) rounding upward, which is one ulp high. Close to the
2988 * subnormal range the cross terms of the last products fall below the subnormal grid and are
2989 * rounded there, which can cost the last bit; the bound is 1 ulp in every direction.
2990 *
2991 * The previous version squared and multiplied the rounded 0.1 itself, carrying its error and
2992 * every rounding along: exp10(-100) was 66 ulp off and exp10(-4000) 1809, and the directed
2993 * modes drifted further still, up to 3453 ulp.
2994 *
2995 * @param e Integer exponent. Beyond the range of the format the result overflows (e > 4932) or
2996 * underflows (e < -4965) as rounding the exact power would, in the current direction and
2997 * with the same exception flags.
2998 * @return 10^e
2999 */
3000 [[nodiscard]] FP128_INLINE static constexpr float128 exp10(int32_t e) noexcept
3001 {
3002 // Past either end of the range the answer is the overflow or the underflow of the current
3003 // direction, which scaling one far out produces with its flags.
3004 if (e > 4932)
3005 return ldexp(one(), SCALE_LIMIT);
3006 if (e < -4965)
3007 return ldexp(one(), -SCALE_LIMIT);
3008 if (std::is_constant_evaluated())
3009 return exp10_double_word(e);
3010 return exp10_filtered(e);
3011 }
3012
3013 /**
3014 * @brief The power of exp10(), for an e whose result is inside the range of the format.
3015 *
3016 * Binary exponentiation on (hi, lo) pairs. The product of two pairs is hi * bh, whose rounding
3017 * error fma() recovers exactly, plus the cross terms, which are 2^-113 of it and are rounded;
3018 * the pair is then renormalized so that lo stays below an ulp of hi.
3019 *
3020 * @param e Exponent, with 10^e inside the range of the format
3021 * @return 10^e, rounded once in the current direction.
3022 */
3023 [[nodiscard]] FP128_INLINE static constexpr float128 exp10_double_word(int32_t e) noexcept
3024 {
3025 float128 res_hi = one(), res_lo;
3026 float128 base_hi = float128(10), base_lo;
3027 if (e < 0) {
3028 // 0.1 as a pair: tenth() and the binary128 nearest to 0.1 - tenth()
3029 base_hi = tenth();
3030 base_lo = float128(0x999999999999999A, 0xBF89999999999999);
3031 e = -e;
3032 }
3033 // hi and bh may be the same object when squaring: every read of the operands happens
3034 // before hi is written.
3035 const auto multiply = [](float128& hi, float128& lo, const float128& bh, const float128& bl) {
3036 const float128 p = hi * bh;
3037 const float128 error = fma(hi, bh, -p);
3038 const float128 cross = error + (hi * bl + lo * bh);
3039 hi = p + cross;
3040 lo = cross - (hi - p);
3041 };
3042 for (;;) {
3043 if (e & 1)
3044 multiply(res_hi, res_lo, base_hi, base_lo);
3045 e >>= 1;
3046 if (e == 0)
3047 break;
3048 multiply(base_hi, base_lo, base_hi, base_lo);
3049 }
3050 return res_hi + res_lo;
3051 }
3052
3053 /**
3054 * @brief exp10_double_word() at run time, raising only the exceptions the result justifies.
3055 *
3056 * The cross terms of the products can underflow while the power itself does not.
3057 *
3058 * @param e Exponent, with 10^e inside the range of the format
3059 * @return 10^e
3060 */
3061 [[nodiscard]] static float128 exp10_filtered(int32_t e) noexcept
3062 {
3063 detail::flag_filter filter;
3064 return filter(exp10_double_word(e));
3065 }
3066
3067 /// @brief Returns false; this type does not conform to IEEE 754-1985.
3068 static constexpr bool is754version1985(void) { return false; }
3069 /**
3070 * @brief Whether the type conforms to IEEE 754-2008 (binary128).
3071 *
3072 * The arithmetic, the conversions and the operations of clause 5 conform in every build, but
3073 * the standard also requires the rounding-direction attributes of clause 4 and the status flags
3074 * of clause 7, which exist only when FP128_IEEE_ENV is defined.
3075 *
3076 * @return True when the program is built with FP128_IEEE_ENV, false otherwise.
3077 */
3078 static constexpr bool is754version2008(void)
3079 {
3080#ifdef FP128_IEEE_ENV
3081 return true;
3082#else
3083 return false;
3084#endif
3085 }
3086 //
3087 // End of class method implementation
3088 //
3089
3090 //
3091 // Binary math operators
3092 //
3093 // Each of these applies the compound assignment to the by value left hand side and then returns
3094 // it on a line of its own, rather than the shorter `return lhs OP= rhs;`. The two are
3095 // equivalent, but the short form makes the return statement copy construct from an lvalue, which
3096 // MSVC compiles into a store forwarding stall. int128_base's binary operators carry the full
3097 // explanation and the measurement.
3098 //
3099 /**
3100 * @brief Adds 2 values and returns the result.
3101 * @param lhs left hand side operand
3102 * @param rhs Right hand side operand
3103 * @return Result of the operation
3104 */
3105 template <typename T> [[nodiscard]] friend FP128_FORCE_INLINE constexpr float128 operator+(float128 lhs, const T& rhs) noexcept
3106 {
3107 lhs += rhs;
3108 return lhs;
3109 }
3110 /**
3111 * @brief subtracts the right hand side operand to this object to and returns the result.
3112 * @param lhs left hand side operand
3113 * @param rhs Right hand side operand
3114 * @return The float128 result
3115 */
3116 template <typename T> [[nodiscard]] friend FP128_FORCE_INLINE constexpr float128 operator-(float128 lhs, const T& rhs) noexcept
3117 {
3118 lhs -= rhs;
3119 return lhs;
3120 }
3121 /**
3122 * @brief Multiplies the right hand side operand with this object to and returns the result.
3123 * @param lhs left hand side operand
3124 * @param rhs Right hand side operand
3125 * @return The float128 result
3126 */
3127 template <typename T> [[nodiscard]] friend FP128_FORCE_INLINE constexpr float128 operator*(float128 lhs, const T& rhs) noexcept
3128 {
3129 lhs *= rhs;
3130 return lhs;
3131 }
3132 /**
3133 * @brief Divides this object by the right hand side operand and returns the result.
3134 * @param lhs left hand side operand
3135 * @param rhs Right hand side operand
3136 * @return The float128 result
3137 */
3138 template <typename T> [[nodiscard]] friend FP128_FORCE_INLINE float128 operator/(float128 lhs, const T& rhs)
3139 {
3140 lhs /= rhs;
3141 return lhs;
3142 }
3143
3144 //
3145 // Binary math operators with the scalar on the left hand side
3146 //
3147 // Without these, an expression like (1 + x) is ambiguous: converting the literal to float128
3148 // and converting x to a builtin type are both one user defined conversion, so neither
3149 // overload wins. Restricting the left operand to the arithmetic types keeps these from
3150 // competing with the float128 on the left versions above, which would otherwise be an equally
3151 // good match. The comparison operators already carry the same pair of overloads.
3152 //
3153
3154 /// @brief Adds a scalar and a float128, in that order. @param lhs Left operand @param rhs Right operand @return The float128 result
3155 template <typename T>
3156 requires std::is_arithmetic_v<T>
3157 [[nodiscard]] friend FP128_FORCE_INLINE constexpr float128 operator+(const T& lhs, const float128& rhs) noexcept
3158 {
3159 return float128(lhs) += rhs;
3160 }
3161 /// @brief Subtracts a float128 from a scalar. @param lhs Left operand @param rhs Right operand @return The float128 result
3162 template <typename T>
3163 requires std::is_arithmetic_v<T>
3164 [[nodiscard]] friend FP128_FORCE_INLINE constexpr float128 operator-(const T& lhs, const float128& rhs) noexcept
3165 {
3166 return float128(lhs) -= rhs;
3167 }
3168 /// @brief Multiplies a scalar and a float128, in that order. @param lhs Left operand @param rhs Right operand @return The float128 result
3169 template <typename T>
3170 requires std::is_arithmetic_v<T>
3171 [[nodiscard]] friend FP128_FORCE_INLINE constexpr float128 operator*(const T& lhs, const float128& rhs) noexcept
3172 {
3173 return float128(lhs) *= rhs;
3174 }
3175 /// @brief Divides a scalar by a float128. @param lhs Left operand @param rhs Right operand @return The float128 result
3176 template <typename T>
3177 requires std::is_arithmetic_v<T>
3178 [[nodiscard]] friend FP128_FORCE_INLINE float128 operator/(const T& lhs, const float128& rhs)
3179 {
3180 return float128(lhs) /= rhs;
3181 }
3182 /**
3183 * @brief Shifts a scalar left by a float128 shift count, scaling it by a power of two.
3184 *
3185 * The left operand is widened to float128 first, so the result is 128 bit rather than the
3186 * builtin type of lhs.
3187 *
3188 * The count is rhs converted to int32_t, the same conversion the float128 on the left overload
3189 * applies, and that conversion truncates, so a count of 3.75 shifts by 3 - as it does in
3190 * fixed_point128, whose conversion is a plain shift.
3191 *
3192 * @param lhs Left operand, the value being shifted
3193 * @param rhs Right operand, the shift count
3194 * @return The float128 result
3195 */
3196 template <typename T>
3197 requires std::is_arithmetic_v<T>
3198 [[nodiscard]] friend FP128_FORCE_INLINE constexpr float128 operator<<(const T& lhs, const float128& rhs) noexcept
3199 {
3200 return float128(lhs) <<= static_cast<int32_t>(rhs);
3201 }
3202 /**
3203 * @brief Shifts a scalar right by a float128 shift count, scaling it by a power of two.
3204 * The left operand is widened to float128 first, see operator<< above.
3205 * @param lhs Left operand, the value being shifted
3206 * @param rhs Right operand, the shift count
3207 * @return The float128 result
3208 */
3209 template <typename T>
3210 requires std::is_arithmetic_v<T>
3211 [[nodiscard]] friend FP128_FORCE_INLINE constexpr float128 operator>>(const T& lhs, const float128& rhs) noexcept
3212 {
3213 return float128(lhs) >>= static_cast<int32_t>(rhs);
3214 }
3215
3216 //
3217 // Comparison operators
3218 //
3219
3220 /**
3221 * @brief Compare logical/bitwise equal.
3222 * @param lhs left hand side operand
3223 * @param rhs Right hand side operand
3224 * @return True if lhs and rhs are equal.
3225 */
3226 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator==(const float128& lhs, const float128& rhs) noexcept
3227 {
3228 // A NaN compares equal to nothing, not even to another NaN with the same bits. Equality is
3229 // a quiet comparison: only a signaling NaN is the invalid operation.
3230 if (lhs.is_nan() || rhs.is_nan()) {
3231 if (lhs.is_signaling() || rhs.is_signaling())
3232 detail::raise_flags(FE_INVALID);
3233 return false;
3234 }
3235 // Positive and negative zero are numerically equal even though their bits differ.
3236 if (lhs.is_zero() && rhs.is_zero())
3237 return true;
3238 return lhs.high == rhs.high && lhs.low == rhs.low;
3239 }
3240 /// @overload
3241 // Constrained to a builtin type. Unconstrained, T deduces to float128 for a comparison of two
3242 // of them, which makes this template an exact match alongside the non-template above - and
3243 // under the C++20 rewriting of == and != the reversed forms join in, which MSVC reports as an
3244 // ambiguity from inside any standard container that compares keys.
3245 template <typename T>
3246 requires std::is_arithmetic_v<T>
3247 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator==(const float128& lhs, const T& rhs) noexcept { return lhs == float128(rhs); }
3248 /// @overload
3249 // Constrained to a builtin type, see operator== above.
3250 template <typename T>
3251 requires std::is_arithmetic_v<T>
3252 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator==(const T& lhs, const float128& rhs) noexcept
3253 {
3254 return rhs == float128(lhs);
3255 }
3256 /**
3257 * @brief Return true when objects are not equal. Can be used as logical XOR.
3258 * @param lhs left hand side operand
3259 * @param rhs Right hand side operand
3260 * @return True if not equal.
3261 */
3262 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator!=(const float128& lhs, const float128& rhs) noexcept { return !(lhs == rhs); }
3263 /// @overload
3264 // Constrained to a builtin type, see operator== above.
3265 template <typename T>
3266 requires std::is_arithmetic_v<T>
3267 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator!=(const float128& lhs, const T& rhs) noexcept { return lhs != float128(rhs); }
3268 /// @overload
3269 /// @copydoc operator!=
3270 template <typename T>
3271 requires std::is_arithmetic_v<T>
3272 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator!=(const T& lhs, const float128& rhs) noexcept { return rhs != float128(lhs); }
3273 /**
3274 * @brief Return true if this object is small than the other
3275 * @param lhs left hand side operand
3276 * @param rhs Right hand side operand
3277 * @return True when this object is smaller.
3278 */
3279 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator<(const float128& lhs, const float128& rhs) noexcept
3280 {
3281 // A NaN is unordered with everything, so every relational test involving one is false. The
3282 // relational operators are IEEE 754's signaling comparisons, so any NaN is the invalid
3283 // operation; isless() and the other <cmath> predicates are the quiet ones.
3284 if (lhs.is_nan() || rhs.is_nan()) {
3285 detail::raise_flags(FE_INVALID);
3286 return false;
3287 }
3288 // The two zeros are numerically equal, so neither is smaller than the other. Without this
3289 // the differing sign bits would make -0 compare smaller than +0.
3290 if (lhs.is_zero() && rhs.is_zero())
3291 return false;
3292
3293 auto rhs_sign = rhs.get_sign();
3294 auto lhs_sign = lhs.get_sign();
3295
3296 // signs are different
3297 if (lhs_sign != rhs_sign)
3298 return lhs_sign > rhs_sign; // true when lhs_sign is 1 and rhs.sign is 0
3299
3300 // MSB is the same, check the LSB, implies the exponent is identical
3301 if (lhs.high == rhs.high)
3302 return (lhs_sign) ? lhs.low > rhs.low : lhs.low < rhs.low;
3303
3304 return (lhs_sign) ? lhs.high > rhs.high : lhs.high < rhs.high;
3305 }
3306 /// @overload
3307 template <typename T>
3308 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator<(const float128& lhs, const T& rhs) noexcept { return lhs < float128(rhs); }
3309 /// @overload
3310 template <typename T>
3311 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator<(const T& lhs, const float128& rhs) noexcept { return float128(lhs) < rhs; }
3312 /**
3313 * @brief Return true this object is small or equal than the other
3314 * @param lhs left hand side operand
3315 * @param rhs Right hand side operand
3316 * @return True when this object is smaller or equal.
3317 */
3318 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator<=(const float128& lhs, const float128& rhs) noexcept
3319 {
3320 // Not simply !(lhs > rhs): a NaN makes every relational test false, so negating the
3321 // opposite test would wrongly report that a NaN is less than or equal to everything.
3322 if (lhs.is_nan() || rhs.is_nan()) {
3323 detail::raise_flags(FE_INVALID);
3324 return false;
3325 }
3326 return !(lhs > rhs);
3327 }
3328 /// @overload
3329 template <typename T>
3330 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator<=(const float128& lhs, const T& rhs) noexcept { return lhs <= float128(rhs); }
3331 /// @overload
3332 template <typename T>
3333 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator<=(const T& lhs, const float128& rhs) noexcept { return float128(lhs) <= rhs; }
3334 /**
3335 * @brief Return true this object is larger than the other
3336 * @param lhs left hand side operand
3337 * @param rhs Right hand side operand
3338 * @return True when this object is larger.
3339 */
3340 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator>(const float128& lhs, const float128& rhs) noexcept
3341 {
3342 // A NaN is unordered with everything, so every relational test involving one is false. The
3343 // relational operators are IEEE 754's signaling comparisons, so any NaN is the invalid
3344 // operation; isless() and the other <cmath> predicates are the quiet ones.
3345 if (lhs.is_nan() || rhs.is_nan()) {
3346 detail::raise_flags(FE_INVALID);
3347 return false;
3348 }
3349 // the two zeros are numerically equal, so neither is larger than the other
3350 if (lhs.is_zero() && rhs.is_zero())
3351 return false;
3352
3353 auto rhs_sign = rhs.get_sign();
3354 auto lhs_sign = lhs.get_sign();
3355
3356 // signs are different
3357 if (lhs_sign != rhs_sign)
3358 return lhs_sign < rhs_sign; // true when lhs_sign is 1 and rhs.sign is 0
3359
3360 // MSB is the same, check the LSB, implies the exponent is identical
3361 if (lhs.high == rhs.high)
3362 return (lhs_sign) ? lhs.low < rhs.low : lhs.low > rhs.low;
3363
3364 return (lhs_sign) ? lhs.high < rhs.high : lhs.high > rhs.high;
3365 }
3366 /// @overload
3367 template <typename T>
3368 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator>(const float128& lhs, const T& rhs) noexcept { return lhs > float128(rhs); }
3369 /// @overload
3370 template <typename T>
3371 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator>(const T& lhs, const float128& rhs) noexcept { return float128(lhs) > rhs; }
3372 /**
3373 * @brief Return true this object is larger or equal than the other
3374 * @param lhs left hand side operand
3375 * @param rhs Right hand side operand
3376 * @return True when this objext is larger or equal.
3377 */
3378 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator>=(const float128& lhs, const float128& rhs) noexcept
3379 {
3380 // see the note on operator<= about why this is not simply !(lhs < rhs)
3381 if (lhs.is_nan() || rhs.is_nan()) {
3382 detail::raise_flags(FE_INVALID);
3383 return false;
3384 }
3385 return !(lhs < rhs);
3386 }
3387 /// @overload
3388 template <typename T>
3389 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator>=(const float128& lhs, const T& rhs) noexcept { return lhs >= float128(rhs); }
3390 /// @overload
3391 template <typename T>
3392 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator>=(const T& lhs, const float128& rhs) noexcept { return float128(lhs) >= rhs; }
3393
3394 /**
3395 * @brief Return the NaN constant
3396 * @return A quiet NaN. The argument only exists so that the call can be found by argument
3397 * dependent lookup, its value is ignored.
3398 */
3399 [[nodiscard]] friend FP128_FORCE_INLINE constexpr float128 nan(const float128&) { return float128::nan(); }
3400 /**
3401 * @brief Tests if the value is a NaN
3402 * @param x Value to test
3403 * @return True when the value is a NaN
3404 */
3405 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool isnan(const float128& x)
3406 {
3407 // zero for +- INF, non-zero for NaN
3408 return x.is_nan();
3409 }
3410 /**
3411 * @brief Tests if the value is an Infinite (negative or positive)
3412 * @param x Value to test
3413 * @return True when the value is an Infinite
3414 */
3415 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool isinf(const float128& x) { return x.is_inf(); }
3416
3417 /**
3418 * @brief Returns the absolute value of x.
3419 * @param x Input value
3420 * @return |x|
3421 */
3422 [[nodiscard]] friend FP128_FORCE_INLINE constexpr float128 fabs(const float128& x) noexcept
3423 {
3424 float128 temp = x;
3425 temp.set_sign(0);
3426 return temp;
3427 }
3428 /**
3429 * @brief Rounds to an integral value (IEEE 754-2008 roundToIntegral, 5.3.1).
3430 *
3431 * The shared engine of floor, ceil, trunc, round, rint and nearbyint, which differ only in the
3432 * direction they round. It works on the encoding: the fraction bits below the units bit are
3433 * cleared, and when the value has to move up one unit is added at the units bit, a carry out of
3434 * the fraction landing in the exponent on its own. Nothing is subtracted, so nothing rounds,
3435 * and the sign is left alone - a negative value that rounds to zero gives -0.
3436 *
3437 * The previous implementations subtracted the fraction from the value, which made the zero
3438 * results of a negative argument positive, and round() added one half and truncated, which
3439 * rounded the largest value below one half up to one and 2^112 + 1 to 2^112 + 2.
3440 *
3441 * @param x Value to round
3442 * @param mode Direction, ignored when @p ties_away is set
3443 * @param ties_away Round to nearest with ties away from zero instead, as round() does
3444 * @param signal_inexact Raise the inexact exception when the result differs from x, which
3445 * distinguishes roundToIntegralExact (rint) from the other five
3446 * @return The integral value. A NaN comes back quieted, an infinity unchanged.
3447 */
3448 [[nodiscard]] FP128_INLINE static constexpr float128 round_integral(const float128& x, detail::rounding mode, bool ties_away,
3449 bool signal_inexact) noexcept
3450 {
3451 if (x.is_nan())
3452 return propagate_nan(x);
3453 const int32_t expo = x.get_exponent();
3454 // Infinities, and every finite value from 2^112 up, have no fraction bits.
3455 if (expo >= FRAC_BITS || x.is_zero())
3456 return x;
3457
3458 const uint32_t sign = x.get_sign();
3459 const uint64_t sign_bit = static_cast<uint64_t>(sign) << 63;
3460 const bool round_up_away = (mode == ((sign != 0) ? detail::rounding::downward : detail::rounding::upward));
3461 if (expo < 0) {
3462 // |x| < 1, subnormals included: the result is zero or one, with the sign of x.
3463 bool one = false;
3464 if (ties_away)
3465 one = expo == -1;
3466 else if (mode == detail::rounding::nearest_even)
3467 one = expo == -1 && (x.get_fraction_bits() | x.low) != 0; // one half itself ties to zero
3468 else
3469 one = round_up_away;
3470 if (signal_inexact)
3471 detail::raise_flags(FE_INEXACT);
3472 return float128(0, sign_bit | (one ? (static_cast<uint64_t>(EXP_BIAS) << EXP_SHIFT) : 0));
3473 }
3474
3475 // The units bit is bit 112 - expo of the encoding. For expo == 0 that is the exponent
3476 // field's lowest bit, which is set for the exponent of [1, 2): the implicit one is odd.
3477 const int32_t units = FRAC_BITS - expo;
3478 const uint64_t mask_low = (units >= 64) ? UINT64_MAX : ((1ull << units) - 1);
3479 const uint64_t mask_high = (units >= 64) ? ((1ull << (units - 64)) - 1) : 0;
3480 uint64_t l = x.low, h = x.high;
3481 if (((l & mask_low) | (h & mask_high)) == 0)
3482 return x;
3483
3484 const int32_t half_index = units - 1;
3485 const uint64_t half_low = (half_index < 64) ? (1ull << half_index) : 0;
3486 const uint64_t half_high = (half_index < 64) ? 0 : (1ull << (half_index - 64));
3487 const bool at_or_above_half = ((l & half_low) | (h & half_high)) != 0;
3488 const bool rest = ((l & mask_low & ~half_low) | (h & mask_high & ~half_high)) != 0;
3489 const bool odd = ((units < 64) ? (l >> units) : (h >> (units - 64))) & 1;
3490
3491 bool up = false;
3492 if (ties_away)
3493 up = at_or_above_half;
3494 else if (mode == detail::rounding::nearest_even)
3495 up = at_or_above_half && (rest || odd);
3496 else
3497 up = round_up_away;
3498
3499 if (signal_inexact)
3500 detail::raise_flags(FE_INEXACT);
3501 l &= ~mask_low;
3502 h &= ~mask_high;
3503 if (up) {
3504 if (units >= 64) {
3505 h += 1ull << (units - 64);
3506 } else {
3507 const uint64_t unit = 1ull << units;
3508 l += unit;
3509 h += (l < unit) ? 1 : 0;
3510 }
3511 }
3512 return float128(l, h);
3513 }
3514
3515 /**
3516 * @brief Converts an integral value to an integer type, the way the C rounding functions do.
3517 * @tparam I The integer type
3518 * @param x An integral value, an infinity or a NaN
3519 * @return The value, or zero when it is a NaN or out of range for the type, which is the
3520 * invalid operation.
3521 */
3522 template <typename I> [[nodiscard]] FP128_INLINE static constexpr I integral_to(const float128& x) noexcept
3523 {
3524 if (x.is_nan() || x > std::numeric_limits<I>::max() || x < std::numeric_limits<I>::min()) {
3525 detail::raise_flags(FE_INVALID);
3526 return 0;
3527 }
3528 return x.to_integer<I>();
3529 }
3530
3531 /**
3532 * @brief Performs the floor() function, similar to libc's floor(), rounds down towards -infinity.
3533 * @param x Input value
3534 * @return A float128 holding the integer value.
3535 */
3536 [[nodiscard]] friend FP128_FORCE_INLINE constexpr float128 floor(const float128& x) noexcept
3537 {
3538 return round_integral(x, detail::rounding::downward, false, false);
3539 }
3540 /**
3541 * @brief Performs the ceil() function, similar to libc's ceil(), rounds up towards infinity.
3542 * @param x Input value
3543 * @return A float128 holding the integer value. A negative value above -1 gives -0.
3544 */
3545 [[nodiscard]] friend FP128_FORCE_INLINE constexpr float128 ceil(const float128& x) noexcept
3546 {
3547 return round_integral(x, detail::rounding::upward, false, false);
3548 }
3549 /**
3550 * @brief Rounds towards zero
3551 * @param x Value to truncate
3552 * @return Integer value, rounded towards zero. A negative value above -1 gives -0.
3553 */
3554 [[nodiscard]] friend FP128_FORCE_INLINE constexpr float128 trunc(const float128& x) noexcept
3555 {
3556 return round_integral(x, detail::rounding::toward_zero, false, false);
3557 }
3558 /**
3559 * @brief Rounds towards the nearest integer.
3560 * The halfway value (0.5) is rounded away from zero.
3561 * @param x Value to round
3562 * @return Integer value, rounded towards the nearest integer.
3563 */
3564 [[nodiscard]] friend FP128_FORCE_INLINE constexpr float128 round(const float128& x) noexcept
3565 {
3566 return round_integral(x, detail::rounding::nearest_even, true, false);
3567 }
3568 /**
3569 * @brief Rounds x to an integer in the current rounding direction and returns it as int64_t.
3570 * @param x Input value
3571 * @return Nearest integer as int64_t. Returns 0 on overflow or for a NaN, raising invalid.
3572 */
3573 // rint rounds ties to even, round() rounds them away from zero, so these cannot forward to
3574 // llround/lround the way they used to: llrint(2.5) is 2 and llround(2.5) is 3.
3575 [[nodiscard]] friend FP128_FORCE_INLINE constexpr int64_t llrint(const float128& x) noexcept { return integral_to<int64_t>(rint(x)); }
3576 /**
3577 * @brief Rounds towards the nearest integer.
3578 * The halfway value (0.5) is rounded away from zero.
3579 * @param x Value to round
3580 * @return Integer value, rounded towards the nearest integer. Returns 0 on overflow or for a
3581 * NaN, raising invalid.
3582 */
3583 [[nodiscard]] friend FP128_FORCE_INLINE constexpr int64_t llround(const float128& x) noexcept { return integral_to<int64_t>(round(x)); }
3584 /**
3585 * @brief Rounds x to an integer in the current rounding direction and returns it as int32_t.
3586 * @param x Input value
3587 * @return Nearest integer as int32_t. Returns 0 on overflow or for a NaN, raising invalid.
3588 */
3589 [[nodiscard]] friend FP128_FORCE_INLINE constexpr int32_t lrint(const float128& x) noexcept { return integral_to<int32_t>(rint(x)); }
3590 /**
3591 * @brief Rounds towards the nearest integer.
3592 * The halfway value (0.5) is rounded away from zero.
3593 * @param x Value to round
3594 * @return Integer value, rounded towards the nearest integer. Returns 0 on overflow or for a
3595 * NaN, raising invalid.
3596 */
3597 [[nodiscard]] friend FP128_FORCE_INLINE constexpr int32_t lround(const float128& x) noexcept { return integral_to<int32_t>(round(x)); }
3598
3599 /**
3600 * @brief Retrieves an integer that represents the base-2 exponent of the specified value.
3601 *
3602 * IEEE 754-2008 logB (5.3.3) with an integer result format: a zero, an infinity and a NaN have
3603 * no exponent the result can express, so each is the invalid operation.
3604 *
3605 * @param x The specified value.
3606 * @return The unbiased exponent of x - that of its leading bit for a subnormal. FP_ILOGB0 for a
3607 * zero, INT_MAX for an infinity and FP_ILOGBNAN for a NaN, each raising invalid.
3608 */
3609 [[nodiscard]] friend FP128_INLINE constexpr int32_t ilogb(const float128& x) noexcept
3610 {
3611 // The three answers <cmath> reserves for the arguments that have no exponent. A subnormal
3612 // does have one, but not the one its exponent field holds, so it goes through
3613 // get_components() with the rest.
3614 if (x.is_zero() || x.is_special()) {
3615 detail::raise_flags(FE_INVALID);
3616 if (x.is_zero())
3617 return FP_ILOGB0;
3618 return x.is_nan() ? FP_ILOGBNAN : INT_MAX;
3619 }
3620
3621 uint64_t l = 0, h = 0;
3622 int32_t expo = 0;
3623 uint32_t sign = 0;
3624 x.get_components(l, h, expo, sign);
3625 return expo;
3626 }
3627 /**
3628 * @brief returns the value of x with the sign of y.
3629 * @param x The value that's returned as the magnitude of the result.
3630 * @param y The sign of the result.
3631 * @return The copysign functions return a floating-point value that combines the magnitude of x and the sign of y.
3632 */
3633 [[nodiscard]] friend FP128_FORCE_INLINE constexpr float128 copysign(const float128& x, const float128& y) noexcept
3634 {
3635 float128 temp = x;
3636 temp.set_sign(y.get_sign());
3637 return temp;
3638 }
3639 /**
3640 * @brief Performs the fmod() function, similar to libc's fmod(), returns the remainder of a division x/root.
3641 * @param x Numerator
3642 * @param y Denominator
3643 * @return The modulo value.
3644 */
3645 [[nodiscard]] friend float128 fmod(const float128& x, const float128& y) noexcept
3646 {
3647 // a NaN operand propagates
3648 if (x.is_nan() || y.is_nan())
3649 return propagate_nan(x, y);
3650
3651 // fmod(x, 0) is the invalid operation and produces a NaN, matching the CRT.
3652 // An infinite dividend is invalid for the same reason.
3653 if (y.is_zero() || x.is_inf())
3654 return invalid_operation();
3655
3656 // trivial case, x is zero
3657 if (x.is_zero())
3658 return x;
3659
3660 // an infinite divisor leaves the dividend untouched
3661 if (y.is_inf())
3662 return x;
3663
3664 // fmod is exact: the result is x - n*y for an integer n, and it is representable. Reaching
3665 // it through trunc(x/y), as this used to, is only exact while the quotient is: once x/y
3666 // needs more than 113 bits the truncated quotient is a rounded value and the subtraction
3667 // returns something unrelated to the remainder. The mantissas are integers, so the whole
3668 // operation is a long division on them, done here one 64 bit block of the exponent
3669 // difference at a time.
3670 uint64_t lx = 0, hx = 0, ly = 0, hy = 0;
3671 int32_t ex = 0, ey = 0;
3672 uint32_t sx = 0, sy = 0;
3673 x.get_components(lx, hx, ex, sx);
3674 y.get_components(ly, hy, ey, sy);
3675
3676 // |x| < |y| leaves the dividend as the remainder
3677 if (ex < ey || (ex == ey && uint128_t(lx, hx) < uint128_t(ly, hy)))
3678 return x;
3679
3680 // Both mantissas hold 113 bits with the leading one at bit 112, so the values compared
3681 // here are x = rem * 2^(ex-112) and y = mod * 2^(ey-112).
3682 uint128_t rem(lx, hx);
3683 const uint128_t mod(ly, hy);
3684 rem %= mod;
3685 int32_t shift = ex - ey;
3686
3687 // A remainder is below the divisor and so holds at most 113 bits; shifting 15 more in
3688 // keeps the dividend inside the 128 the modulo can take.
3689 constexpr int32_t block = 15;
3690 while (shift > 0 && !rem.is_zero()) {
3691 const int32_t step = (shift < block) ? shift : block;
3692 rem <<= step;
3693 shift -= step;
3694 rem %= mod;
3695 }
3696
3697 if (rem.is_zero()) {
3698 float128 zero;
3699 zero.set_sign(sx);
3700 return zero;
3701 }
3702
3703 // Rebuild the value: the remainder is an integer scaled by the divisor's last place.
3704 uint64_t rl = 0, rh = 0;
3705 rem.get_components(rl, rh);
3706 const int32_t msb = static_cast<int32_t>(log2(rl, rh));
3707 shift_left128_inplace_safe(rl, rh, FRAC_BITS - msb);
3708
3709 float128 res;
3710 res.set_components(rl, rh, ey - FRAC_BITS + msb, sx);
3711 return res;
3712 }
3713 /**
3714 * @brief Split into integer and fraction parts.
3715 * Both results carry the sign of the input variable.
3716 * @param x Input value
3717 * @param iptr Pointer to float128 holding the integer part of x.
3718 * @return The fraction part of x. Undefined when iptr is nullptr.
3719 */
3720 [[nodiscard]] friend FP128_FORCE_INLINE constexpr float128 modf(const float128& x, float128* iptr) noexcept
3721 {
3722 if (iptr == nullptr)
3723 return 0;
3724
3725 // A NaN splits into two NaNs, an infinity into itself and a zero fraction.
3726 if (x.is_nan()) {
3727 *iptr = propagate_nan(x);
3728 return *iptr;
3729 }
3730 *iptr = trunc(x);
3731 if (x.is_inf())
3732 return float128(0, static_cast<uint64_t>(x.get_sign()) << 63);
3733
3734 // The difference is exact, and a zero one takes the sign of x as C requires.
3735 float128 res = x - *iptr;
3736 res.set_sign(x.get_sign());
3737 return res;
3738 }
3739 /**
3740 * @brief Determines the positive difference between the first and second values.
3741 * @param x First value
3742 * @param y Second value
3743 * @return If x > y returns x - y. Otherwise zero.
3744 */
3745 [[nodiscard]] friend FP128_INLINE constexpr float128 fdim(const float128& x, const float128& y) noexcept
3746 {
3747 if (x.is_nan() || y.is_nan())
3748 return propagate_nan(x, y);
3749 return (x > y) ? x - y : float128();
3750 }
3751 /**
3752 * @brief Returns the minimum between x and y.
3753 * @param x First value
3754 * @param y Second value
3755 * @return If x < y returns x. Otherwise y.
3756 */
3757 [[nodiscard]] friend FP128_INLINE constexpr float128 fmin(const float128& x, const float128& y) noexcept
3758 {
3759 // A quiet NaN operand is treated as missing rather than as a value, so the other one wins.
3760 // Every comparison against a NaN is false, which made the plain conditional return
3761 // whichever operand happened to sit on the false branch. A signaling NaN is the invalid
3762 // operation instead, and produces a quiet NaN (IEEE 754-2008 minNum).
3763 if (x.is_signaling() || y.is_signaling())
3764 return propagate_nan(x, y);
3765 if (x.is_nan())
3766 return y;
3767 if (y.is_nan())
3768 return x;
3769 // The comparison operators treat the two zeros as equal, and the standard asks for the
3770 // negative one here.
3771 if (x.is_zero() && y.is_zero())
3772 return x.is_negative() ? x : y;
3773 return (x < y) ? x : y;
3774 }
3775 /**
3776 * @brief Returns the maximum between x and y.
3777 * @param x First value
3778 * @param y Second value
3779 * @return If x > y returns x. Otherwise y.
3780 */
3781 [[nodiscard]] friend FP128_INLINE constexpr float128 fmax(const float128& x, const float128& y) noexcept
3782 {
3783 if (x.is_signaling() || y.is_signaling())
3784 return propagate_nan(x, y);
3785 if (x.is_nan())
3786 return y;
3787 if (y.is_nan())
3788 return x;
3789 if (x.is_zero() && y.is_zero())
3790 return x.is_positive() ? x : y;
3791 return (x > y) ? x : y;
3792 }
3793 /**
3794 * @brief Calculates the hypotenuse. i.e. sqrt(x^2 + y^2)
3795 * @param x First value
3796 * @param y Second value
3797 * @return sqrt(x^2 + y^2).
3798 */
3799 [[nodiscard]] friend FP128_INLINE float128 hypot(const float128& x, const float128& y) noexcept
3800 {
3801 // An infinity wins even over a quiet NaN (IEEE 754-2008 9.2.1); a signaling NaN does not.
3802 if (x.is_signaling() || y.is_signaling())
3803 return propagate_nan(x, y);
3804 if (x.is_inf() || y.is_inf())
3805 return inf();
3806 if (x.is_nan() || y.is_nan())
3807 return propagate_nan(x, y);
3808
3809 // Scaling by the larger side keeps both squares inside the format's range. Squaring the
3810 // values as they came, as this used to, overflowed for a side above 2^8192 and lost
3811 // everything below 2^-8247 to underflow.
3812 const float128 largest = fmax(fabs(x), fabs(y));
3813 if (largest.is_zero())
3814 return largest;
3815 // From here on only the flags the result justifies reach the caller.
3816 detail::flag_filter filter;
3817 const int32_t expo = ilogb(largest);
3818 const float128 a = ldexp(x, -expo);
3819 const float128 b = ldexp(y, -expo);
3820 return filter(ldexp(sqrt(sqr(a) + sqr(b)), expo));
3821 }
3822 /**
3823 * @brief Calculates the square of a value. i.e. x^2
3824 *
3825 * Faster than x * x and identical to it, see float128::square().
3826 *
3827 * @param x Value to square
3828 * @return x^2, which is never negative.
3829 */
3830 [[nodiscard]] friend FP128_FORCE_INLINE constexpr float128 sqr(float128 x) noexcept { return x.square(); }
3831 /**
3832 * @brief Square of a 113 bit significand compared with a 256 bit value.
3833 * @param rl Low QWORD of the significand
3834 * @param rh High QWORD of the significand
3835 * @param n The value to compare against, n[0] the least significant word
3836 * @return Negative, zero or positive as r*r is below, equal to or above n.
3837 */
3838 [[nodiscard]] FP128_INLINE static constexpr int32_t square_compare(uint64_t rl, uint64_t rh, const uint64_t n[4]) noexcept
3839 {
3840 uint64_t sq[4] {};
3841 mul128to256(rl, rh, rl, rh, sq);
3842 for (int32_t i = 3; i >= 0; --i) {
3843 if (sq[i] != n[i])
3844 return (sq[i] > n[i]) ? 1 : -1;
3845 }
3846 return 0;
3847 }
3848
3849 /**
3850 * @brief Calculates the square root, correctly rounded.
3851 *
3852 * IEEE 754 requires the square root to be correctly rounded, the same as the four arithmetic
3853 * operations, and Newton's method alone cannot promise that: every step rounds, and the last one
3854 * can land a unit either side of the answer. It used to, for a quarter of all arguments.
3855 *
3856 * So Newton's method only gets close, and the last bit is then settled exactly. The mantissa m
3857 * (doubled when the exponent is odd, so that what is left of it halves exactly) is in
3858 * [2^112, 2^114), which puts the square root of N = m * 2^112 in [2^112, 2^113) - exactly the
3859 * 113 bit significand the result needs. Squaring a candidate r in integer arithmetic and
3860 * comparing with N moves it onto floor(sqrt(N)), and the remainder N - r*r then says which way
3861 * to round: the root is past the halfway point r + 1/2 exactly when the remainder exceeds r,
3862 * and it can never sit on it, because (r + 1/2)^2 is not an integer.
3863 *
3864 * Based on the book "Math toolkit for real time programming" by Jack W. Crenshaw.
3865 *
3866 * @param x Value to calculate the root of
3867 * @param iterations Ignored. The result is correctly rounded whatever its value; the parameter
3868 * is kept so that existing calls still compile.
3869 * @return Square root of x. sqrt(-0) is -0, and any other negative argument is the invalid
3870 * operation and returns a NaN.
3871 */
3872 [[nodiscard]] friend float128 sqrt(const float128& x, [[maybe_unused]] uint32_t iterations) noexcept
3873 {
3874 if (x.is_nan())
3875 return propagate_nan(x);
3876 if (x.is_zero())
3877 return x; // sqrt(-0) is -0
3878 if (x.is_negative())
3879 return invalid_operation();
3880 if (x.is_inf())
3881 return x;
3882
3883 // Split off an even power of two, leaving a mantissa in [1, 4). Halving an even exponent is
3884 // exact. Reading the mantissa through get_components() also normalizes a subnormal
3885 // argument.
3886 uint64_t l = 0, h = 0;
3887 int32_t expo = 0;
3888 uint32_t sign = 0;
3889 x.get_components(l, h, expo, sign);
3890 const int32_t odd = expo & 1;
3891 const float128 norm_x(l, h, static_cast<uint32_t>(EXP_BIAS + odd), 0);
3892 const int32_t half_expo = (expo - odd) / 2;
3893
3894 // The hardware double gives 53 correct bits to start from and every Newton step doubles
3895 // them, so two passes reach the last bit give or take the rounding of the steps themselves.
3896 // X
3897 // Xn+1 = 0.5 * (---- + Xn )
3898 // Xn
3899 float128 root;
3900 {
3901 // The steps are inexact even when the root is not; only the final rounding may say so.
3902 const detail::flag_quiet quiet;
3903 root = ::sqrt(static_cast<double>(norm_x));
3904 for (int32_t i = 0; i < 2; ++i)
3905 root = (norm_x / root + root) >> 1;
3906 }
3907
3908 // The candidate as a 113 bit integer. The root of a value below 4 is below 2, so an
3909 // exponent of one only arises from rounding up to 2 itself, and the largest significand
3910 // stands in for it.
3911 uint64_t rl = 0, rh = 0;
3912 int32_t root_expo = 0;
3913 uint32_t root_sign = 0;
3914 root.get_components(rl, rh, root_expo, root_sign);
3915 if (root_expo > 0) {
3916 rl = UINT64_MAX;
3917 rh = MAX_SIG_HIGH;
3918 }
3919
3920 // N = m * 2^112, with m the mantissa shifted up by one for an odd exponent.
3921 if (odd != 0)
3923 const uint64_t n[4] = {0, l << 48, (l >> 16) | (h << 48), h >> 16};
3924
3925 // Walk the candidate onto floor(sqrt(N)). It starts within a unit or two, so neither loop
3926 // runs more than twice.
3927 while (square_compare(rl, rh, n) > 0) {
3928 if (rl-- == 0)
3929 --rh;
3930 }
3931 for (;;) {
3932 uint64_t nl = rl + 1, nh = rh + ((rl == UINT64_MAX) ? 1 : 0);
3933 if (square_compare(nl, nh, n) > 0)
3934 break;
3935 rl = nl;
3936 rh = nh;
3937 }
3938
3939 // The remainder N - r*r is below 2r + 1, so it fits in the low 128 bits.
3940 uint64_t sq[4] {};
3941 mul128to256(rl, rh, rl, rh, sq);
3942 uint64_t rem_l = 0, rem_h = 0;
3943 const uint8_t borrow = subborrow_u64(0, n[0], sq[0], &rem_l);
3944 subborrow_u64(borrow, n[1], sq[1], &rem_h);
3945
3946 const bool exact = (rem_l | rem_h) == 0;
3947 const bool above_half = (rem_h > rh) || (rem_h == rh && rem_l > rl);
3948 const uint64_t extra = above_half ? ((1ull << 63) | 1) : (exact ? 0 : 1);
3949 return round_pack(0, half_expo, rl, rh, extra);
3950 }
3951 /**
3952 * @brief Calculates the cube root.
3953 * Uses the Halley's method.
3954 * @param x Floating point value
3955 * @param iterations how many Halley to perform, usually 1 is enough
3956 * @return cube root of x
3957 */
3958 [[nodiscard]] friend FP128_INLINE float128 cbrt(const float128 x, uint32_t iterations) noexcept
3959 {
3960 if (x.is_nan())
3961 return propagate_nan(x);
3962 // The real cube root is defined for a negative argument and is an odd function, which is
3963 // what the C library's cbrt computes. Returning a NaN, as this used to, made cbrt(-8)
3964 // undefined where the standard has it equal to -2.
3965 if (x.is_zero() || x.is_inf())
3966 return x;
3967 // From here on only the flags the result justifies reach the caller.
3968 detail::flag_filter filter;
3969
3970 // Split off a power of two whose exponent is a multiple of three, leaving a mantissa in
3971 // [1, 8). Dividing that exponent by three is exact, so no correction factor is needed.
3972 //
3973 // The factors this used to multiply by, cbrt(2)/2 and cbrt(4)/2, were written out to the
3974 // 17 digits a double round trips through and no further, so two thirds of all arguments
3975 // came back with 53 correct bits instead of 113.
3976 uint64_t l = 0, h = 0;
3977 int32_t expo = 0;
3978 uint32_t sign = 0;
3979 x.get_components(l, h, expo, sign);
3980 int32_t rem = expo % 3;
3981 if (rem < 0)
3982 rem += 3;
3983 const float128 norm_x(l, h, static_cast<uint32_t>(EXP_BIAS + rem), 0);
3984 const int32_t third_expo = (expo - rem) / 3;
3985
3986 // Halley's method triples the correct digits per pass, so two passes take the 53 bits the
3987 // hardware seed provides past the 113 the mantissa holds.
3988 float128 root = ::cbrt(static_cast<double>(norm_x));
3989
3990 // 3
3991 // Xn + 2X
3992 // Xn+1 = Xn ----------
3993 // 3
3994 // 2Xn + X
3995 const auto x2 = norm_x << 1;
3996 for (auto i = iterations; i != 0; --i) {
3997 float128 r_cube = root * root * root;
3998 root = root * (r_cube + x2) / ((r_cube << 1) + norm_x);
3999 }
4000
4001 root = ldexp(root, third_expo);
4002 root.set_sign(sign);
4003 return filter(root);
4004 }
4005 /**
4006 * @brief Calculates the reciprocal of a value, 1 / x, correctly rounded.
4007 *
4008 * The division itself, which rounds once in the current direction. This used to refine a
4009 * double seed with Newton iterations, which was a third of the speed of the division (11 M/s
4010 * against 35 M/s on MSVC, 10.5 against 37 on Clang, P-core, 2026-10-10) and up to an ulp off:
4011 * a subnormal result was rounded twice, and in a directed rounding mode the result could land
4012 * on the wrong side.
4013 *
4014 * @param x Input value
4015 * @return 1 / x. +-0 gives +-inf and raises division by zero, +-inf gives +-0, a NaN is propagated.
4016 */
4017 [[nodiscard]] friend FP128_INLINE float128 reciprocal(const float128& x) noexcept
4018 {
4019 float128 res = float128::one();
4020 res /= x;
4021 return res;
4022 }
4023 /**
4024 * @brief Factorial reciprocal (inverse). Calculates 1 / x!
4025 * Maximum supported value of x is 50.
4026 * @param x Input value
4027 * @param res Result of the function
4028 */
4029 friend FP128_INLINE void fact_reciprocal(int x, float128& res) noexcept
4030 {
4031 // Given as encodings rather than decimal strings. Several of the strings this replaced
4032 // were the 17 digit expansion of a double - 1/6! among them - which capped the accuracy of
4033 // every series built on the table at 53 bits. The exponential's own reduction is good to
4034 // better than 2^-110, and a single term formed from a double sized constant was throwing
4035 // 40 of those bits away.
4036 static constexpr float128 c[] = {
4037 float128(0x0000000000000000, 0x000000000000, 0x3FFF, 0), // 1 / 0!
4038 float128(0x0000000000000000, 0x000000000000, 0x3FFF, 0), // 1 / 1!
4039 float128(0x0000000000000000, 0x000000000000, 0x3FFE, 0), // 1 / 2!
4040 float128(0x5555555555555555, 0x555555555555, 0x3FFC, 0), // 1 / 3!
4041 float128(0x5555555555555555, 0x555555555555, 0x3FFA, 0), // 1 / 4!
4042 float128(0x1111111111111111, 0x111111111111, 0x3FF8, 0), // 1 / 5!
4043 float128(0x6C16C16C16C16C17, 0x6C16C16C16C1, 0x3FF5, 0), // 1 / 6!
4044 float128(0xA01A01A01A01A01A, 0xA01A01A01A01, 0x3FF2, 0), // 1 / 7!
4045 float128(0xA01A01A01A01A01A, 0xA01A01A01A01, 0x3FEF, 0), // 1 / 8!
4046 float128(0x38FAAC1C88E50017, 0x71DE3A556C73, 0x3FEC, 0), // 1 / 9!
4047 float128(0xC72EF016D3EA6679, 0x27E4FB7789F5, 0x3FE9, 0), // 1 / 10!
4048 float128(0x38FE747E4B837DC7, 0xAE64567F544E, 0x3FE5, 0), // 1 / 11!
4049 float128(0x7B544DA987ACFE85, 0x1EED8EFF8D89, 0x3FE2, 0), // 1 / 12!
4050 float128(0x97CA38331D23AF68, 0x6124613A86D0, 0x3FDE, 0), // 1 / 13!
4051 float128(0xD20BADF145DFA3E5, 0x93974A8C07C9, 0x3FDA, 0), // 1 / 14!
4052 float128(0xF11D8656B0EE8CB0, 0xAE7F3E733B81, 0x3FD6, 0), // 1 / 15!
4053 float128(0xF11D8656B0EE8CB0, 0xAE7F3E733B81, 0x3FD2, 0), // 1 / 16!
4054 float128(0xA6B2605197771B00, 0x952C77030AD4, 0x3FCE, 0), // 1 / 17!
4055 float128(0x77BB004886A2C2AB, 0x6827863B97D9, 0x3FCA, 0), // 1 / 18!
4056 float128(0x724CA1EC3B7B9675, 0x2F49B4681415, 0x3FC6, 0), // 1 / 19!
4057 float128(0x507A9CAD2BF8F0BB, 0xE542BA402022, 0x3FC1, 0), // 1 / 20!
4058 float128(0x18BEF146FCEE6E45, 0x71B8EF6DCF57, 0x3FBD, 0), // 1 / 21!
4059 float128(0x29450C90B7F338EC, 0x0CE396DB7F85, 0x3FB9, 0), // 1 / 22!
4060 float128(0x9D97B8704DD7F628, 0x761B41316381, 0x3FB4, 0), // 1 / 23!
4061 float128(0x7CCA4B4067CA9D8A, 0xF2CF01972F57, 0x3FAF, 0), // 1 / 24!
4062 float128(0x8D4E44A419776F11, 0x3F3CCDD165FA, 0x3FAB, 0), // 1 / 25!
4063 float128(0x9A38F2050BA6B015, 0x88E85FC6A4E5, 0x3FA6, 0), // 1 / 26!
4064 float128(0x320A9A18F15D4277, 0xD1AB1C2DCCEA, 0x3FA1, 0), // 1 / 27!
4065 float128(0xD373C5C51C354A8D, 0x0A18A2635085, 0x3F9D, 0), // 1 / 28!
4066 float128(0xD7ABE30E7766F129, 0x259F98B4358A, 0x3F98, 0), // 1 / 29!
4067 float128(0xE60CADED4C2989C5, 0x3932C5047D60, 0x3F93, 0), // 1 / 30!
4068 float128(0xC42E1EE46FA6BFC4, 0x434D2E783F5B, 0x3F8E, 0), // 1 / 31!
4069 float128(0xC42E1EE46FA6BFC4, 0x434D2E783F5B, 0x3F89, 0), // 1 / 32!
4070 float128(0x1B5382CDFFA97422, 0x3981254DD0D5, 0x3F84, 0), // 1 / 33!
4071 float128(0xA13F8A2B4AF9D6B7, 0x2710231C0FD7, 0x3F7F, 0), // 1 / 34!
4072 float128(0xF2833C7F5A7E0624, 0x0DC59C716D91, 0x3F7A, 0), // 1 / 35!
4073 float128(0x92B06B8D12A7275C, 0xDF983290C2CA, 0x3F74, 0), // 1 / 36!
4074 float128(0xAF4C78B15C3D89D3, 0x9EC8D1C94E85, 0x3F6F, 0), // 1 / 37!
4075 float128(0xAE913D370A4EC4E8, 0x5D4ACB9C0C3A, 0x3F6A, 0), // 1 / 38!
4076 float128(0xDE0104476AEB4C3B, 0x1E99449A4BAC, 0x3F65, 0), // 1 / 39!
4077 float128(0x3001A07244ABAD2B, 0xCA8ED42A12AE, 0x3F5F, 0), // 1 / 40!
4078 float128(0x0C7E25CFD1B1B2DD, 0x65E61C39D024, 0x3F5A, 0), // 1 / 41!
4079 float128(0x836C4D9225DCB90A, 0x10AF527530DE, 0x3F55, 0), // 1 / 42!
4080 float128(0x22DCBAE56DEF3720, 0x95DB45257E51, 0x3F4F, 0), // 1 / 43!
4081 float128(0xA4FD9F327E7F6DE9, 0x272B1B03FEC6, 0x3F4A, 0), // 1 / 44!
4082 float128(0x78E02C5E91C64CAC, 0xA3CB87222064, 0x3F44, 0), // 1 / 45!
4083 float128(0x062CA46E4F25C608, 0x240804F65951, 0x3F3F, 0), // 1 / 46!
4084 float128(0x9B78B454D8B628E5, 0x8DA8E0A127EB, 0x3F39, 0), // 1 / 47!
4085 float128(0x67A5CD8DE5CEC5EE, 0x091B406B6FF2, 0x3F34, 0), // 1 / 48!
4086 float128(0x5D94A3FD410E1232, 0x5A42F0DFEB08, 0x3F2E, 0), // 1 / 49!
4087 float128(0x8205F0A053453602, 0xBB36F6E12CD7, 0x3F28, 0), // 1 / 50!
4088 };
4089 constexpr int series_len = array_length(c);
4090 static_assert(series_len == 51);
4091
4092 res = (x >= 0 && x < series_len) ? c[x] : float128();
4093 }
4094 /**
4095 * @brief Returns the double factorial of a number, x!! = x * (x - 2) * (x - 4) * ...
4096 *
4097 * The values below 100 come from a table built during compilation, every product rounded to
4098 * nearest. Filling a function local table on first use, as this used to, was a data race when
4099 * two threads made the first call together, and under FP128_IEEE_ENV the products took the
4100 * rounding direction of whichever caller came first.
4101 *
4102 * @param x The number to compute the double factorial of.
4103 * @return x!!: exact for every odd x up to 51 and every even x up to 74, and within 1 ulp of the
4104 * correctly rounded value up to 99 (each product of the table rounds once, so the error
4105 * can accumulate). (-1)!! is 1, the empty product (2n - 1)!! takes for n = 0. Any other
4106 * negative x is the invalid operation and returns a NaN; x of 100 or more returns
4107 * infinity.
4108 */
4109 [[nodiscard]] friend FP128_INLINE float128 double_factorial(int x) noexcept
4110 {
4111 constexpr int32_t arr_size = 100;
4112 struct table_t {
4113 float128 c[arr_size]; ///< c[i] is i!!
4114 };
4115 static constexpr table_t table = [] {
4116 table_t t {};
4117 t.c[0] = float128::one();
4118 t.c[1] = float128::one();
4119 // the odd and even double factorials
4120 for (int32_t i = 2; i < arr_size - 1; i += 2) {
4121 t.c[i] = t.c[i - 2] * i;
4122 t.c[i + 1] = t.c[i - 1] * (i + 1);
4123 }
4124 return t;
4125 }();
4126 if (x < 0)
4127 return (x == -1) ? float128::one() : invalid_operation();
4128 if (x < arr_size)
4129 return table.c[x];
4130
4131 // TODO: compute the following members
4132 return float128::inf();
4133 }
4134 /**
4135 * x
4136 * @brief Calculates the exponent of x: e
4137 * Using the Maclaurin series expansion, the formula is:
4138 * 1 2 3
4139 * x x x
4140 * exp(x) = 1 + --- + --- + --- + ...
4141 * 1! 2! 3!
4142 *
4143 * The Maclaurin series will quickly overflow as x's power increases rapidly.
4144 * x ix fx
4145 * Using the equality e = e * e
4146 * Where ix is the integer part of x and fx is the fraction part.
4147 * ix is computed via multiplications which won't overflow if the result value can be held.
4148 * fx is computed via Maclaurin series expansion, but since fx < 1, it won't overflow.
4149 * @param x A number specifying a power.
4150 * @return Exponent of x
4151 */
4152 /// @brief Terms of the Maclaurin series exp_reduced() runs. |r| <= ln2/2, so r^28/28! is past the last bit.
4153 static constexpr int32_t EXP_TERMS = 28;
4154
4155 /**
4156 * @brief e to the power of a reduced argument, |r| <= ln2/2.
4157 * @param r Reduced argument
4158 * @return exp(r)
4159 */
4160 [[nodiscard]] FP128_INLINE static float128 exp_reduced(const float128& r) noexcept
4161 {
4162 float128 acc, factorial;
4164 for (int32_t n = EXP_TERMS - 1; n >= 0; --n) {
4165 fact_reciprocal(n, factorial);
4166 acc = factorial + r * acc;
4167 }
4168 return acc;
4169 }
4170
4171 /**
4172 * @brief Computes e to the power of x.
4173 *
4174 * x is written as k*ln2 + r with k an integer and |r| <= ln2/2, which turns the answer into
4175 * 2^k * exp(r): the power of two is an exact scaling and only the reduced argument goes
4176 * through a series.
4177 *
4178 * The reduction is where the accuracy of the whole function is decided. ln2 is irrational, so
4179 * k*ln2 cannot be represented and subtracting a rounded one leaves an error of k ulp - at the
4180 * top of the range k reaches 16000 and fourteen bits of the answer are gone before the series
4181 * even starts. Splitting ln2 into a high part whose low 14 bits are zero, so that k times it
4182 * is exact, and a low part carrying the rest, keeps r accurate to far below its last bit.
4183 *
4184 * The previous implementation raised e to the integer part by repeated squaring, which doubles
4185 * its own error at every step, and reached the negative half of the range through reciprocal().
4186 *
4187 * @param x A number specifying a power.
4188 * @return e^x
4189 */
4190 [[nodiscard]] friend FP128_INLINE float128 exp(const float128& x) noexcept
4191 {
4192 if (x.is_nan())
4193 return propagate_nan(x);
4194 if (x.is_inf())
4195 return x.is_negative() ? float128() : x;
4196 if (x.is_zero())
4197 return float128::one();
4198 // From here on only the flags the result justifies reach the caller.
4199 detail::flag_filter filter;
4200
4201 // log of the largest finite value is 11356.52, log of the smallest subnormal is -11433.46
4202 if (x > float128(11357))
4203 return filter.inexact(inf());
4204 if (x < float128(-11434))
4205 return filter.inexact(float128());
4206
4207 // ln2 to 321 bits, in three pieces. The first two have their low 16 mantissa bits zeroed,
4208 // so multiplying either by a k of up to 2^16 is exact and the products can be removed from
4209 // the argument without a rounding of their own.
4210 //
4211 // Two pieces would only carry ln2 to the 113 bits a float128 holds, which is not enough:
4212 // the reduction multiplies whatever error the constant has by k, and at the top of the
4213 // range k reaches 16000, so a constant good to 2^-114 leaves the reduced argument good to
4214 // only 2^-100 and the answer 8000 ulp wide.
4215 constexpr float128 ln2_hi(0xF35793C767300000, 0x62E42FEFA39E, 0x3FFE, 0);
4216 constexpr float128 ln2_mid(0x93394C5B16C50000, 0xF97B57A079A1, 0x3F98, 0);
4217 constexpr float128 ln2_lo(0x7CF70EC40DBD7593, 0xA2EB71755F45, 0x3F32, 0);
4218
4219 const int32_t k = static_cast<int32_t>(llround(x * float128::log2_e()));
4220 const float128 kf(k);
4221 // The first subtraction is exact, cancelling two values within a factor of two of each
4222 // other; the others remove quantities far below the last place of the result.
4223 const float128 r = ((x - kf * ln2_hi) - kf * ln2_mid) - kf * ln2_lo;
4224
4225 return filter(ldexp(exp_reduced(r), k));
4226 }
4227 /**
4228 * @brief Computes 2 to the power of x
4229 * @param x Exponent value
4230 * @return 2^x
4231 */
4232 [[nodiscard]] friend FP128_INLINE float128 exp2(const float128& x) noexcept
4233 {
4234 //
4235 // Based on exponent law: (x^n)^m = x^(m*n)
4236 // Convert the exponent x (function parameter) to produce an exponent that will work with exp()
4237 // y = log(2)
4238 // 2^x = e^(y*x) = exp(y*x)
4239 //
4240 if (x.is_nan())
4241 return propagate_nan(x);
4242 if (x.is_inf())
4243 return x.is_negative() ? float128() : x;
4244 if (x.is_zero())
4245 return float128::one();
4246 // From here on only the flags the result justifies reach the caller.
4247 detail::flag_filter filter;
4248 if (x > float128(16384))
4249 return filter.inexact(inf());
4250 if (x < float128(-16495))
4251 return filter.inexact(float128());
4252
4253 // The integer part scales exactly, so only the fraction reaches exp() and the argument it
4254 // is handed stays small enough that the rounding of the multiply below is the only error.
4255 // That rounding is then recovered with an exact fma and folded back in: exp(p + e) is
4256 // exp(p) * (1 + e) to well past the last bit for an e this small.
4257 const int32_t k = static_cast<int32_t>(llround(x));
4258 const float128 f = x - float128(k);
4259 const float128 p = f * float128::ln2();
4260 const float128 correction = fma(f, float128::ln2(), -p);
4261
4262 return filter(ldexp(exp(p) * (float128::one() + correction), k));
4263 }
4264 /**
4265 * @brief Calculates the exponent of x and reduces 1 from the result: (e^x) - 1
4266 * @param x A number specifying a power.
4267 * @return Exponent of x
4268 */
4269 [[nodiscard]] friend FP128_INLINE float128 expm1(const float128& x) noexcept
4270 {
4271 if (x.is_nan())
4272 return propagate_nan(x);
4273 if (x.is_zero())
4274 return x;
4275 if (x.is_inf())
4276 return x.is_negative() ? -float128::one() : x;
4277 // From here on only the flags the result justifies reach the caller.
4278 detail::flag_filter filter;
4279
4280 // Half is the point where exp(x) - 1 stops throwing away significant bits: below it the
4281 // subtraction cancels most of what exp() produced, and at 2^-60 there is nothing left of
4282 // the answer at all. The Maclaurin series has no cancellation - every term is formed from
4283 // the argument itself - and needs 30 terms to reach the last bit at this magnitude.
4284 if (fabs(x) <= float128::half()) {
4285 constexpr int32_t terms = 30;
4286 float128 acc, factorial;
4287 fact_reciprocal(terms + 1, acc);
4288 for (int32_t n = terms - 1; n >= 0; --n) {
4289 fact_reciprocal(n + 1, factorial);
4290 acc = factorial + x * acc;
4291 }
4292 return filter(x * acc);
4293 }
4294
4295 return filter(exp(x) - float128::one());
4296 }
4297 /**
4298 * @brief a^n by repeated squaring, for a positive finite a.
4299 *
4300 * A negative exponent inverts the power, unless the power overflowed or underflowed on its way
4301 * there while its reciprocal would not have: then exp() and log() reach it directly.
4302 *
4303 * @param a Base, positive and finite
4304 * @param n Exponent
4305 * @return a^n.
4306 */
4307 [[nodiscard]] FP128_INLINE static float128 pown_magnitude(const float128& a, int32_t n) noexcept
4308 {
4309 // The magnitude is taken in the unsigned domain: negating the most negative int32_t is
4310 // undefined.
4311 uint32_t expo = (n < 0) ? (0u - static_cast<uint32_t>(n)) : static_cast<uint32_t>(n);
4312 float128 res = float128::one();
4313 float128 b = a;
4314 while (expo > 0) {
4315 if (expo & 1)
4316 res *= b;
4317 expo >>= 1;
4318 if (expo > 0)
4319 b.square();
4320 }
4321 if (n >= 0)
4322 return res;
4323 if (res.is_inf() || res.is_zero() || res.is_subnormal())
4324 return exp(float128(n) * log(a));
4325 return float128::one() / res;
4326 }
4327 /**
4328 * @brief Computes x to the power of y (IEEE 754-2008 pown)
4329 * @param x Base value
4330 * @param y Exponent value (integer)
4331 * @return x^y
4332 */
4333 [[nodiscard]] friend FP128_INLINE float128 pow(const float128& x, int32_t y) noexcept
4334 {
4335 // Every int32_t is exact in a float128, so the general function answers this too, with
4336 // IEEE 754's pown special cases being the same as its pow ones for an integer exponent.
4337 return pow(x, float128(y));
4338 }
4339 /**
4340 * @brief Computes x to the power of y
4341 *
4342 * The special values follow IEEE 754-2008 9.2.1 throughout. Among those the previous version
4343 * got wrong: pow(0.5, inf) and pow(2, -inf) were infinite rather than zero, pow(2, NaN) was
4344 * infinite, pow(-0, 0.5) a NaN, and every integer exponent beyond 11355 in magnitude overflowed
4345 * whatever the base, so pow(1 + 2^-40, 12000), which is about 1.00000001, came out infinite.
4346 *
4347 * Accuracy, measured against mpmath and pinned by tests/float128_accuracy_gtest.cpp: within
4348 * 4 + 2.5 |y log2(x)| ulp, which is about 41000 ulp next to the overflow and underflow
4349 * thresholds, where |y log2(x)| reaches 16383. Both methods below lose about two ulp per unit of
4350 * that product - the relative error of log(x), or of every squaring, becomes an absolute error
4351 * of the exponent, and the exponential makes it relative again - and holding it to a few ulp
4352 * would take an intermediate wider than 113 bits. A y of 1/2 is the square root, correctly
4353 * rounded.
4354 *
4355 * @param x Base value
4356 * @param y Exponent value
4357 * @return x^y
4358 */
4359 [[nodiscard]] friend FP128_INLINE float128 pow(const float128& x, const float128& y) noexcept
4360 {
4361 const float128 one_value = float128::one();
4362
4363 // IEEE 754-2008 9.2.1, in the order its exceptions to the NaN rule need: x^0 is one and
4364 // so is 1^y, for any x and y, quiet NaNs included.
4365 if (y.is_zero() || x == one_value) {
4366 if (x.is_signaling() || y.is_signaling())
4367 return propagate_nan(x, y);
4368 return one_value;
4369 }
4370 if (x.is_nan() || y.is_nan())
4371 return propagate_nan(x, y);
4372
4373 // The sign of a zero or infinite x survives only an odd integer exponent.
4374 const bool y_odd = is_odd_int(y);
4375 const bool negative_odd = x.is_negative() && y_odd;
4376 if (x.is_zero()) {
4377 if (y.is_negative()) {
4378 // a pole, except that 0^-inf is an exact infinity
4379 if (!y.is_inf())
4380 detail::raise_flags(FE_DIVBYZERO);
4381 return negative_odd ? -inf() : inf();
4382 }
4383 return negative_odd ? x : float128();
4384 }
4385 if (y.is_inf()) {
4386 const float128 a = fabs(x);
4387 if (a == one_value)
4388 return one_value; // (-1)^+-inf
4389 return ((a > one_value) != y.is_negative()) ? inf() : float128();
4390 }
4391 if (x.is_inf()) {
4392 if (y.is_negative())
4393 return negative_odd ? -float128() : float128();
4394 return negative_odd ? -inf() : inf();
4395 }
4396
4397 // Both finite and non zero. A negative base has a real power only for an integer exponent.
4398 if (x.is_negative() && !y.is_int())
4399 return invalid_operation();
4400 // x^0.5 is the square root, which is correctly rounded and so exact wherever the root is
4401 // representable. Through exp(log(x)/2) it was 300 ulp off at the top of the range and 4000
4402 // off sqrt(denorm_min) = 2^-8247, which is exact.
4403 if (y == float128::half()) {
4404 return sqrt(x);
4405 }
4406 // From here on only the flags the result justifies reach the caller.
4407 detail::flag_filter filter;
4408
4409 const float128 a = fabs(x);
4410 float128 res;
4411 // Repeated multiplication is exact for as long as the powers are, and otherwise loses
4412 // about half an ulp per unit of the exponent; exp(y * log(a)) loses about half an ulp per
4413 // unit of y * log(a) instead. The multiplication wins for a short exponent, and for any
4414 // base outside [1/2, 2) where log(a) is at least about one. It is limited to exponents an
4415 // int32_t holds, which is more than any finite result needs at that size.
4416 const int32_t a_expo = ilogb(a);
4417 if (y.is_int() && fabs(y) <= float128(INT32_MAX) && (fabs(y) <= float128(64) || a_expo >= 1 || a_expo <= -2))
4418 res = pown_magnitude(a, static_cast<int32_t>(y));
4419 else
4420 res = exp(y * log(a));
4421
4422 return filter(negative_odd ? -res : res);
4423 }
4424 /**
4425 * @brief The arguments every logarithm treats alike (IEEE 754-2008 9.2.1).
4426 *
4427 * A NaN propagates, a zero is a pole - the division by zero exception, and -inf - any other
4428 * negative argument is the invalid operation, and +inf is its own logarithm. log2() used to
4429 * return -inf for a negative argument, a finite value for +inf, and a finite value for a NaN.
4430 *
4431 * @param x Argument
4432 * @param result Receives the answer when there is one
4433 * @return True when x was one of these and @p result holds the answer.
4434 */
4435 [[nodiscard]] FP128_INLINE static constexpr bool log_special(const float128& x, float128& result) noexcept
4436 {
4437 if (x.is_nan()) {
4438 result = propagate_nan(x);
4439 return true;
4440 }
4441 if (x.is_zero()) {
4442 detail::raise_flags(FE_DIVBYZERO);
4443 result = -inf();
4444 return true;
4445 }
4446 if (x.is_negative()) {
4447 result = invalid_operation();
4448 return true;
4449 }
4450 if (x.is_inf()) {
4451 result = x;
4452 return true;
4453 }
4454 return false;
4455 }
4456
4457 /// @brief Largest |t| the log1p_small() series is used for. Chosen so twelve terms suffice.
4458 [[nodiscard]] FP128_FORCE_INLINE static constexpr float128 log1p_small_limit() noexcept { return float128(0, 0, EXP_BIAS - 4, 0); }
4459 /// @brief Terms of the log1p_small() series. |s| stays below 2^-4.9, so s^24 is past the last bit.
4460 static constexpr int32_t LOG1P_TERMS = 12;
4461
4462 /**
4463 * @brief Natural logarithm of 1+t for |t| <= 2^-4, accurate relative to the result.
4464 *
4465 * log(1+t) = 2 * atanh(t / (2+t)). The substitution replaces the Mercator series in t, which
4466 * would need a hundred terms at this precision, with one in s^2 where |s| < 2^-4.9, so twelve
4467 * terms reach the last bit of the mantissa.
4468 *
4469 * What matters more than the term count is that the result stays accurate relative to its own
4470 * size. Near one the logarithm is proportional to t, and t reaches this function exactly - the
4471 * subtraction that produced it cancelled two values within a factor of two of each other, which
4472 * is exact. Computing the same thing as a difference of two numbers near one loses a bit for
4473 * every power of two the argument sits closer to one: at t = 2^-60 barely half the mantissa
4474 * survives.
4475 *
4476 * @param t Offset from one, must satisfy |t| <= 2^-4
4477 * @return log(1+t)
4478 */
4479 [[nodiscard]] FP128_INLINE static float128 log1p_small(const float128& t) noexcept
4480 {
4481 if (t.is_zero())
4482 return t;
4483 // Below 2^-60 the cubic term is under 2^-120 of the result, so t - t^2/2 is the answer to
4484 // the last bit. The substitution below would halve t first, which for a subnormal t rounds
4485 // away its last bit: log1p(denorm_min) came out zero.
4486 if (fabs(t) < float128(0, 0, EXP_BIAS - 60, 0)) {
4487 return t - (sqr(t) >> 1);
4488 }
4489
4490 const float128 s = t / (float128(2) + t);
4491 const float128 w = sqr(s);
4492
4493 // 1/(2k+1) for the Horner pass below. Built once: the divisions are far more expensive
4494 // than the series itself, and the values do not depend on the argument.
4495 static const auto odd_reciprocal = [] {
4496 std::array<float128, LOG1P_TERMS + 1> table {};
4497 for (int32_t k = 0; k <= LOG1P_TERMS; ++k)
4498 table[static_cast<size_t>(k)] = float128::one() / float128(2 * k + 1);
4499 return table;
4500 }();
4501
4502 float128 acc = odd_reciprocal[LOG1P_TERMS];
4503 for (int32_t k = LOG1P_TERMS - 1; k >= 0; --k)
4504 acc = odd_reciprocal[static_cast<size_t>(k)] + w * acc;
4505
4506 return (s * acc) << 1;
4507 }
4508 /**
4509 * @brief Calculates the natural Log (base e) of x: log(x)
4510 * @param x The number to perform log on.
4511 * @return log(x)
4512 */
4513 [[nodiscard]] friend FP128_INLINE float128 log(float128 x) noexcept
4514 {
4515 float128 special;
4516 if (log_special(x, special))
4517 return special;
4518 // From here on only the flags the result justifies reach the caller.
4519 detail::flag_filter filter;
4520
4521 // Sterbenz guarantees the subtraction is exact over the range the branch covers, so the
4522 // series below sees the offset from one with every bit it has.
4523 const float128 t = x - float128::one();
4524 if (fabs(t) <= log1p_small_limit())
4525 return filter(log1p_small(t));
4526
4527 return filter(log2(x) * float128::ln2());
4528 }
4529 /**
4530 * @brief Calculates the Log base 2 of x: y = log2(x)
4531 *
4532 * Accurate relative to its own result, which matters most for an argument close to one: the
4533 * answer is then proportional to x - 1, and that difference is carried through exactly rather
4534 * than being rounded onto a grid it would barely register on. That holds on both sides of one;
4535 * below it the exponent is -1, and the answer is formed without the -1 that would cancel. The
4536 * earlier implementation built the answer as a fixed point fraction of 112 bits before
4537 * returning it as a float, which left log2(1 + 2^-112) with no correct significant bits at all.
4538 *
4539 * @param x The number to perform log2 on.
4540 * @return log2(x)
4541 */
4542 [[nodiscard]] friend FP128_INLINE float128 log2(float128 x) noexcept
4543 {
4544 float128 special;
4545 if (log_special(x, special))
4546 return special;
4547 // From here on only the flags the result justifies reach the caller.
4548 detail::flag_filter filter;
4549
4550 // Calculate the log in 2 steps:
4551 // - The integer part is simple and fast via the exponent.
4552 // - The fraction part is log2 of the mantissa, by argument reduction and a short series.
4553 // The result is the sum of the two. Based on the identity:
4554 // log(x + y) = log(x) + log(y)
4555 //
4556 // The exponent comes from get_components(), which normalizes a subnormal: the exponent
4557 // field of every subnormal is the same and says nothing about its magnitude.
4558 uint64_t frac_low = 0, frac_high = 0;
4559 int32_t expo = 0;
4560 uint32_t mantissa_sign = 0;
4561 x.get_components(frac_low, frac_high, expo, mantissa_sign);
4562 frac_high &= UPPER_FRAC_MASK; // drop the unity bit, leaving f in [0,1) scaled by 2^112
4563
4564 // x is a power of 2, so the mantissa contributes nothing.
4565 if ((frac_low | frac_high) == 0) {
4566 return filter(float128(expo));
4567 }
4568
4569 // The leading log2_reduction_bits fraction bits choose the reciprocal to reduce with.
4570 const size_t j = static_cast<size_t>(frac_high >> (FRAC_BITS - 64 - log2_reduction_bits));
4571
4572 // x in [1 - 2^-6, 1): the exponent is -1 and the mantissa is within 2^-5 of two, which puts
4573 // its leading fraction bits in one of the last two table rows.
4574 constexpr size_t entries = size_t{1} << log2_reduction_bits;
4575 const bool just_below_one = (expo == -1) && (j >= entries - 2);
4576
4577 // z, the reduced argument, as a 128 bit fraction. The series below needs |z| <= 2^-6.
4578 uint64_t z_low = 0, z_high = 0;
4579 uint32_t z_sign = 0;
4580 if (j == 0) {
4581 // Already inside the series' range, so no reduction is applied - and none is wanted.
4582 // f is exact here, and multiplying it by a rounded reciprocal would cost it every
4583 // significant bit it has when it is small. That is what makes log2 near 1 accurate:
4584 // the answer is then proportional to f, and f survives intact.
4585 z_low = frac_low << 16;
4586 z_high = (frac_high << 16) | (frac_low >> 48);
4587 } else if (just_below_one) {
4588 // The mirror image of the case above. Reducing from the exponent -1 would form the
4589 // answer as -1 plus the logarithm of a mantissa just under two, and that sum cancels: it
4590 // loses a bit for every power of two x sits closer to one, half the mantissa at 2^-60
4591 // below one and nearly all of it at 2^-110. Instead the series is taken at one itself,
4592 // with z = x - 1. That difference is exact - x is mantissa/2, which as a 128 bit fraction
4593 // has room for every bit of it - and the answer is then proportional to z, as above.
4594 const uint64_t m_low = frac_low << 15;
4595 const uint64_t m_high = (1ull << 63) | (frac_high << 15) | (frac_low >> 49);
4596 const uint8_t borrow = subborrow_u64(0, 0, m_low, &z_low);
4597 subborrow_u64(borrow, 0, m_high, &z_high);
4598 z_sign = 1;
4599 } else {
4600 // mantissa/2 as a 128 bit fraction, which is in [0.5,1)
4601 const uint64_t m_low = frac_low << 15;
4602 const uint64_t m_high = (1ull << 63) | (frac_high << 15) | (frac_low >> 49);
4603 uint64_t p_low = 0, p_high = 0;
4604 mul128_high(m_low, m_high, log2_recip_table[j][1], log2_recip_table[j][0], p_low, p_high);
4605
4606 // z = 2 * (mantissa/2 * recip) - 1. Normally non negative; a reciprocal that rounded
4607 // down can take it just below zero.
4608 constexpr uint64_t one_half = 1ull << 63;
4609 uint64_t d_low = 0, d_high = 0;
4610 if (p_high >= one_half) {
4611 d_low = p_low;
4612 d_high = p_high - one_half;
4613 } else {
4614 d_low = 0ull - p_low;
4615 d_high = one_half - p_high - ((p_low != 0) ? 1ull : 0ull);
4616 z_sign = 1;
4617 }
4618 z_low = d_low << 1;
4619 z_high = (d_high << 1) | (d_low >> 63);
4620 }
4621
4622 // Horner over 1/(n*ln2), from the last term down, giving A = log2(1+z)/z.
4623 //
4624 // Every value here is halved relative to the mathematics - log2_inv_n_table already holds
4625 // 1/(2n*ln2) - so that all of them stay below one and can be held as plain 128 bit
4626 // fractions. A is about 1.44 and would not fit otherwise. The accumulator stays inside
4627 // [0.019, 0.734] throughout, so neither the subtraction nor the addition can leave range.
4628 uint64_t acc_low = log2_inv_n_table[LOG2_TERMS - 1][1];
4629 uint64_t acc_high = log2_inv_n_table[LOG2_TERMS - 1][0];
4630 for (int32_t n = LOG2_TERMS - 1; n >= 1; --n) {
4631 uint64_t term_low = 0, term_high = 0;
4632 mul128_high(z_low, z_high, acc_low, acc_high, term_low, term_high);
4633 const uint64_t q_low = log2_inv_n_table[n - 1][1], q_high = log2_inv_n_table[n - 1][0];
4634 if (z_sign) {
4635 const uint8_t carry = addcarryx_u64(0, q_low, term_low, &acc_low);
4636 addcarryx_u64(carry, q_high, term_high, &acc_high);
4637 } else {
4638 const uint8_t borrow = subborrow_u64(0, q_low, term_low, &acc_low);
4639 subborrow_u64(borrow, q_high, term_high, &acc_high);
4640 }
4641 }
4642
4643 // The rest of (0.5, 1) that the table reduces. The answer is -1 + T + S, where T is the table
4644 // value below and S the series, and it is as small as 0.0227, so the -1 still cancels up to
4645 // five and a half bits. Rounding T to a float128 first leaves an absolute error of 2^-114
4646 // for those bits to expose - measured, up to 9 ulp at 1 - 2^-4 and 42 at 1 - 2^-6 - so the
4647 // sum is formed on the exact 128 bit fractions instead, where every term is good to a few
4648 // units of 2^-128, and rounded once. That keeps this range within 0.75 ulp.
4649 if (expo == -1 && j != 0 && !just_below_one) {
4650 uint64_t s_low = 0, s_high = 0;
4651 mul128_high(z_low, z_high, acc_low, acc_high, s_low, s_high);
4652 s_high = (s_high << 1) | (s_low >> 63); // undo the halving the table carries
4653 s_low <<= 1;
4654
4655 // r = 1 - T - S = -log2(x). T is in (0,1), so 1 - T fits a fraction exactly.
4656 uint64_t r_low = 0, r_high = 0;
4657 const uint8_t borrow = subborrow_u64(0, 0, log2_value_table[j][1], &r_low);
4658 subborrow_u64(borrow, 0, log2_value_table[j][0], &r_high);
4659 if (z_sign) {
4660 const uint8_t carry = addcarryx_u64(0, r_low, s_low, &r_low);
4661 addcarryx_u64(carry, r_high, s_high, &r_high);
4662 } else {
4663 const uint8_t borrow_s = subborrow_u64(0, r_low, s_low, &r_low);
4664 subborrow_u64(borrow_s, r_high, s_high, &r_high);
4665 }
4666
4667 float128 res = from_fraction128(r_low, r_high);
4668 res.set_sign(1);
4669 return filter(res);
4670 }
4671
4672 // The product is formed in float128 rather than in the fraction arithmetic above. A fraction
4673 // grid is absolute, and log2(1+z) is proportional to z, so holding the product on that grid
4674 // would leave a small result with only as many significant bits as it has room above 2^-128.
4675 // Multiplying an exact z by an A that is accurate in its own right keeps the answer accurate
4676 // relative to its own size, which is what a floating point type is expected to do.
4677 float128 series = from_fraction128(z_low, z_high) * from_fraction128(acc_low, acc_high);
4678 series <<= 1; // undo the halving the table carries
4679 series.set_sign(z_sign);
4680
4681 // Taken at one, so the series is the whole answer: neither the exponent nor a table value
4682 // applies.
4683 if (just_below_one) {
4684 return filter(series);
4685 }
4686
4687 // -log2(recip), the part of the answer the reduction removed. Zero when nothing was reduced.
4688 const float128 table_value = (j != 0) ? from_fraction128(log2_value_table[j][1], log2_value_table[j][0]) : float128();
4689
4690 // The two fraction parts are summed before the exponent is added in. Both are below one, so
4691 // that first addition rounds against a small value; adding the exponent first would round
4692 // twice against a number as large as 16000 and cost the answer a bit for nothing.
4693 return filter(float128(expo) + (table_value + series));
4694 }
4695 /**
4696 * @brief Calculates Log base 10 of x: log10(x)
4697 * @param x The number to perform log on.
4698 * @return log10(x)
4699 */
4700 [[nodiscard]] friend FP128_INLINE float128 log10(float128 x) noexcept
4701 {
4702 float128 special;
4703 if (log_special(x, special))
4704 return special;
4705 // From here on only the flags the result justifies reach the caller.
4706 detail::flag_filter filter;
4707
4708 const float128 t = x - float128::one();
4709 if (fabs(t) <= log1p_small_limit())
4710 return filter(log1p_small(t) * float128::log10_e());
4711
4712 return filter(log2(x) * float128::log10_2());
4713 }
4714 /**
4715 * @brief Calculates Log base 2 of x as an integer ignoring the sign of x.
4716 * Similar to: floor(log2(fabs(x)))
4717 * @param x The number to perform log on.
4718 * @return logb(x)
4719 */
4720 [[nodiscard]] friend FP128_INLINE float128 logb(float128 x) noexcept
4721 {
4722 if (x.is_nan())
4723 return propagate_nan(x);
4724 if (x.is_inf())
4725 return fabs(x);
4726 if (x.is_zero()) {
4727 detail::raise_flags(FE_DIVBYZERO);
4728 return -inf();
4729 }
4730
4731 // get_components() normalizes a subnormal, whose stored exponent field is the same for
4732 // every one of them and therefore says nothing about the value.
4733 uint64_t l = 0, h = 0;
4734 int32_t expo = 0;
4735 uint32_t sign = 0;
4736 x.get_components(l, h, expo, sign);
4737 return float128(expo);
4738 }
4739 /**
4740 * @brief Calculates the natural Log (base e) of 1 + x: log(1 + x)
4741 * @param x The number to perform log on.
4742 * @return log1p(x)
4743 */
4744 [[nodiscard]] friend FP128_INLINE float128 log1p(float128 x) noexcept
4745 {
4746 if (x.is_nan())
4747 return propagate_nan(x);
4748 if (x.is_zero() || (x.is_inf() && x.is_positive()))
4749 return x;
4750
4751 const float128 one_value = float128::one();
4752 if (x < -one_value)
4753 return invalid_operation();
4754 if (x == -one_value) {
4755 detail::raise_flags(FE_DIVBYZERO);
4756 return -inf();
4757 }
4758 // From here on only the flags the result justifies reach the caller.
4759 detail::flag_filter filter;
4760
4761 if (fabs(x) <= log1p_small_limit())
4762 return filter(log1p_small(x));
4763
4764 // Above the series' range but still below one, 1+x rounds and the logarithm of a value
4765 // that close to one magnifies the error. Both subtractions below are exact - the first by
4766 // Sterbenz, the second because the operands agree to within a rounding - so the correction
4767 // puts back exactly what the rounding of 1+x took away.
4768 if (fabs(x) < one_value) {
4769 const float128 sum = one_value + x;
4770 const float128 rounding = (sum - one_value) - x;
4771 return filter(log(sum) - rounding / sum);
4772 }
4773
4774 return filter(log(one_value + x));
4775 }
4776
4777 //
4778 // Trigonometric functions
4779 //
4780
4781 /**
4782 * @brief Calculate the sine function over a limited range [-0.5pi, 0.5pi]
4783 * Using the Maclaurin series expansion, the formula is:
4784 * x^3 x^5 x^7
4785 * sin(x) = x - --- + --- - --- + ...
4786 * 3! 5! 7!
4787 * @param x value in Radians in the range [-0.5pi, 0.5pi]
4788 * @return Sine of x
4789 */
4790 [[nodiscard]] friend FP128_INLINE float128 sin1(float128 x) noexcept
4791 {
4792 assert(fabs(x) <= float128::half_pi());
4793
4794 // first part of the series is just 'x'
4795 const float128 xx = x * x;
4796 float128 elem_denom, elem_nom = x;
4797
4798 // Compute the rest of the series, starting with: -(x^3 / 3!). The reciprocal factorials stop
4799 // at 1/50!, and the argument is reduced long before the terms could need more; the bound
4800 // only makes sure an unreduced argument cannot keep the loop alive. One once could: past
4801 // 2^321 the powers overflow, inf * 0 is a NaN, and a NaN never compares equal to zero.
4802 for (int i = 3, sign = 1; i <= 51; i += 2, sign = 1 - sign) {
4803 elem_nom *= xx;
4804 fact_reciprocal(i, elem_denom);
4805 float128 elem = elem_nom * elem_denom; // next element in the series
4806 // precision limit has been hit
4807 if (!elem)
4808 break;
4809 x += (sign) ? -elem : elem;
4810 }
4811
4812 return x;
4813 }
4814 /// @brief Terms of the cosine series cos1() runs. Up to pi/4, x^32/32! is below 2^-125.
4815 static constexpr int32_t COS_TERMS = 16;
4816
4817 /**
4818 * @brief Calculate the cosine function over a limited range [-0.5pi, 0.5pi]
4819 *
4820 * Up to pi/4, the range the trigonometric functions reduce their argument to, the Maclaurin
4821 * series is evaluated as one minus its tail:
4822 *
4823 * 2 4 6
4824 * x x x
4825 * cos(x) = 1 - ( --- - ( --- - ( --- - ...)))
4826 * 2! 4! 6!
4827 *
4828 * The tail is at most 0.3 and is formed from the argument alone, so it carries its own last
4829 * bits and the subtraction from one rounds once. A zero argument gives exactly one, and so does
4830 * any argument whose square is below the last place of one. This used to be computed as
4831 * sin1(pi/2 - x), whose series sums to 1 - 2^-113 for x = 0: cos(0) and sin(pi/2) were not one.
4832 *
4833 * Beyond pi/4 the cosine is the sine of the complement, which stays accurate near pi/2 where the
4834 * series above would cancel down to nothing.
4835 *
4836 * @param x value in Radians in the range [-0.5pi, 0.5pi]
4837 * @return Cosine of x
4838 */
4839 [[nodiscard]] friend FP128_INLINE float128 cos1(const float128& x) noexcept
4840 {
4841 constexpr float128 half_pi = float128::half_pi();
4842 assert(fabs(x) <= half_pi);
4843 if (fabs(x) > float128::quarter_pi()) {
4844 return (x.is_positive()) ? sin1(half_pi - x) : -sin1(-half_pi - x);
4845 }
4846
4847 const float128 xx = x * x;
4848 float128 tail, factor;
4849 fact_reciprocal(2 * COS_TERMS, tail);
4850 for (int32_t k = COS_TERMS - 1; k >= 1; --k) {
4851 fact_reciprocal(2 * k, factor);
4852 tail = factor - xx * tail;
4853 }
4854 return float128::one() - xx * tail;
4855 }
4856 /**
4857 * @brief Calculate the Sine function
4858 * Ultimately uses sin() with a reduced range of [-pi/4, pi/4]
4859 * @param x value in Radians
4860 * @return Sine of x
4861 */
4862 /**
4863 * @name Unevaluated sums
4864 *
4865 * A value held as a pair of float128 whose sum is the quantity meant, with the second one
4866 * below the last place of the first. That is 226 bits of significand out of two 113 bit
4867 * values, which is what the trigonometric argument reduction needs: the residual it produces
4868 * has to be known to the absolute precision of the *result*, and near a zero of the sine the
4869 * result is many orders of magnitude below the argument it came from.
4870 * @{
4871 */
4872
4873 /**
4874 * @brief Exact sum of two values, as a rounded sum and the error it made.
4875 *
4876 * Dekker's algorithm. Nothing here is an approximation: a + b is exactly sum + err for any two
4877 * finite operands.
4878 *
4879 * @param a First operand
4880 * @param b Second operand
4881 * @param sum Receives the rounded sum
4882 * @param err Receives a + b - sum, exactly
4883 */
4884 FP128_INLINE static void two_sum(const float128& a, const float128& b, float128& sum, float128& err) noexcept
4885 {
4886 sum = a + b;
4887 const float128 b_part = sum - a;
4888 err = (a - (sum - b_part)) + (b - b_part);
4889 }
4890
4891 /**
4892 * @brief Exact sum of two values whose magnitudes are ordered.
4893 * @param a First operand, must not be smaller in magnitude than b
4894 * @param b Second operand
4895 * @param sum Receives the rounded sum
4896 * @param err Receives a + b - sum, exactly
4897 */
4898 FP128_INLINE static void quick_two_sum(const float128& a, const float128& b, float128& sum, float128& err) noexcept
4899 {
4900 sum = a + b;
4901 err = b - (sum - a);
4902 }
4903 /// @}
4904
4905 /**
4906 * @brief Nearest integer to x / (pi/2), the quadrant the argument falls in.
4907 *
4908 * Beyond 2^62 the quadrant no longer fits in the integer the reduction counts with, and an
4909 * argument that large has fewer bits below the binary point than a quadrant is wide - its
4910 * sine is not determined by the value in any useful sense. Everything up to there reduces
4911 * exactly, see reduce_half_pi().
4912 *
4913 * @param x Argument, below 2^60 in magnitude; reduce_large() takes the larger ones
4914 * @return Quadrant index, zero for an argument too large to reduce.
4915 */
4916 [[nodiscard]] FP128_INLINE static int64_t quadrant_of(const float128& x) noexcept
4917 {
4918 constexpr float128 two_over_pi(0x2A53F84EAFA3EA6A, 0x45F306DC9C88, 0x3FFE, 0);
4919 const float128 scaled = x * two_over_pi;
4920 if (fabs(scaled) >= ldexp(float128::one(), 62))
4921 return 0;
4922 return llround(scaled);
4923 }
4924
4925 /**
4926 * @brief Reduces an argument of any size: x = n * pi/2 + r, with |r| <= pi/4 (Payne and Hanek).
4927 *
4928 * Subtracting multiples of a stored pi/2, as reduce_half_pi() does, needs the multiple n as an
4929 * integer and pi/2 to as many bits as n has plus the 226 the residual keeps - out of reach once
4930 * n runs to thousands of bits. Here x * 2/pi is formed instead, in integer arithmetic, from the
4931 * 113 bit mantissa and a 384 bit window of the binary expansion of 2/pi chosen by the exponent.
4932 * The bits of 2/pi above the window only add multiples of four to the product, which leave the
4933 * quadrant where it is; the bits below it only reach past the fraction the window keeps.
4934 *
4935 * That fraction has 380 bits or more, which leaves 226 significant ones even when x is closer
4936 * to a multiple of pi/2 than any binary128 argument can be: for a random argument the fraction
4937 * leads with about as many zero bits as the logarithm of the count of binary128 values, 127.
4938 * Rounded to the nearest quadrant and multiplied by pi/2, it becomes the residual.
4939 *
4940 * Before this existed sin(), cos() and tan() reduced nothing above 2^62, and returned values
4941 * such as 2^3240 for sin(1.5e21). Above 2^321 the series they evaluated never terminated.
4942 *
4943 * @param x Argument, finite and non zero
4944 * @param hi Receives the residual
4945 * @param lo Receives what did not fit in hi
4946 * @return n mod 4, the quadrant.
4947 */
4948 FP128_INLINE static int32_t reduce_large(const float128& x, float128& hi, float128& lo) noexcept
4949 {
4950 constexpr float128 half_pi_hi(0x8469898CC51701B8, 0x921FB54442D1, 0x3FFF, 0);
4951 constexpr float128 half_pi_mid(0xA67CC74020BBEA64, 0xCD129024E088, 0x3F8C, 0);
4952 constexpr int32_t window_words = 6;
4953 constexpr int32_t window_bits = window_words * 64;
4954 constexpr int32_t product_words = window_words + 2;
4955
4956 uint64_t ml = 0, mh = 0;
4957 int32_t e = 0;
4958 uint32_t sign = 0;
4959 x.get_components(ml, mh, e, sign);
4960
4961 // |x| = m * 2^(e-112) and bit i of 2/pi is worth 2^-i, so bit i times m lands on 2^(e-112-i).
4962 // The window starts at the bit that lands on 2^1; the ones above it are multiples of four.
4963 const int32_t first = (e - 113 > 1) ? (e - 113) : 1;
4964 const int32_t frac_bits = (first + window_bits - 1) - (e - FRAC_BITS);
4965
4966 // The window, least significant word first.
4967 uint64_t window[window_words] {};
4968 const int32_t word = (first - 1) >> 6;
4969 const int32_t bit = (first - 1) & 63;
4970 for (int32_t k = 0; k < window_words; ++k) {
4971 const uint64_t w0 = detail::two_over_pi_bits[word + k];
4972 const uint64_t w1 = detail::two_over_pi_bits[word + k + 1];
4973 window[window_words - 1 - k] = (bit == 0) ? w0 : ((w0 << bit) | (w1 >> (64 - bit)));
4974 }
4975
4976 // The product of the mantissa and the window, scaled by 2^frac_bits.
4977 uint64_t p[product_words] {};
4978 const uint64_t m[2] = {ml, mh};
4979 for (int32_t i = 0; i < 2; ++i) {
4980 uint64_t carry = 0;
4981 for (int32_t j = 0; j < window_words; ++j) {
4982 uint64_t high_word = 0;
4983 uint64_t low_word = mulx_u64(m[i], window[j], &high_word);
4984 uint8_t c = addcarryx_u64(0, low_word, carry, &low_word);
4985 high_word += c;
4986 c = addcarryx_u64(0, p[i + j], low_word, &p[i + j]);
4987 carry = high_word + c;
4988 }
4989 p[i + window_words] = carry;
4990 }
4991
4992 // frac_bits is at most 436 for the exponents that reach here, inside the 512 bits of p; the
4993 // bound keeps that true for any argument.
4994 const auto bit_at = [&p](int32_t index) {
4995 return ((index >> 6) < product_words) ? static_cast<uint32_t>((p[index >> 6] >> (index & 63)) & 1) : 0u;
4996 };
4997 uint32_t quadrant = bit_at(frac_bits) | (bit_at(frac_bits + 1) << 1);
4998
4999 // Keep the fraction only.
5000 for (int32_t i = 0; i < product_words; ++i) {
5001 const int32_t lowest = i * 64;
5002 if (lowest >= frac_bits)
5003 p[i] = 0;
5004 else if (lowest + 64 > frac_bits)
5005 p[i] &= FP128_MAX_VALUE_64(frac_bits - lowest);
5006 }
5007
5008 // A fraction of one half or more belongs to the next quadrant, as a negative residual.
5009 const bool negative = bit_at(frac_bits - 1) != 0;
5010 if (negative) {
5011 ++quadrant;
5012 uint8_t borrow = 0;
5013 for (int32_t i = 0; i < product_words; ++i)
5014 borrow = subborrow_u64(borrow, 0, p[i], &p[i]);
5015 for (int32_t i = 0; i < product_words; ++i) {
5016 const int32_t lowest = i * 64;
5017 if (lowest >= frac_bits)
5018 p[i] = 0;
5019 else if (lowest + 64 > frac_bits)
5020 p[i] &= FP128_MAX_VALUE_64(frac_bits - lowest);
5021 }
5022 }
5023
5024 int32_t msb = -1;
5025 for (int32_t i = product_words - 1; i >= 0 && msb < 0; --i) {
5026 if (p[i] != 0)
5027 msb = i * 64 + 63 - static_cast<int32_t>(lzcnt64(p[i]));
5028 }
5029
5030 hi = float128();
5031 lo = float128();
5032 if (msb >= 0) {
5033 // 128 bits of the fraction starting at bit pos, zeros below bit 0.
5034 const auto extract = [&p](int32_t pos, uint64_t& l, uint64_t& h) {
5035 const int32_t from = (pos > 0) ? pos : 0;
5036 const int32_t w = from >> 6;
5037 const int32_t b = from & 63;
5038 const uint64_t p0 = (w < product_words) ? p[w] : 0;
5039 const uint64_t p1 = (w + 1 < product_words) ? p[w + 1] : 0;
5040 const uint64_t p2 = (w + 2 < product_words) ? p[w + 2] : 0;
5041 l = (b == 0) ? p0 : ((p0 >> b) | (p1 << (64 - b)));
5042 h = (b == 0) ? p1 : ((p1 >> b) | (p2 << (64 - b)));
5043 if (pos < 0)
5044 shift_left128_inplace_safe(l, h, -pos);
5045 h &= MAX_SIG_HIGH; // 113 bits
5046 };
5047
5048 // The top 113 bits of the fraction and the 113 below them, both exact.
5049 uint64_t l = 0, h = 0;
5050 extract(msb - FRAC_BITS, l, h);
5051 float128 f_hi;
5052 f_hi.set_components(l, h, msb - frac_bits, 0);
5053 extract(msb - 2 * FRAC_BITS - 1, l, h);
5054 const float128 f_lo = norm_round_pack(0, msb - FRAC_BITS - 1 - frac_bits, l, h, false);
5055
5056 // r = f * pi/2, with the error of the leading product recovered exactly.
5057 const float128 product = f_hi * half_pi_hi;
5058 const float128 product_err = fma(f_hi, half_pi_hi, -product);
5059 quick_two_sum(product, product_err + (f_hi * half_pi_mid + f_lo * half_pi_hi), hi, lo);
5060 if (negative) {
5061 hi = -hi;
5062 lo = -lo;
5063 }
5064 }
5065
5066 // sin and cos of -x follow from the reduction of x mirrored.
5067 if (sign != 0) {
5068 hi = -hi;
5069 lo = -lo;
5070 quadrant = 0u - quadrant;
5071 }
5072 return static_cast<int32_t>(quadrant & 3);
5073 }
5074
5075 /**
5076 * @brief Reduces x to [-pi/4, pi/4], as an unevaluated sum, and returns the quadrant.
5077 * @param x Argument, finite
5078 * @param hi Receives the residual
5079 * @param lo Receives what did not fit in hi
5080 * @return n mod 4, where x = n * pi/2 + hi + lo.
5081 */
5082 FP128_INLINE static int32_t reduce_trig(const float128& x, float128& hi, float128& lo) noexcept
5083 {
5084 // Up to 2^60 the multiple fits the integer reduce_half_pi() counts with, and its 342 bits
5085 // of pi/2 leave the residual 226 good bits. Beyond that the multiple is formed in integer
5086 // arithmetic instead.
5087 if (x.get_exponent() < 60) {
5088 const int64_t n = quadrant_of(x);
5089 reduce_half_pi(x, n, hi, lo);
5090 return static_cast<int32_t>(n & 3);
5091 }
5092 return reduce_large(x, hi, lo);
5093 }
5094
5095 /**
5096 * @brief Subtracts n*(pi/2) from x, leaving the residual as an unevaluated sum.
5097 *
5098 * pi/2 is irrational, so no single float128 multiple of it can be subtracted without leaving
5099 * an error of n ulp behind - and the sine of the residual is only as accurate as the residual
5100 * itself. Where the answer is small, which is exactly where an argument lands near a multiple
5101 * of pi/2, that error is the whole answer: sin() used to return a value with 55 correct bits
5102 * for an argument a few ulp away from pi.
5103 *
5104 * Two things fix it. pi/2 is carried in three pieces covering 342 bits rather than 113, and
5105 * each product n*piece is split into its rounded value and its exact error with fma(), so no
5106 * multiplication is lost either. The residual accumulates as a pair, giving it 226 bits.
5107 *
5108 * @param x Argument
5109 * @param n Multiple of pi/2 to remove
5110 * @param hi Receives the residual
5111 * @param lo Receives what did not fit in hi
5112 */
5113 FP128_INLINE static void reduce_half_pi(const float128& x, int64_t n, float128& hi, float128& lo) noexcept
5114 {
5115 constexpr float128 half_pi_parts[3] = {
5116 float128(0x8469898CC51701B8, 0x921FB54442D1, 0x3FFF, 0),
5117 float128(0xA67CC74020BBEA64, 0xCD129024E088, 0x3F8C, 0),
5118 float128(0xE19C72FEC8841ABA, 0x3B19376BAD7D, 0x3F1A, 1),
5119 };
5120
5121 hi = x;
5122 lo = float128();
5123 if (n == 0)
5124 return;
5125
5126 const float128 nf(n);
5127 for (const float128& part : half_pi_parts) {
5128 // n * part is exactly product + product_err
5129 const float128 product = nf * part;
5130 const float128 product_err = fma(nf, part, -product);
5131
5132 float128 sum, err;
5133 two_sum(hi, -product, sum, err);
5134 // Everything that did not fit is collected and folded back in, which keeps the pair
5135 // normalized for the next piece.
5136 quick_two_sum(sum, (err + lo) - product_err, hi, lo);
5137 }
5138 }
5139
5140 [[nodiscard]] friend float128 sin(float128 x) noexcept
5141 {
5142 if (x.is_nan())
5143 return propagate_nan(x);
5144 if (x.is_zero())
5145 return x;
5146 if (x.is_inf())
5147 return invalid_operation();
5148 // From here on only the flags the result justifies reach the caller.
5149 detail::flag_filter filter;
5150
5151 float128 hi, lo;
5152 const int32_t n = reduce_trig(x, hi, lo);
5153
5154 switch (n) {
5155 case 0: // [-45-45) degrees
5156 return filter(sin1(hi) + cos1(hi) * lo);
5157 case 1: // [45-135) degrees
5158 return filter(cos1(hi) - sin1(hi) * lo);
5159 case 2: // [135-225) degrees
5160 return filter(-(sin1(hi) + cos1(hi) * lo));
5161 case 3: // [225-315) degrees
5162 default:
5163 return filter(-(cos1(hi) - sin1(hi) * lo));
5164 }
5165 }
5166 /**
5167 * @brief Calculate the inverse sine function
5168 *
5169 * asin(x) = atan(x / sqrt((1-x)(1+x))). The Newton iteration on sin() this replaced divided by
5170 * cos(), the derivative, which vanishes at the ends of the domain: it converged slowly there,
5171 * to about 58 correct bits at asin(1). Near the ends 1-x is exact, so the argument of atan()
5172 * keeps its accuracy however close to one x gets.
5173 *
5174 * @param x value in the range [-1,1]
5175 * @return Inverse sine of x. Outside the domain the result is a NaN, the invalid operation.
5176 */
5177 [[nodiscard]] friend float128 asin(float128 x) noexcept
5178 {
5179 if (x.is_nan())
5180 return propagate_nan(x);
5181 const float128 one_value = float128::one();
5182 const float128 a = fabs(x);
5183 if (a > one_value)
5184 return invalid_operation();
5185 if (x.is_zero())
5186 return x;
5187 // From here on only the flags the result justifies reach the caller.
5188 detail::flag_filter filter;
5189
5190 float128 res;
5191 if (a == one_value)
5192 res = float128::half_pi();
5193 else if (a < ldexp(one_value, -57)) {
5194 res = a; // the cubic term is below half an ulp
5195 detail::raise_flags(FE_INEXACT);
5196 }
5197 else
5198 res = atan(a / sqrt((one_value - a) * (one_value + a)));
5199
5200 res.set_sign(x.get_sign());
5201 return filter(res);
5202 }
5203 /**
5204 * @brief Calculate the cosine function
5205 * Ultimately uses sin1() with a reduced range of [-pi/4, pi/4]
5206 * Sine's Maclaurin series converges faster than Cosine's.
5207 * @param x value in Radians
5208 * @return Cosine of x
5209 */
5210 [[nodiscard]] friend float128 cos(float128 x) noexcept
5211 {
5212 if (x.is_nan())
5213 return propagate_nan(x);
5214 if (x.is_inf())
5215 return invalid_operation();
5216 // From here on only the flags the result justifies reach the caller.
5217 detail::flag_filter filter;
5218
5219 float128 hi, lo;
5220 const int32_t n = reduce_trig(x, hi, lo);
5221
5222 switch (n) {
5223 case 0: // [-45-45) degrees
5224 return filter(cos1(hi) - sin1(hi) * lo);
5225 case 1: // [45-135) degrees
5226 return filter(-(sin1(hi) + cos1(hi) * lo));
5227 case 2: // [135-225) degrees
5228 return filter(-(cos1(hi) - sin1(hi) * lo));
5229 case 3: // [225-315) degrees
5230 default:
5231 return filter(sin1(hi) + cos1(hi) * lo);
5232 }
5233 }
5234 /**
5235 * @brief Calculate the inverse cosine function
5236 *
5237 * acos(x) = 2 * atan(sqrt((1-x)/(1+x))). The Newton iteration this replaced divided by sin(),
5238 * which is zero at acos(1): that returned a NaN, and so did acos(1 - 2^-100). Near x = 1 the
5239 * difference 1-x is exact, and near x = -1 the sum 1+x is, so the quotient keeps its accuracy
5240 * at both ends.
5241 *
5242 * @param x value in the range [-1,1]
5243 * @return Inverse cosine of x. Outside the domain the result is a NaN, the invalid operation.
5244 */
5245 [[nodiscard]] friend float128 acos(float128 x) noexcept
5246 {
5247 if (x.is_nan())
5248 return propagate_nan(x);
5249 const float128 one_value = float128::one();
5250 if (fabs(x) > one_value)
5251 return invalid_operation();
5252 if (x == one_value)
5253 return float128();
5254 if (x == -one_value)
5255 return float128::pi();
5256 // From here on only the flags the result justifies reach the caller.
5257 detail::flag_filter filter;
5258
5259 return filter(atan(sqrt((one_value - x) / (one_value + x))) << 1);
5260 }
5261 /**
5262 * @brief Calculate the tangent function
5263 * tan(x) = sin(x)/cos(x)
5264 * @param x value
5265 * @return Tangent of x
5266 */
5267 [[nodiscard]] friend FP128_FORCE_INLINE float128 tan(float128 x) noexcept { return sin(x) / cos(x); }
5268 /**
5269 * @brief Calculate the inverse tangent function
5270 * @param x value
5271 * @return Arctangent of x
5272 */
5273 [[nodiscard]] friend float128 atan(float128 x) noexcept
5274 {
5275 if (x.is_nan())
5276 return propagate_nan(x);
5277 if (x.is_zero())
5278 return x;
5279 // From here on only the flags the result justifies reach the caller.
5280 detail::flag_filter filter;
5281
5282 // constants for segmentation
5283 constexpr float128 half_pi = float128::half_pi(); // pi / 2
5284 bool comp = false;
5285 constexpr int max_iterations = 6;
5286
5287 // make argument positive, save the sign
5288 auto sign = x.get_sign();
5289 x.set_sign(0);
5290
5291 // atan(1) is pi/4, which quarter_pi() holds correctly rounded. The Newton iteration below
5292 // settles wherever the rounding of its sine and cosine leaves it, an ulp either side, and
5293 // acos(0) = 2 atan(1) and atan2(y, y) inherit that.
5294 if (x == float128::one()) {
5296 res.set_sign(sign);
5297 return filter.inexact(res);
5298 }
5299
5300 // limit argument to 0..1. x is greater than one here, so the division cannot be by zero.
5301 if (x > 1) {
5302 comp = true;
5303 x = one() / x;
5304 }
5305
5306 // initial step uses the CRT function.
5307 float128 res = ::atan(static_cast<double>(x));
5308 const float128 eps = fabs(res >> 110);
5309
5310 //
5311 // Xn+1 = Xn - cos(Xn) * ( sin(Xn) - a * cos(Xn))
5312 //
5313 // where 'a' is the argument, each iteration will converge on the result if the initial
5314 // estimate is close enough.
5315 for (int i = 0; i < max_iterations; ++i) {
5316 float128 cos_xn = cos(res);
5317 float128 sin_xn = sin(res);
5318 float128 e = cos_xn * (sin_xn - x * cos_xn); // this is the iteration estimated error
5319 res -= e;
5320 if (fabs(e) <= eps)
5321 break;
5322 }
5323
5324 // restore complement if needed
5325 if (comp)
5326 res = half_pi - res;
5327 // restore sign if needed
5328 res.set_sign(sign);
5329 return filter(res);
5330 }
5331 /**
5332 * @brief Calculate the inverse tangent function of the ratio y / x
5333 * @param y value
5334 * @param x value
5335 * @return Arctangent of y / x in the range [-pi, pi]. The zeros and infinities follow
5336 * IEEE 754-2008 9.2.1: the sign of a zero y is kept, a negative x (-0 included) puts
5337 * the result at +-pi, and two infinities give +-pi/4 or +-3pi/4.
5338 */
5339 [[nodiscard]] friend float128 atan2(float128 y, float128 x) noexcept
5340 {
5341 // constants for segmentation
5342 constexpr float128 pi = float128::pi();
5343 constexpr float128 half_pi = float128::half_pi(); // pi / 2
5344 constexpr float128 three_quarter_pi(0x234F272993D1414A, 0x2D97C7F3321D, 0x4000, 0);
5345
5346 if (x.is_nan() || y.is_nan())
5347 return propagate_nan(y, x);
5348
5349 // The zeros and the infinities. Each result takes the sign of y, a zero y included; the
5350 // previous code returned pi for atan2(0, 1) and lost the sign of every zero.
5351 float128 res;
5352 if (y.is_zero() || x.is_zero() || y.is_inf() || x.is_inf()) {
5353 if (y.is_zero())
5354 res = x.is_negative() ? pi : float128(); // on the axis, the left half including -0
5355 else if (y.is_inf())
5356 res = x.is_inf() ? (x.is_negative() ? three_quarter_pi : float128::quarter_pi()) : half_pi;
5357 else if (x.is_zero())
5358 res = half_pi;
5359 else
5360 res = x.is_negative() ? pi : float128(); // y finite, x infinite
5361 res.set_sign(y.get_sign());
5362 return res;
5363 }
5364 // From here on only the flags the result justifies reach the caller.
5365 detail::flag_filter filter;
5366
5367 // save the signs of x, y
5368 bool comp = fabs(y) > fabs(x);
5369 float128 ratio;
5370
5371 // calculate the ratio keeping it below 1.0
5372 ratio = (comp) ? x / y : y / x;
5373 res = atan(ratio);
5374
5375 if (comp)
5376 res = (res.is_negative()) ? -half_pi - res : half_pi - res;
5377
5378 if (x > 0)
5379 return filter(res);
5380
5381 // x < 0
5382 return filter((y < 0) ? res - pi : res + pi);
5383 }
5384 /**
5385 * @brief Calculate the hyperbolic sine function
5386 * Use the exponent function which produces more accurate results than the power series.
5387 * e^x - e^(-x)
5388 * sinh(x) = ------------
5389 * 2
5390 * @param x value
5391 * @return Sine of x
5392 */
5393 [[nodiscard]] friend FP128_INLINE float128 sinh(const float128 x) noexcept
5394 {
5395 if (x.is_nan())
5396 return propagate_nan(x);
5397 if (x.is_inf() || x.is_zero())
5398 return x;
5399 // From here on only the flags the result justifies reach the caller.
5400 detail::flag_filter filter;
5401
5402 const float128 a = fabs(x);
5403 float128 res;
5404 // Below one, exp(a) and exp(-a) agree to within a factor of e and their difference cancels
5405 // away most of the mantissa - at a = 2^-60 all of it. expm1() holds the same quantity with
5406 // no cancellation at all, and t/(t+1) is exp(-a)-1 expressed through it.
5407 if (a < float128::one()) {
5408 const float128 t = expm1(a);
5409 res = (t + t / (t + float128::one())) >> 1;
5410 } else if (a < float128(11350)) {
5411 res = (exp(a) - exp(-a)) >> 1;
5412 } else {
5413 // exp(a) overflows before sinh(a), which is half of it, does. Squaring exp(a/2) reaches
5414 // the same value without the intermediate overflow; exp(-a) is far below its last place.
5415 const float128 half_power = exp(a >> 1);
5416 res = half_power * (half_power >> 1);
5417 }
5418
5419 return filter((x.is_negative()) ? -res : res);
5420 }
5421 /**
5422 * @brief Calculates the inverse hyperbolic sine
5423 * For positive x:
5424 * asinh(x) = log(x + sqrt(x^2 + 1))
5425 * For negative x, the function returns the result with the sign inverted
5426 * @param x value
5427 * @return Inverse hyperbolic sine of x
5428 */
5429 [[nodiscard]] friend FP128_INLINE float128 asinh(const float128 x) noexcept
5430 {
5431 if (x.is_nan())
5432 return propagate_nan(x);
5433 if (x.is_inf() || x.is_zero())
5434 return x;
5435 // From here on only the flags the result justifies reach the caller.
5436 detail::flag_filter filter;
5437
5438 const float128 one_value = float128::one();
5439 const float128 a = fabs(x);
5440 float128 res;
5441
5442 // Three regimes, because the closed form is only usable in the middle one.
5443 //
5444 // Below 2^-57 the answer is the argument to within half an ulp, and the closed form would
5445 // square it to zero and hand back log(1) = 0 instead.
5446 //
5447 // Above 2^57 the square overflows long before the argument does, and asinh(a) is log(2a)
5448 // to well past the last bit.
5449 //
5450 // In between, adding a to sqrt(a*a+1) cancels for a negative argument, which is why the
5451 // sign is taken out first, and the a*a/(1+sqrt(1+a*a)) form is used rather than
5452 // sqrt(a*a+1)-a: near zero the latter subtracts two values that agree to every bit the
5453 // result needs.
5454 if (a < ldexp(one_value, -57)) {
5455 res = a;
5456 detail::raise_flags(FE_INEXACT); // asinh(a) is a hair below a, not equal to it
5457 } else if (a > ldexp(one_value, 57)) {
5458 res = log(a) + float128::ln2();
5459 } else {
5460 const float128 a2 = sqr(a);
5461 res = log1p(a + a2 / (one_value + sqrt(one_value + a2)));
5462 }
5463
5464 return filter((x.is_positive()) ? res : -res);
5465 }
5466 /**
5467 * @brief Calculate the hyperbolic cosine function over a limited range [-0.5pi, 0.5pi]
5468 * e^x + e^(-x)
5469 * cosh(x) = ------------
5470 * 2
5471 * @param x value in Radians in the range [-0.5pi, 0.5pi]
5472 * @return Sine of x
5473 */
5474 [[nodiscard]] friend FP128_INLINE float128 cosh(const float128 x) noexcept
5475 {
5476 if (x.is_nan())
5477 return propagate_nan(x);
5478 const float128 a = fabs(x);
5479 if (a.is_inf())
5480 return a;
5481 // From here on only the flags the result justifies reach the caller.
5482 detail::flag_filter filter;
5483 // As in sinh(): exp(a) overflows a little before cosh(a) = exp(a)/2 does.
5484 if (a > float128(11350)) {
5485 const float128 half_power = exp(a >> 1);
5486 return filter(half_power * (half_power >> 1));
5487 }
5488 return filter((exp(a) + exp(-a)) >> 1);
5489 }
5490 /**
5491 * @brief Calculates the inverse hyperbolic cosine
5492 * For x >= 1:
5493 * acosh(x) = log(x + sqrt(x^2 - 1))
5494 * For x < 1, the function return zero
5495 * @param x value in the range [1, inf]
5496 * @return Inverse hyperbolic cosine of x
5497 */
5498 [[nodiscard]] friend FP128_INLINE float128 acosh(const float128 x) noexcept
5499 {
5500 if (x.is_nan())
5501 return propagate_nan(x);
5502 // Outside the domain the result is undefined rather than zero, which is what the previous
5503 // version returned for every argument below one.
5504 const float128 one_value = float128::one();
5505 if (x < one_value)
5506 return invalid_operation();
5507 if (x.is_inf())
5508 return x;
5509 // From here on only the flags the result justifies reach the caller.
5510 detail::flag_filter filter;
5511
5512 // Near one, x*x-1 cancels: at x = 1+2^-100 the square rounds back to one and the root
5513 // comes out zero. The argument of log1p below is built from t = x-1, which is exact over
5514 // that range, so the answer keeps its significant bits.
5515 if (x < float128(2)) {
5516 const float128 t = x - one_value;
5517 return filter(log1p(t + sqrt((t << 1) + sqr(t))));
5518 }
5519 // Beyond 2^57 the square overflows before the argument does and acosh(x) is log(2x).
5520 if (x > ldexp(one_value, 57))
5521 return filter(log(x) + float128::ln2());
5522
5523 return filter(log(x + sqrt(sqr(x) - one_value)));
5524 }
5525 /**
5526 * @brief Calculates the hyperbolic tangent
5527 * e^x - e^(-x)
5528 * tanh(x) = ------------
5529 * e^x + e^(-x)
5530 * @param x value
5531 * @return hyperbolic tangent of x
5532 */
5533 [[nodiscard]] friend FP128_INLINE float128 tanh(const float128 x) noexcept
5534 {
5535 if (x.is_nan())
5536 return propagate_nan(x);
5537 if (x.is_zero())
5538 return x;
5539 // From here on only the flags the result justifies reach the caller.
5540 detail::flag_filter filter;
5541
5542 const float128 a = fabs(x);
5543 float128 res;
5544 // Past 40 the two exponentials differ by more than the mantissa can express and the
5545 // quotient is one to the last bit.
5546 if (x.is_inf() || a > float128(40)) {
5547 res = float128::one();
5548 } else {
5549 // e^x - e^(-x) e^(2x) - 1
5550 // tanh(x) = ------------ = ----------------
5551 // e^x + e^(-x) (e^(2x) - 1) + 2
5552 //
5553 // The right hand form is written in terms of expm1, which holds e^(2x)-1 without the
5554 // cancellation that subtracting the two exponentials suffers for a small argument.
5555 const float128 t = expm1(a << 1);
5556 res = t / (t + float128(2));
5557 }
5558
5559 return filter((x.is_negative()) ? -res : res);
5560 }
5561 /**
5562 * @brief Calculates the inverse hyperbolic tangent
5563 * 1 + x
5564 * atanh(x) = 0.5 * log( -----)
5565 * 1 - x
5566 * @param x value in the range (-1, 1)
5567 * @return Inverse hyperbolic tangent of x
5568 */
5569 [[nodiscard]] friend FP128_INLINE float128 atanh(const float128 x) noexcept
5570 {
5571 if (x.is_nan())
5572 return propagate_nan(x);
5573 if (x.is_zero())
5574 return x;
5575
5576 constexpr auto one_value = float128::one();
5577 const float128 a = fabs(x);
5578 // The endpoints are poles and outside them the function is undefined. Returning zero for
5579 // all three, as this used to, gave atanh(1) a finite value and atanh(2) a defined one.
5580 if (a > one_value)
5581 return invalid_operation();
5582 if (a == one_value) {
5583 detail::raise_flags(FE_DIVBYZERO);
5584 return x.is_negative() ? -inf() : inf();
5585 }
5586 // From here on only the flags the result justifies reach the caller.
5587 detail::flag_filter filter;
5588
5589 // 2*atanh(a) = log1p(2a/(1-a)). Splitting the argument as below keeps the numerator from
5590 // rounding away for a small a, where the answer is proportional to it: the previous form,
5591 // log((1+x)/(1-x)), formed a quotient that rounds to exactly one and then took its
5592 // logarithm, which is zero.
5593 float128 res;
5594 if (a < float128::half())
5595 res = log1p((a << 1) + (sqr(a) << 1) / (one_value - a)) >> 1;
5596 else
5597 res = log1p((a << 1) / (one_value - a)) >> 1;
5598
5599 return filter((x.is_negative()) ? -res : res);
5600 }
5601 /**
5602 * @brief Calculates the Maclaurin series constants for the erf function.
5603 * The array will hold 1 / (n! * (2n + 1))
5604 * @param a pointer to array that receives the results. The array must be preallocated.
5605 * @param count Element count in the array
5606 */
5607 friend void erf_constants(float128* a, int32_t count)
5608 {
5609 if (a == nullptr)
5610 return;
5611
5612 a[0] = 1;
5613 float128 f = 1; // value of 0!
5614 for (int32_t i = 1; i < count; ++i) {
5615 f *= i;
5616 a[i] = float128::one() / (f * (2 * i + 1));
5617 }
5618 }
5619 /**
5620 * @brief Computes the error function of a value.
5621 * The erf function return a value in the range -1.0 to 1.0.
5622 * There's no error return.
5623 * @param x A floating-point value.
5624 * @return The erf functions return the Gauss error function of x.
5625 */
5626 [[nodiscard]] friend FP128_INLINE float128 erf(float128 x) noexcept
5627 {
5628 if (x.is_nan())
5629 return propagate_nan(x);
5630 if (x.is_zero())
5631 return x;
5632 // From here on only the flags the result justifies reach the caller.
5633 detail::flag_filter filter;
5634
5635 const uint32_t sign = x.get_sign();
5636 const float128 a = fabs(x);
5637 float128 res;
5638
5639 // erfc(9) is 4.1e-37, which is below half the last place of one, so erf is one from here
5640 // on and the series need never be run outside the range it converges quickly over.
5641 if (x.is_inf() || a >= float128(9)) {
5642 res = float128::one();
5643 } else {
5644 // 2 n
5645 // 2x -x inf (2x^2)
5646 // erf(x) = ------ * e * sum ------------------
5647 // sqrt(pi) n=0 1*3*5*...*(2n+1)
5648 //
5649 // Every term of this series is positive, unlike the Maclaurin series in x^(2n+1) that
5650 // this replaced: that one alternates, and its terms peak around n = x^2 at a value
5651 // 2^24 times the sum by the time x reaches 4, so the answer was formed by cancelling
5652 // away 24 bits of it. Past x = 2 the old code did not use a series at all - it called
5653 // the CRT's double erf and returned 53 correct bits.
5654 const float128 xx = sqr(a);
5655 // The square rounds, and exp() magnifies that by x^2, which reaches 81 here. Keeping
5656 // the exact error of the multiply and applying it as a factor puts those bits back.
5657 const float128 xx_err = fma(a, a, -xx);
5658 const float128 two_xx = xx << 1;
5659
5660 // The sum runs to eighty terms near the top of the range and every one of them rounds
5661 // against a running total, which alone would cost the answer seven bits. two_sum()
5662 // hands back what each addition lost, so it can be carried and added in at the end.
5663 float128 term = float128::one();
5664 float128 sum = term;
5665 float128 lost;
5666 for (int32_t n = 1; n < 1024; ++n) {
5667 term = term * two_xx / float128(2 * n + 1);
5668 float128 rounded, err;
5669 two_sum(sum, term, rounded, err);
5670 sum = rounded;
5671 lost += err;
5672 if (term.get_exponent() + FRAC_BITS + 8 < sum.get_exponent())
5673 break;
5674 }
5675 sum += lost;
5676
5677 const float128 gaussian = exp(-xx) * (float128::one() - xx_err);
5678 res = ((a * sum) << 1) * float128::inv_sqrt_pi() * gaussian;
5679 }
5680
5681 res.set_sign(sign);
5682 return filter(res);
5683 }
5684 /**
5685 * @brief Computes the complementary error function, 1 - erf(x).
5686 *
5687 * Above one the answer is a small difference of two values close to one, so it cannot be
5688 * reached through erf() - at x = 6 the subtraction would leave 55 of the 113 bits, and past
5689 * 13 nothing at all. It is computed directly instead, from Laplace's continued fraction
5690 *
5691 * 2
5692 * -x
5693 * e 1
5694 * erfc(x) = ---------- * ------------------------
5695 * sqrt(pi) x + (1/2)/(x + 1/(x + ...))
5696 *
5697 * evaluated with the modified Lentz algorithm. The fraction converges for every x above one,
5698 * and fastest where the series form is weakest.
5699 *
5700 * Accuracy, measured against mpmath and pinned by tests/float128_accuracy_gtest.cpp: within
5701 * 56 ulp. The worst is just above one, 43 ulp at 1.32, where the fraction converges slowest and
5702 * rounds once per step; from 2 on the error was measured below 28 ulp, and below one, where the
5703 * answer is 1 - erf(x), below 8.
5704 *
5705 * @param x Input value
5706 * @return 1 - erf(x)
5707 */
5708 [[nodiscard]] friend FP128_INLINE float128 erfc(float128 x) noexcept
5709 {
5710 if (x.is_nan())
5711 return propagate_nan(x);
5712 if (x.is_inf())
5713 return x.is_negative() ? float128(2) : float128();
5714 if (x.is_zero())
5715 return float128::one();
5716 // From here on only the flags the result justifies reach the caller.
5717 detail::flag_filter filter;
5718
5719 const float128 one_value = float128::one();
5720 // erfc is symmetric about one: the negative half is where the answer approaches two and
5721 // keeps every bit, so it is the reflection that is well conditioned there.
5722 if (x.is_negative())
5723 return filter(float128(2) - erfc(-x));
5724 if (x < one_value)
5725 return filter(one_value - erf(x));
5726 // exp(-x*x) reaches the smallest subnormal at 106.9
5727 if (x > float128(107))
5728 return filter.inexact(float128());
5729
5730 constexpr int32_t max_iterations = 4096;
5731 const float128 tiny = ldexp(one_value, -16000);
5732 const float128 epsilon = ldexp(one_value, -FRAC_BITS - 8);
5733
5734 float128 f = tiny;
5735 float128 c = f;
5736 float128 d;
5737 for (int32_t n = 1; n < max_iterations; ++n) {
5738 // a_1 is one, every a after it is (n-1)/2
5739 const float128 a = (n == 1) ? one_value : (float128(n - 1) >> 1);
5740
5741 d = x + a * d;
5742 if (d.is_zero())
5743 d = tiny;
5744 c = x + a / c;
5745 if (c.is_zero())
5746 c = tiny;
5747 d = one_value / d;
5748
5749 const float128 delta = c * d;
5750 f *= delta;
5751 if (fabs(delta - one_value) < epsilon)
5752 break;
5753 }
5754
5755 const float128 xx = sqr(x);
5756 const float128 xx_err = fma(x, x, -xx);
5757 const float128 gaussian = exp(-xx) * (one_value - xx_err);
5758 return filter(gaussian * float128::inv_sqrt_pi() * f);
5759 }
5760 /**
5761 * @brief Tests whether x is finite (not infinite and not NaN).
5762 * @param x Input value
5763 * @return Non-zero if finite, zero otherwise.
5764 */
5765 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool isfinite(const float128& x) noexcept { return x.is_finite(); }
5766 /**
5767 * @brief Computes (x * y) + z with a single rounding at the end.
5768 *
5769 * The whole point of a fused multiply add is that the product is not rounded before the
5770 * addend reaches it, which is what makes the result correct to the last bit and what lets a
5771 * caller recover the error of a multiplication as fma(x, y, -x*y). Writing it as x * y + z
5772 * rounds twice and loses everything the addend cancels against.
5773 *
5774 * The exact product of the two 113 bit mantissas is 226 bits, and the addend is another 113.
5775 * Both are placed in a wide accumulator with their leading bits aligned, added or subtracted
5776 * there, and the single rounding is applied when the result is read back out. An operand too
5777 * far below the other one to reach the accumulator cannot change any bit of the result except
5778 * through the tie break, so it is folded into the sticky bit.
5779 *
5780 * @param x The first value to multiply.
5781 * @param y The second value to multiply.
5782 * @param z The value to add to the product.
5783 * @return (x * y) + z, correctly rounded.
5784 */
5785 [[nodiscard]] friend FP128_INLINE constexpr float128 fma(float128 x, float128 y, float128 z) noexcept
5786 {
5787 const uint32_t product_sign = x.get_sign() ^ y.get_sign();
5788
5789 // The product of a zero and an infinity is the invalid operation even when the addend is a
5790 // quiet NaN (IEEE 754-2008 7.2 leaves that case to the implementation; signaling it is what
5791 // x86 does). Otherwise a NaN operand propagates.
5792 if ((x.is_inf() && y.is_zero()) || (y.is_inf() && x.is_zero())) {
5793 if (z.is_nan())
5794 detail::raise_flags(FE_INVALID);
5795 return z.is_nan() ? quiet_nan(z) : invalid_operation();
5796 }
5797 if (x.is_nan() || y.is_nan() || z.is_nan())
5798 return propagate_nan(x, y, z);
5799
5800 // An infinite product decides the result on its own, unless the addend is the opposite
5801 // infinity and the sum is undefined.
5802 if (x.is_inf() || y.is_inf()) {
5803 if (z.is_inf() && z.get_sign() != product_sign)
5804 return invalid_operation();
5805 float128 res = inf();
5806 res.set_sign(product_sign);
5807 return res;
5808 }
5809 if (z.is_inf())
5810 return z;
5811
5812 // A zero product leaves the addend. Two zeros give a zero that is negative only when both
5813 // of them are, or, rounding downward, when either is: the sign rule for an exact zero sum.
5814 if (x.is_zero() || y.is_zero()) {
5815 if (!z.is_zero())
5816 return z;
5817 float128 res;
5818 res.set_sign((z.get_sign() == product_sign) ? product_sign : exact_zero_sign());
5819 return res;
5820 }
5821 // A zero addend leaves the product, which the multiply already rounds correctly.
5822 if (z.is_zero())
5823 return x * y;
5824
5825 uint64_t lx = 0, hx = 0, ly = 0, hy = 0, lz = 0, hz = 0;
5826 int32_t ex = 0, ey = 0, ez = 0;
5827 uint32_t sx = 0, sy = 0, sz = 0;
5828 x.get_components(lx, hx, ex, sx);
5829 y.get_components(ly, hy, ey, sy);
5830 z.get_components(lz, hz, ez, sz);
5831
5832 // The exact 226 bit product of the two 113 bit mantissas. Both were normalized to
5833 // [2^112, 2^113), so the product is in [2^224, 2^226) and its value is
5834 // product * 2^(ex + ey - 224).
5835 uint64_t product[4] {};
5836 mul128to256(lx, hx, ly, hy, product);
5837 const int32_t product_bits = wide_msb(product, 4);
5838
5839 // Weight of the leading bit of each operand, which is what they are aligned by.
5840 const int32_t product_msb = ex + ey - 2 * FRAC_BITS + product_bits;
5841 const int32_t top = (product_msb > ez) ? product_msb : ez;
5842
5843 // Bit WIDE_TOP of an accumulator carries the weight 2^top.
5844 uint64_t product_acc[WIDE_WORDS] {};
5845 uint64_t addend_acc[WIDE_WORDS] {};
5846 const uint64_t addend[2] = {lz, hz};
5847 bool sticky = wide_place(product_acc, product, 4, WIDE_TOP - (top - product_msb) - product_bits);
5848 sticky = wide_place(addend_acc, addend, 2, WIDE_TOP - (top - ez) - FRAC_BITS) || sticky;
5849
5850 // Only the operand with the smaller leading bit can have been placed below the
5851 // accumulator, so a sticky bit always belongs to the smaller of the two.
5852 uint64_t* acc = product_acc;
5853 uint32_t sign = product_sign;
5854 if (product_sign == sz) {
5855 wide_add(product_acc, addend_acc);
5856 } else {
5857 const int32_t cmp = wide_cmp(product_acc, addend_acc);
5858 // Equal accumulators mean equal values: a dropped tail puts its operand more than 157
5859 // bits below the other one, which no accumulator of the larger one can match.
5860 if (cmp == 0)
5861 return float128(0, static_cast<uint64_t>(exact_zero_sign()) << 63);
5862
5863 if (cmp > 0) {
5864 wide_sub(product_acc, addend_acc);
5865 } else {
5866 wide_sub(addend_acc, product_acc);
5867 acc = addend_acc;
5868 sign = sz;
5869 }
5870 // What the subtrahend lost below the accumulator makes the difference smaller by less
5871 // than one of its last places. Borrowing that one place and marking the remainder
5872 // sticky says exactly that.
5873 if (sticky)
5874 wide_dec(acc);
5875 }
5876
5877 const int32_t msb = wide_msb(acc, WIDE_WORDS);
5878 int32_t expo = top - WIDE_TOP + msb;
5879
5880 // Read the 113 bit mantissa out of the accumulator, with the bit below it and whether
5881 // anything below that was set.
5882 uint64_t l = 0, h = 0;
5883 uint64_t guard = 0;
5884 const int32_t lsb = msb - FRAC_BITS;
5885 if (lsb <= 0) {
5886 // Fewer bits survived than the mantissa holds, so the result is exact. Cancellation
5887 // that deep cannot coexist with a dropped tail, which needs the operands far apart.
5888 l = acc[0];
5889 h = acc[1];
5890 shift_left128_inplace_safe(l, h, -lsb);
5891 } else {
5892 const int32_t word = lsb >> 6;
5893 const int32_t bit = lsb & 63;
5894 l = acc[word] >> bit;
5895 h = (word + 1 < WIDE_WORDS) ? (acc[word + 1] >> bit) : 0;
5896 if (bit != 0) {
5897 if (word + 1 < WIDE_WORDS)
5898 l |= acc[word + 1] << (64 - bit);
5899 if (word + 2 < WIDE_WORDS)
5900 h |= acc[word + 2] << (64 - bit);
5901 }
5902 h &= FRAC_UNITY | UPPER_FRAC_MASK;
5903
5904 guard = FP128_GET_BIT(acc[(lsb - 1) >> 6], (lsb - 1) & 63);
5905 for (int32_t i = 0; i < ((lsb - 1) >> 6); ++i)
5906 sticky = sticky || acc[i] != 0;
5907 const int32_t below = (lsb - 1) & 63;
5908 if (below != 0)
5909 sticky = sticky || (acc[(lsb - 1) >> 6] & FP128_MAX_VALUE_64(below)) != 0;
5910 }
5911
5912 // The single rounding, to the final width: a subnormal result keeps fewer than 113 bits, and
5913 // rounding to 113 first would round it twice.
5914 return round_pack(sign, expo, l, h, (guard << 63) | (sticky ? 1 : 0));
5915 }
5916 /**
5917 * @brief Gets the mantissa and exponent of a floating-point number.
5918 * @param x Floating-point value.
5919 * @param expptr Receives the exponent: zero for a zero, an infinity or a NaN.
5920 * @return Mantissa in the [0.5,1) range with the sign of x. A zero or an infinity comes back
5921 * unchanged, a NaN quieted (a signaling one raising invalid, as for every operation).
5922 */
5923 [[nodiscard]] friend FP128_FORCE_INLINE constexpr float128 frexp(float128 x, int* expptr) noexcept
5924 {
5925 if (x.is_nan()) {
5926 *expptr = 0;
5927 return propagate_nan(x);
5928 }
5929 if (x.is_inf() || x.is_zero()) {
5930 *expptr = 0;
5931 return x;
5932 }
5933
5934 uint64_t l, h;
5935 int32_t e;
5936 uint32_t s;
5937 x.get_components(l, h, e, s);
5938 *expptr = e + 1;
5939 float128 res(l, h, EXP_BIAS - 1, s);
5940 return res;
5941 }
5942 /**
5943 * @brief Multiplies a floating-point number by an integral power of two.
5944 * @param x Floating-point value.
5945 * @param exp Integer exponent.
5946 * @return The ldexp functions return the value of x * 2^exp if successful. On overflow, and depending on the sign of x, ldexp returns +/- inf
5947 */
5948 [[nodiscard]] friend FP128_FORCE_INLINE constexpr float128 ldexp(float128 x, int exp) noexcept
5949 {
5950 if (x.is_zero())
5951 return x;
5952 if (x.is_special())
5953 return x.is_nan() ? propagate_nan(x) : x;
5954
5955 // Clamped before it is negated, which INT_MIN cannot be.
5956 if (exp > 0)
5957 return x << ((exp < SCALE_LIMIT) ? exp : SCALE_LIMIT);
5958 return x >> ((exp > -SCALE_LIMIT) ? -exp : SCALE_LIMIT);
5959 }
5960
5961 /**
5962 * @name Classification and comparison
5963 *
5964 * The `<cmath>` predicates. They are functions rather than the macros the C header defines, in
5965 * the same way the standard library's own C++ overloads are, so they take part in overload
5966 * resolution and can be found by argument dependent lookup.
5967 * @{
5968 */
5969
5970 /// @brief True when the sign bit is set, including for -0 and for a negative NaN.
5971 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool signbit(const float128& x) noexcept { return x.get_sign() != 0; }
5972 /// @brief True when x is neither zero, subnormal, infinite nor NaN.
5973 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool isnormal(const float128& x) noexcept { return x.is_normal() && !x.is_zero(); }
5974 /// @brief One of FP_NAN, FP_INFINITE, FP_ZERO, FP_SUBNORMAL or FP_NORMAL.
5975 [[nodiscard]] friend FP128_INLINE constexpr int fpclassify(const float128& x) noexcept
5976 {
5977 if (x.is_nan())
5978 return FP_NAN;
5979 if (x.is_inf())
5980 return FP_INFINITE;
5981 if (x.is_zero())
5982 return FP_ZERO;
5983 return x.is_subnormal() ? FP_SUBNORMAL : FP_NORMAL;
5984 }
5985 /**
5986 * @brief True when either operand is a NaN, so that the two do not compare in any order.
5987 *
5988 * This and the five predicates below are IEEE 754-2008's quiet comparisons (5.11): a quiet NaN
5989 * operand is an ordinary unordered answer, a signaling one is the invalid operation. The
5990 * relational operators are the signaling comparisons instead, which raise invalid for any NaN.
5991 * The five below decide unorderedness through this function, which is where the signal comes from.
5992 */
5993 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool isunordered(const float128& x, const float128& y) noexcept
5994 {
5995 if (x.is_signaling() || y.is_signaling())
5996 detail::raise_flags(FE_INVALID);
5997 return x.is_nan() || y.is_nan();
5998 }
5999 /// @brief x > y, false rather than unordered when either is a NaN.
6000 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool isgreater(const float128& x, const float128& y) noexcept
6001 {
6002 return !isunordered(x, y) && x > y;
6003 }
6004 /// @brief x >= y, false when either is a NaN.
6005 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool isgreaterequal(const float128& x, const float128& y) noexcept
6006 {
6007 return !isunordered(x, y) && x >= y;
6008 }
6009 /// @brief x < y, false when either is a NaN.
6010 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool isless(const float128& x, const float128& y) noexcept
6011 {
6012 return !isunordered(x, y) && x < y;
6013 }
6014 /// @brief x <= y, false when either is a NaN.
6015 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool islessequal(const float128& x, const float128& y) noexcept
6016 {
6017 return !isunordered(x, y) && x <= y;
6018 }
6019 /// @brief x < y or x > y, false when either is a NaN.
6020 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool islessgreater(const float128& x, const float128& y) noexcept
6021 {
6022 return !isunordered(x, y) && (x < y || x > y);
6023 }
6024 /// @}
6025
6026 /**
6027 * @name IEEE 754-2008 operations beyond <cmath>
6028 *
6029 * Operations clause 5 requires that the C library of the time did not name. They are spelled
6030 * the way ISO/IEC TS 18661-1, and after it C23, binds them to C.
6031 * @{
6032 */
6033
6034 /**
6035 * @brief The encoding as a key whose unsigned order is the total order of IEEE 754-2008 5.10.
6036 *
6037 * Positive encodings already ascend with their value, NaNs above infinity and quiet NaNs above
6038 * signaling ones; negative encodings descend. Flipping every bit of a negative encoding and
6039 * only the sign bit of a positive one puts the whole range in one ascending sequence.
6040 */
6041 FP128_FORCE_INLINE constexpr void total_order_key(uint64_t& l, uint64_t& h) const noexcept
6042 {
6043 const uint64_t flip = (get_sign() != 0) ? UINT64_MAX : 0;
6044 l = low ^ flip;
6045 h = high ^ (flip | SIGN_MASK);
6046 }
6047
6048 /**
6049 * @brief totalOrder(x, y): true when x precedes y, or equals it, in the IEEE 754 total order.
6050 *
6051 * The order every value takes part in, NaNs included: -NaN < -inf < negative values < -0 <
6052 * +0 < positive values < +inf < +NaN, a signaling NaN before a quiet one of the same sign, and
6053 * NaNs of the same kind ordered by payload. It never signals, even for a signaling NaN.
6054 *
6055 * @param x First value
6056 * @param y Second value
6057 * @return True when x is ordered before or the same as y.
6058 */
6059 [[nodiscard]] friend FP128_INLINE constexpr bool totalorder(const float128& x, const float128& y) noexcept
6060 {
6061 uint64_t xl = 0, xh = 0, yl = 0, yh = 0;
6062 x.total_order_key(xl, xh);
6063 y.total_order_key(yl, yh);
6064 return (xh != yh) ? (xh < yh) : (xl <= yl);
6065 }
6066 /// @brief totalOrderMag(x, y): totalorder() of the absolute values.
6067 [[nodiscard]] friend FP128_INLINE constexpr bool totalordermag(const float128& x, const float128& y) noexcept
6068 {
6069 return totalorder(fabs(x), fabs(y));
6070 }
6071
6072 /**
6073 * @brief maxNumMag: whichever of x and y has the larger magnitude, or fmax() when they tie.
6074 * @param x First value
6075 * @param y Second value
6076 * @return The larger magnitude. A quiet NaN is treated as missing; a signaling one is the
6077 * invalid operation and gives a quiet NaN.
6078 */
6079 [[nodiscard]] friend FP128_INLINE constexpr float128 fmaxmag(const float128& x, const float128& y) noexcept
6080 {
6081 if (!x.is_nan() && !y.is_nan()) {
6082 const float128 ax = fabs(x), ay = fabs(y);
6083 if (ax > ay)
6084 return x;
6085 if (ay > ax)
6086 return y;
6087 }
6088 return fmax(x, y);
6089 }
6090 /// @brief minNumMag: whichever of x and y has the smaller magnitude, or fmin() when they tie.
6091 /// @copydetails fmaxmag
6092 [[nodiscard]] friend FP128_INLINE constexpr float128 fminmag(const float128& x, const float128& y) noexcept
6093 {
6094 if (!x.is_nan() && !y.is_nan()) {
6095 const float128 ax = fabs(x), ay = fabs(y);
6096 if (ax < ay)
6097 return x;
6098 if (ay < ax)
6099 return y;
6100 }
6101 return fmin(x, y);
6102 }
6103
6104 /// @brief isCanonical: always true, every binary128 encoding is canonical.
6105 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool iscanonical(const float128&) noexcept { return true; }
6106 /// @brief isSignaling: true for a signaling NaN.
6107 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool issignaling(const float128& x) noexcept { return x.is_signaling(); }
6108 /// @brief isSubnormal: true for a subnormal value, which zero is not.
6109 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool issubnormal(const float128& x) noexcept { return x.is_subnormal(); }
6110 /// @brief isZero: true for either zero.
6111 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool iszero(const float128& x) noexcept { return x.is_zero(); }
6112 /// @}
6113
6114 /**
6115 * @brief A quiet NaN carrying the payload spelled out in the argument.
6116 *
6117 * Mirrors the C library's nan(): the string is read as an unsigned integer, decimal by
6118 * default, hexadecimal after an 0x prefix, and its low bits become the NaN's fraction. An
6119 * empty or unparsable string gives the default NaN.
6120 *
6121 * @param payload Digits of the payload, may be empty
6122 * @return A quiet NaN.
6123 */
6124 [[nodiscard]] friend FP128_INLINE float128 nan(const char* payload) noexcept
6125 {
6126 uint64_t bits = 1;
6127 if (payload != nullptr && *payload != '\0') {
6128 const uint64_t parsed = strtoull(payload, nullptr, 0);
6129 // A zero fraction is an infinity rather than a NaN, so the default payload stands in.
6130 if (parsed != 0)
6131 bits = parsed;
6132 }
6133 // The leading fraction bit marks the NaN quiet; the payload fills the bits below it.
6134 float128 res = float128(bits, 0, INF_EXP_BIASED, 0);
6135 res.high |= QUIET_NAN_BIT;
6136 return res;
6137 }
6138
6139 /// @brief True when x is an integer whose last place is one, which is the parity a tie needs.
6140 [[nodiscard]] FP128_INLINE static constexpr bool is_odd_int(const float128& x) noexcept
6141 {
6142 uint64_t l = 0, h = 0;
6143 int32_t expo = 0;
6144 uint32_t sign = 0;
6145 x.get_components(l, h, expo, sign);
6146 // Below one there is no units bit; above 2^112 the last place is two or more, so every
6147 // value that far out is even.
6148 if (expo < 0 || expo > FRAC_BITS)
6149 return false;
6150 const int32_t bit = FRAC_BITS - expo;
6151 return (bit < 64) ? ((l >> bit) & 1) != 0 : ((h >> (bit - 64)) & 1) != 0;
6152 }
6153
6154 /**
6155 * @name Rounding to the current mode
6156 *
6157 * Both round in the current rounding direction, which is to nearest with ties to even unless
6158 * FP128_IEEE_ENV is defined and fesetround() chose another. They differ in one respect:
6159 * rint is IEEE 754's roundToIntegralExact and raises the inexact exception when the result
6160 * differs from its argument, nearbyint never does. round() differs from both: it breaks a tie
6161 * away from zero whatever the rounding direction.
6162 * @{
6163 */
6164 /// @brief x rounded to an integral value in the current direction, raising inexact when that changes it.
6165 [[nodiscard]] friend FP128_INLINE constexpr float128 rint(const float128& x) noexcept
6166 {
6167 return round_integral(x, detail::current_rounding(), false, true);
6168 }
6169 /// @brief x rounded to an integral value in the current direction.
6170 [[nodiscard]] friend FP128_FORCE_INLINE constexpr float128 nearbyint(const float128& x) noexcept
6171 {
6172 return round_integral(x, detail::current_rounding(), false, false);
6173 }
6174 /// @}
6175
6176 /**
6177 * @name Exponent manipulation
6178 * @{
6179 */
6180 /// @brief x * 2^n, the same operation ldexp performs.
6181 [[nodiscard]] friend FP128_FORCE_INLINE constexpr float128 scalbn(const float128& x, int n) noexcept { return ldexp(x, n); }
6182 /// @brief x * 2^n for a long exponent, clamped to what the format can reach.
6183 [[nodiscard]] friend FP128_INLINE constexpr float128 scalbln(const float128& x, long n) noexcept
6184 {
6185 // Anything past the format's range saturates the same way the shift itself would, and
6186 // clamping keeps the conversion to int well defined.
6187 constexpr long limit = SCALE_LIMIT;
6188 const long clamped = (n > limit) ? limit : ((n < -limit) ? -limit : n);
6189 return ldexp(x, static_cast<int>(clamped));
6190 }
6191 /// @}
6192
6193 /**
6194 * @brief The representable value next to x in the direction of y.
6195 *
6196 * A quiet operation, like IEEE 754-2008's nextUp and nextDown that it is built on: stepping
6197 * from the largest finite value to infinity, or into the subnormal range or onto zero, raises
6198 * neither overflow nor underflow (C's Annex F would raise them). Only a signaling NaN operand
6199 * raises an exception, invalid, and is quieted.
6200 *
6201 * @param x Starting value
6202 * @param y Value giving the direction
6203 * @return The neighbour of x towards y, or y itself when the two are equal.
6204 */
6205 [[nodiscard]] friend FP128_INLINE constexpr float128 nextafter(const float128& x, const float128& y) noexcept
6206 {
6207 if (x.is_nan() || y.is_nan())
6208 return propagate_nan(x, y);
6209 if (x == y)
6210 return y; // the sign of y is what the standard hands back here
6211 return (y > x) ? nextUp(x) : nextDown(x);
6212 }
6213 /// @brief The neighbour of x towards y. The same as nextafter: there is no wider type to convert from.
6214 [[nodiscard]] friend FP128_FORCE_INLINE constexpr float128 nexttoward(const float128& x, const float128& y) noexcept
6215 {
6216 return nextafter(x, y);
6217 }
6218
6219 /**
6220 * @brief |x| mod |y|, along with the low bits of the quotient it implies.
6221 *
6222 * The shared engine behind fmod, remainder and remquo. All three are exact operations on the
6223 * mantissas, and all three need the same long division; only what they do with the quotient
6224 * differs.
6225 *
6226 * @param x Dividend, must be finite and non zero
6227 * @param y Divisor, must be finite and non zero
6228 * @param quotient Receives the low bits of the integer quotient
6229 * @param half Receives how twice the remainder compares with |y|: negative, zero or positive.
6230 * remainder() decides on it, and it is decided here, on the integer mantissas, because
6231 * doubling the remainder in floating point overflows once |y| is above half the largest
6232 * finite value.
6233 * @return The remainder, with a positive sign.
6234 */
6235 [[nodiscard]] FP128_INLINE static float128 fmod_magnitude(const float128& x, const float128& y, uint64_t& quotient, int32_t& half) noexcept
6236 {
6237 quotient = 0;
6238
6239 uint64_t lx = 0, hx = 0, ly = 0, hy = 0;
6240 int32_t ex = 0, ey = 0;
6241 uint32_t sx = 0, sy = 0;
6242 x.get_components(lx, hx, ex, sx);
6243 y.get_components(ly, hy, ey, sy);
6244 const uint128_t mx(lx, hx);
6245 const uint128_t mod(ly, hy);
6246
6247 if (ex < ey || (ex == ey && mx < mod)) {
6248 // |x| is the remainder. Both mantissas lead at bit 112, so 2|x| against |y| is mx * 2 on
6249 // the same exponent, mx on the next one up, and smaller still below that.
6250 if (ex + 1 < ey) {
6251 half = -1;
6252 } else {
6253 const uint128_t twice = (ex == ey) ? (mx << 1) : mx;
6254 half = (twice < mod) ? -1 : ((twice == mod) ? 0 : 1);
6255 }
6256 return fabs(x);
6257 }
6258
6259 uint128_t rem = mx;
6260 uint128_t block_quotient = rem / mod;
6261 rem -= block_quotient * mod;
6262 uint64_t low = 0, high = 0;
6263 block_quotient.get_components(low, high);
6264 quotient = low;
6265
6266 int32_t shift = ex - ey;
6267 constexpr int32_t block = 15;
6268 while (shift > 0) {
6269 const int32_t step = (shift < block) ? shift : block;
6270 rem <<= step;
6271 shift -= step;
6272 block_quotient = rem / mod;
6273 rem -= block_quotient * mod;
6274 block_quotient.get_components(low, high);
6275 // Only the low bits of the quotient are ever wanted, so the overflow is dropped.
6276 quotient = (quotient << step) + low;
6277 }
6278
6279 // rem is below mod, which is below 2^113, so doubling it stays within 128 bits.
6280 const uint128_t twice = rem << 1;
6281 half = (twice < mod) ? -1 : ((twice == mod) ? 0 : 1);
6282
6283 if (rem.is_zero())
6284 return float128();
6285
6286 uint64_t rl = 0, rh = 0;
6287 rem.get_components(rl, rh);
6288 const int32_t msb = static_cast<int32_t>(log2(rl, rh));
6289 shift_left128_inplace_safe(rl, rh, FRAC_BITS - msb);
6290
6291 float128 res;
6292 res.set_components(rl, rh, ey - FRAC_BITS + msb, 0);
6293 return res;
6294 }
6295
6296 /**
6297 * @brief IEEE 754 remainder: x - n*y with n the quotient rounded to the nearest even integer.
6298 *
6299 * Unlike fmod, whose result keeps the sign of x, this one lands in [-|y|/2, |y|/2].
6300 *
6301 * @param x Dividend
6302 * @param y Divisor
6303 * @return The remainder.
6304 */
6305 [[nodiscard]] friend FP128_INLINE float128 remainder(const float128& x, const float128& y) noexcept
6306 {
6307 int quotient = 0;
6308 return remquo(x, y, &quotient);
6309 }
6310
6311 /**
6312 * @brief The IEEE remainder together with the low bits of the quotient.
6313 * @param x Dividend
6314 * @param y Divisor
6315 * @param quo Receives at least the low three bits of the quotient, with the sign of x/y
6316 * @return The remainder.
6317 */
6318 [[nodiscard]] friend FP128_INLINE float128 remquo(const float128& x, const float128& y, int* quo) noexcept
6319 {
6320 if (quo != nullptr)
6321 *quo = 0;
6322 if (x.is_nan() || y.is_nan())
6323 return propagate_nan(x, y);
6324 if (x.is_inf() || y.is_zero())
6325 return invalid_operation();
6326 if (y.is_inf() || x.is_zero())
6327 return x;
6328
6329 uint64_t bits = 0;
6330 int32_t half = 0;
6331 const float128 magnitude = fabs(y);
6332 float128 rem = fmod_magnitude(x, y, bits, half);
6333
6334 // fmod leaves the remainder in [0, |y|); the IEEE one is the nearer of that and |y| - it,
6335 // with a tie going to whichever leaves an even quotient. Which is nearer comes from the
6336 // integer mantissas: doubling rem in floating point, as this used to, overflowed for |y|
6337 // above half the largest value, raising overflow for an exact operation and - rounding
6338 // toward zero or downward, where the doubled value stops at the largest one - taking the
6339 // wrong side.
6340 const bool round_up = half > 0 || (half == 0 && (bits & 1) != 0);
6341 if (round_up) {
6342 // rem is at least |y| / 2 here, so the difference is exact (Sterbenz).
6343 rem -= magnitude;
6344 ++bits;
6345 }
6346
6347 if (quo != nullptr) {
6348 // The standard asks for the low bits of the magnitude of the quotient, signed by the
6349 // signs of the operands. Seven bits is the customary amount and fits any int.
6350 const int low_bits = static_cast<int>(bits & 0x7F);
6351 *quo = (x.get_sign() != y.get_sign()) ? -low_bits : low_bits;
6352 }
6353
6354 rem.set_sign(rem.is_zero() ? x.get_sign() : (x.get_sign() ^ rem.get_sign()));
6355 return rem;
6356 }
6357
6358 /**
6359 * @brief Length of the diagonal of a box, computed without an intermediate overflow.
6360 * @param x First side
6361 * @param y Second side
6362 * @param z Third side
6363 * @return sqrt(x*x + y*y + z*z)
6364 */
6365 [[nodiscard]] friend FP128_INLINE float128 hypot(const float128& x, const float128& y, const float128& z) noexcept
6366 {
6367 if (x.is_signaling() || y.is_signaling() || z.is_signaling())
6368 return propagate_nan(x, y, z);
6369 if (x.is_inf() || y.is_inf() || z.is_inf())
6370 return inf();
6371 if (x.is_nan() || y.is_nan() || z.is_nan())
6372 return propagate_nan(x, y, z);
6373
6374 // Scaling by the largest term keeps every square inside the format's range, which squaring
6375 // the values as they came would not: a side above 2^8192 overflows on its own.
6376 const float128 largest = fmax(fabs(x), fmax(fabs(y), fabs(z)));
6377 if (largest.is_zero())
6378 return largest;
6379 // From here on only the flags the result justifies reach the caller.
6380 detail::flag_filter filter;
6381
6382 const int32_t expo = ilogb(largest);
6383 const float128 a = ldexp(x, -expo);
6384 const float128 b = ldexp(y, -expo);
6385 const float128 c = ldexp(z, -expo);
6386 return filter(ldexp(sqrt(sqr(a) + sqr(b) + sqr(c)), expo));
6387 }
6388
6389 /// @brief Terms of the Stirling series lgamma() runs. Sixteen reach 2^-119 for an argument of 32.
6390 static constexpr int32_t STIRLING_TERMS = 16;
6391 /// @brief Terms of the series lgamma_near_two() runs. For |z| <= 1/2 the last is below 2^-120 of the sum.
6392 static constexpr int32_t LGAMMA_NEAR_TWO_TERMS = 58;
6393 /// @brief Below this magnitude lgamma() and tgamma() move the argument next to two by the recurrence.
6394 static constexpr int32_t GAMMA_RECURRENCE_LIMIT = 32;
6395
6396 /**
6397 * @brief lgamma(2 + z) for |z| <= 1/2, accurate relative to the result.
6398 *
6399 * The Taylor series of log(gamma) about 2:
6400 *
6401 * inf k zeta(k) - 1 k
6402 * lgamma(2 + z) = (1 - gamma) z + sum (-1) ----------- z
6403 * k=2 k
6404 *
6405 * zeta(k) - 1 is about 2^-k, so a term is about (z/2)^k / k and 58 of them reach past the last
6406 * bit for |z| <= 1/2. Every term carries a power of z, so the sum is accurate relative to itself
6407 * however close z is to zero - which is what lgamma near its zeros at 1 and 2 needs, and what the
6408 * recurrence and Stirling series it replaced there could not give: they formed the answer as a
6409 * difference of two values near 80, 2^-106 wide in absolute terms, which was 2^28 ulp at
6410 * lgamma(1 + 2^-20) and every bit of lgamma(2 - 2^-100).
6411 *
6412 * The coefficients are the series' own, rounded to binary128 (ties to even) from mpmath at 400
6413 * bits; the first is 1 - gamma, gamma being Euler's constant.
6414 *
6415 * @param z Offset from two, |z| <= 1/2
6416 * @return lgamma(2 + z)
6417 */
6418 [[nodiscard]] FP128_INLINE static float128 lgamma_near_two(const float128& z) noexcept
6419 {
6420 constexpr float128 coefficients[LGAMMA_NEAR_TWO_TERMS] = {
6421 float128(0xE16CB90701FBFAB5ull, 0x3FFDB0EE6072093Cull), // 0.42278434
6422 float128(0x6461CF62448802EBull, 0x3FFD4A34CC4A60FAull), // 0.32246703
6423 float128(0x68125D0741DF7858ull, 0xBFFB13E001A55760ull), // -0.067352301
6424 float128(0x36BF2242232DCA47ull, 0x3FF951322AC7D848ull), // 0.020580808
6425 float128(0x186D6760C385330Eull, 0xBFF7E404FC218F5Full), // -0.007385551
6426 float128(0xFD490FAE70050172ull, 0x3FF67ADD6EADB6C2ull), // 0.0028905103
6427 float128(0x7CEB67C604C626F6ull, 0xBFF538AC5C2BF8E0ull), // -0.0011927539
6428 float128(0x8BE59CA4DDB5A64Dull, 0x3FF40B36AF86396Eull), // 0.00050966952
6429 float128(0x7C70754606688FA5ull, 0xBFF2D3FD4C76D2FCull), // -0.00022315476
6430 float128(0xA33A61354E004CF2ull, 0x3FF1A127B0F17D65ull), // 9.9457513e-5
6431 float128(0xEF2EFD5F190DC2CDull, 0xBFF078DE5BD7C81Eull), // -4.4926237e-5
6432 float128(0x224C0AE964B1EE44ull, 0x3FEF580DCEE66EB0ull), // 2.0507213e-5
6433 float128(0x2856A464E0AB35D5ull, 0xBFEE3CBC963CE224ull), // -9.4394883e-6
6434 float128(0xB901BBAE75609FD8ull, 0x3FED2597A39F34AAull), // 4.3748668e-6
6435 float128(0x11C76B0E65AC639Bull, 0xBFEC11B2EB767954ull), // -2.0392158e-6
6436 float128(0xF3A02AD5FFB78217ull, 0x3FEB0064CDEB22F0ull), // 9.5514121e-7
6437 float128(0xEBB3D4F1868FBE6Bull, 0xBFE9E2600D93CFD2ull), // -4.4924692e-7
6438 float128(0xD7668ADDDDA6D48Full, 0x3FE8C76BBB3F07A4ull), // 2.1207185e-7
6439 float128(0x7657C89FA5B60F88ull, 0xBFE7AF5A6CBBF8A9ull), // -1.0043225e-7
6440 float128(0xF40C9C591CD909EAull, 0x3FE699B93C2070B0ull), // 4.7698102e-8
6441 float128(0xC6CCA00AFB036818ull, 0xBFE5862C734DF3EAull), // -2.2711095e-8
6442 float128(0xCB258B1DCC5155DFull, 0x3FE47469DACCFADCull), // 1.0838659e-8
6443 float128(0xD035EE5DBF0EDF9Aull, 0xBFE36434A8447AEAull), // -5.183475e-9
6444 float128(0x29E2BE683656F13Bull, 0x3FE2555A877FFD2Cull), // 2.4836745e-9
6445 float128(0xE413CDB83A1538F4ull, 0xBFE147B1679258D0ull), // -1.1921401e-9
6446 float128(0xBC50C1202229AE9Aull, 0x3FE03B15D2B2FC10ull), // 5.7313672e-10
6447 float128(0xF97A755322CE1DB6ull, 0xBFDF2F69A9FABE3Dull), // -2.7595229e-10
6448 float128(0xC41820A7091423A3ull, 0x3FDE24932A337434ull), // 1.3304764e-10
6449 float128(0xC53D3AF6D2812D29ull, 0xBFDD1A7C26EC2523ull), // -6.4229646e-11
6450 float128(0x78E3F2CAD8600E57ull, 0x3FDC11116E693ED9ull), // 3.1044248e-11
6451 float128(0x8281DF041B793D4Bull, 0xBFDB08424CBC543Dull), // -1.5021384e-11
6452 float128(0xF4D51A9815322258ull, 0x3FDA000026E3F644ull), // 7.2759745e-12
6453 float128(0xA0BADB5F2A2D6045ull, 0xBFD8F07C514FC9F0ull), // -3.5277425e-12
6454 float128(0x7A755E9E6B1E780Aull, 0x3FD7E1E2026AAFCDull), // 1.7119918e-12
6455 float128(0x1D78ED65B062543Eull, 0xBFD6D41D56E5EE2Eull), // -8.3153858e-13
6456 float128(0x6BFBE2E26CB30374ull, 0x3FD5C71C7F6F10E3ull), // 4.0422005e-13
6457 float128(0xAD6B4BBD43F5EE38ull, 0xBFD4BACF9A27BC89ull), // -1.9664756e-13
6458 float128(0xE281AFE37085970Eull, 0x3FD3AF28718A10D6ull), // 9.5736304e-14
6459 float128(0x5A75058C37B49BF0ull, 0xBFD2A41A45603E5Bull), // -4.664076e-14
6460 float128(0x8B187BC1BEF29131ull, 0x3FD199999C0716EEull), // 2.273737e-14
6461 float128(0x7E625A92BB8E6DFAull, 0xBFD08F9C1A8DF9D7ull), // -1.1091399e-14
6462 float128(0x4CC5056234AEF19Eull, 0x3FCF8618628D2890ull), // 5.4136592e-15
6463 float128(0x05C6EE82DF30CE0Bull, 0xBFCE7D05F4C31C56ull), // -2.64388e-15
6464 float128(0xA674E2F0035C28C7ull, 0x3FCD745D17B56BA4ull), // 1.2918959e-15
6465 float128(0x66BB45CB97243D92ull, 0xBFCC6C16C1B4D645ull), // -6.3159355e-16
6466 float128(0xC887EB79BCA14271ull, 0x3FCB642C85C023D9ull), // 3.0893163e-16
6467 float128(0xC9A37039036FD052ull, 0xBFCA5C9882D825E9ull), // -1.5117931e-16
6468 float128(0x639EB90C92EA148Aull, 0x3FC9555555698A86ull), // 7.4014869e-17
6469 float128(0x8DAE8C46EE149FD0ull, 0xBFC84E5E0A8022BCull), // -3.625218e-17
6470 float128(0xE882E7B3E6F672F6ull, 0x3FC747AE14838081ull), // 1.7763568e-17
6471 float128(0x13C8EE7D4261693Full, 0xBFC641414146E3E3ull), // -8.7076316e-18
6472 float128(0xA0A0E2D83D68A5C6ull, 0x3FC53B13B13EC2F3ull), // 4.2700886e-18
6473 float128(0x94896C42A8F2EC41ull, 0xBFC43521CFB52085ull), // -2.0947604e-18
6474 float128(0x922DAAC30B4BE8C9ull, 0x3FC32F684BDBA6A9ull), // 1.0279843e-18
6475 float128(0x3B3843DA7A1E5BB0ull, 0xBFC229E4129F4967ull), // -5.0464683e-19
6476 float128(0xBBBA2C3DB2CD6133ull, 0x3FC1249249253F4Cull), // 2.4781764e-19
6477 float128(0xB6A6D988E3DBA6D1ull, 0xBFC01F7047DC8348ull), // -1.2173498e-19
6478 float128(0xBB412D63F4093EF5ull, 0x3FBF1A7B9611F1F7ull), // 5.9818051e-20
6479 };
6480 float128 acc = coefficients[LGAMMA_NEAR_TWO_TERMS - 1];
6481 for (int32_t k = LGAMMA_NEAR_TWO_TERMS - 2; k >= 0; --k) {
6482 acc = coefficients[k] + z * acc;
6483 }
6484 return z * acc;
6485 }
6486
6487 /**
6488 * @brief |sin(pi * x)| for a finite x that is not an integer, without the error of rounding pi * x.
6489 *
6490 * The integer part of x only changes the sign, and x - round(x) is exact, so the reduction costs
6491 * nothing. What is left, f in [-1/2, 1/2], is multiplied by pi as an unevaluated sum: the rounded
6492 * product, its exact error from fma(), and the part of pi below the last place of float128::pi().
6493 * sin(pi * f) is then sin(p) + cos(p) * e to well past the last bit. Forming sin(pi() * x)
6494 * instead, as lgamma() did, rounded the argument before reducing it: next to a pole, where the
6495 * sine is as small as x is close to an integer, that rounding was most of the answer.
6496 *
6497 * @param x Finite value, not an integer, below 2^112 in magnitude
6498 * @return |sin(pi * x)|, which is positive.
6499 */
6500 [[nodiscard]] FP128_INLINE static float128 abs_sin_pi(const float128& x) noexcept
6501 {
6502 constexpr float128 pi_low(0xA67CC74020BBEA64ull, 0x3F8DCD129024E088ull); // pi - pi(), from mpmath
6503 const float128 f = x - round(x);
6504 const float128 p = float128::pi() * f;
6505 const float128 e = fma(float128::pi(), f, -p) + pi_low * f;
6506 return fabs(sin(p) + cos(p) * e);
6507 }
6508
6509 /**
6510 * @brief Natural logarithm of the absolute value of the gamma function.
6511 *
6512 * Three regimes:
6513 * - |x| < 32: x = n + z with n = round(x), and the recurrence gamma(x + 1) = x * gamma(x) moves the
6514 * argument to 2 + z, where lgamma_near_two() is accurate relative to its result. Every factor
6515 * the recurrence takes is x moved by an integer towards zero, which is exact, so the answer is
6516 * lgamma(2 + z) plus or minus the logarithm of their product: rounded a few times rather than
6517 * cancelled. Next to a pole the factor z is the small one, and its logarithm is the answer.
6518 * - x >= 32: Stirling's asymptotic series.
6519 * - x <= -32: the reflection formula, as |gamma(x)| = pi / (|sin(pi x)| |x| gamma(-x)), with the
6520 * sine reduced exactly by abs_sin_pi().
6521 *
6522 * The result is the logarithm of the absolute value: the gamma function alternates sign between
6523 * the poles at the non positive integers.
6524 *
6525 * Accuracy, measured against mpmath and pinned by tests/float128_accuracy_gtest.cpp: within 6 ulp
6526 * for x > 0. For x < 0 within the larger of 6 ulp and an absolute error of 2^-110. The absolute
6527 * term matters next to the zeros lgamma has on the negative axis - two between each pair of
6528 * poles from (-3, -2) to (-32, -31), about 1/n! from the poles - where the answer is a difference
6529 * of terms of order log(n!): relative to a result that vanishes there it is unbounded.
6530 *
6531 * @param x Input value
6532 * @return log(|gamma(x)|)
6533 */
6534 [[nodiscard]] friend FP128_INLINE float128 lgamma(float128 x) noexcept
6535 {
6536 if (x.is_nan())
6537 return propagate_nan(x);
6538 if (x.is_inf())
6539 return inf();
6540 // The non positive integers are the poles of the gamma function
6541 if (x.is_zero() || (x.is_negative() && x.is_int())) {
6542 detail::raise_flags(FE_DIVBYZERO);
6543 return inf();
6544 }
6545 // gamma(1) and gamma(2) are both one, which the reduction below reaches exactly as well;
6546 // this only saves the work.
6547 if (x == float128::one() || x == float128(2))
6548 return float128();
6549 // From here on only the flags the result justifies reach the caller.
6550 detail::flag_filter filter;
6551
6553 const float128 n_value = round(x);
6554 const float128 z = x - n_value; // exact, |z| <= 1/2
6555 const int32_t n = static_cast<int32_t>(n_value);
6556 float128 product = float128::one();
6557 if (n >= 2) {
6558 // gamma(x) = gamma(2 + z) * (z + 2) * (z + 3) * ... * (z + n - 1)
6559 for (int32_t j = 2; j < n; ++j) {
6560 product *= z + float128(j);
6561 }
6562 return filter(lgamma_near_two(z) + log(product));
6563 }
6564 // gamma(x) = gamma(2 + z) / ((1 + z) * z * (z - 1) * ... * (z + n)). Of the factors only
6565 // 1 + z can round, so its logarithm comes from log1p().
6566 for (int32_t k = n; k <= 0; ++k) {
6567 product *= z + float128(k);
6568 }
6569 return filter(lgamma_near_two(z) - (log1p(z) + log(fabs(product))));
6570 }
6571
6572 if (x.is_negative()) {
6573 return filter(log(float128::pi() / (abs_sin_pi(x) * fabs(x))) - lgamma(-x));
6574 }
6575
6576 constexpr float128 coefficients[STIRLING_TERMS] = {
6577 float128(0x5555555555555555, 0x555555555555, 0x3FFB, 0), // B2 / (2*1)
6578 float128(0x6C16C16C16C16C17, 0x6C16C16C16C1, 0x3FF6, 1), // B4 / (4*3)
6579 float128(0xA01A01A01A01A01A, 0xA01A01A01A01, 0x3FF4, 0), // B6 / (6*5)
6580 float128(0x3813813813813814, 0x381381381381, 0x3FF4, 1), // B8 / (8*7)
6581 float128(0x3570EA73806E5479, 0xB951E2B18FF2, 0x3FF4, 0), // B10 / (10*9)
6582 float128(0xC81F6AB0D9993C7D, 0xF6AB0D9993C7, 0x3FF5, 1), // B12 / (12*11)
6583 float128(0xA41A41A41A41A41A, 0xA41A41A41A41, 0x3FF7, 0), // B14 / (14*13)
6584 float128(0x7DC2064A8ED3175C, 0xE4286CB0F539, 0x3FF9, 1), // B16 / (16*15)
6585 float128(0xFFA1876FE96381E0, 0x6FE96381E067, 0x3FFC, 0), // B18 / (18*17)
6586 float128(0x9EDBDB9CE625987D, 0x6476701181F3, 0x3FFF, 1), // B20 / (20*19)
6587 float128(0x5A74F53910C8B380, 0xACE44322CE00, 0x4002, 0), // B22 / (22*21)
6588 float128(0xAAB67EE25D73C0F9, 0x39B2525CCCC1, 0x4006, 1), // B24 / (24*23)
6589 float128(0x1B4E81B4E81B4E82, 0x12234E81B4E8, 0x400A, 0), // B26 / (26*25)
6590 float128(0x7EB3FEDDD8496920, 0x1A198AE1C4AB, 0x400E, 1), // B28 / (28*27)
6591 float128(0xA38433DC9FB888D4, 0x51A2089A6E11, 0x4012, 0), // B30 / (30*29)
6592 float128(0x77880C2D3577880C, 0xD1089B142D35, 0x4016, 1), // B32 / (32*31)
6593 };
6594 constexpr float128 half_log_two_pi(0x4A69297920028832, 0xD67F1C864BEB, 0x3FFE, 0);
6595
6596 const float128 inv_xx = float128::one() / sqr(x);
6597 float128 series;
6598 for (int32_t i = STIRLING_TERMS - 1; i >= 1; --i)
6599 series = (series + coefficients[i]) * inv_xx;
6600 series = (series + coefficients[0]) / x;
6601
6602 return filter((x - float128::half()) * log(x) - x + half_log_two_pi + series);
6603 }
6604
6605 /**
6606 * @brief The gamma function.
6607 *
6608 * - The integers up to 38: the factorial, exactly. 37! is the largest factorial a binary128 holds
6609 * without rounding - its odd part has 110 bits - so no partial product of the integers below x
6610 * rounds either.
6611 * - |x| < 32: exp(lgamma(2 + z)) multiplied or divided by the exact factors the recurrence takes,
6612 * see lgamma(). The exponential is of a value below 0.3 and the product rounds once per factor,
6613 * so the result is within a few ulp - also next to a pole, where it used to be 2^39 ulp off at
6614 * -1 + 2^-40, and at a tiny argument, where gamma(x) is about 1/x.
6615 * - Elsewhere exp(lgamma(x)), with the sign of the interval between the poles. The exponential
6616 * is what limits the accuracy there: a logarithm as large as 11000 carries its own last bit
6617 * into the fourteenth bit from the bottom of the result.
6618 *
6619 * Accuracy, measured against mpmath and pinned by tests/float128_accuracy_gtest.cpp: exact for
6620 * the integers up to 38, within 8 ulp for |x| < 32, and within 8 + 4.5 |lgamma(x)| ulp beyond
6621 * that, which reaches about 51000 ulp at either end of the range.
6622 *
6623 * @param x Input value
6624 * @return gamma(x)
6625 */
6626 [[nodiscard]] friend FP128_INLINE float128 tgamma(float128 x) noexcept
6627 {
6628 if (x.is_nan())
6629 return propagate_nan(x);
6630 if (x.is_inf())
6631 return x.is_negative() ? invalid_operation() : x;
6632 // The poles, and the two zeros of 1/gamma that a signed zero argument picks out
6633 if (x.is_zero()) {
6634 detail::raise_flags(FE_DIVBYZERO);
6635 return x.is_negative() ? -inf() : inf();
6636 }
6637 if (x.is_negative() && x.is_int())
6638 return invalid_operation();
6639 // From here on only the flags the result justifies reach the caller.
6640 detail::flag_filter filter;
6641 // gamma(1756) overflows
6642 if (x > float128(1756))
6643 return filter.inexact(inf());
6644
6645 // 37! is the largest factorial a binary128 holds exactly, so every integer argument up to
6646 // 38 comes back with no rounding at all.
6647 if (x.is_int() && x <= float128(38)) {
6648 float128 result = float128::one();
6649 for (float128 i = float128(2); i < x; i += float128::one())
6650 result *= i;
6651 return filter(result);
6652 }
6653
6655 const float128 n_value = round(x);
6656 const float128 z = x - n_value; // exact, |z| <= 1/2
6657 const int32_t n = static_cast<int32_t>(n_value);
6658 float128 result = exp(lgamma_near_two(z));
6659 if (n >= 2) {
6660 for (int32_t j = 2; j < n; ++j) {
6661 result *= z + float128(j);
6662 }
6663 return filter(result);
6664 }
6665 // gamma(1 + z) = gamma(2 + z) / (1 + z)
6666 if (n == 1) {
6667 return filter(result / (float128::one() + z));
6668 }
6669 // Every factor but z itself is at least 1/2 in magnitude, so their product is formed
6670 // first and z, which may be subnormal, divides last: gamma(z) is then about 1/z, and
6671 // dividing by a subnormal z rounds only once.
6672 float128 product = float128::one() + z;
6673 for (int32_t k = n; k < 0; ++k) {
6674 product *= z + float128(k);
6675 }
6676 return filter((result / product) / z);
6677 }
6678
6679 const float128 magnitude = exp(lgamma(x));
6680 if (x.is_positive())
6681 return filter(magnitude);
6682
6683 // Between two poles the gamma function keeps one sign, alternating with every step: it is
6684 // negative on (-1, 0), positive on (-2, -1), and so on, which is the parity of floor(x).
6685 const float128 floor_x = floor(x);
6686 return filter(is_odd_int(floor_x) ? -magnitude : magnitude);
6687 }
6688
6689 /// @brief Absolute value, the name `<cmath>` gives the floating point overload alongside fabs.
6690 [[nodiscard]] friend FP128_FORCE_INLINE constexpr float128 abs(const float128& x) noexcept { return fabs(x); }
6691
6692 /// @brief User-defined literal implementation for constructing float128 from a string.
6693 friend float128 operator""_f128(const char* literal) { return float128(literal); }
6694};
6695
6696static_assert(sizeof(float128) == sizeof(uint64_t) * 2);
6697
6698/***********************************************************************************
6699 * Text conversion and standard library integration
6700 ************************************************************************************/
6701
6702namespace detail
6703{
6704/// @brief Default precision the e, f and g styles use when none is given, as in printf.
6705inline constexpr int32_t DEFAULT_PRECISION = 6;
6706
6707/**
6708 * @brief Appends the decimal exponent of a scientific or hexadecimal form, with a sign.
6709 * @param out Text to append to
6710 * @param exponent The exponent
6711 * @param marker The character that introduces it: e, E, p or P
6712 * @param min_digits Fewest digits to show, zero padded: two as printf shows a double's decimal
6713 * exponent, one as std::to_chars shows a hexadecimal one
6714 */
6715inline void append_exponent(std::string& out, int32_t exponent, char marker, int32_t min_digits = 2)
6716{
6717 out += marker;
6718 out += (exponent < 0) ? '-' : '+';
6719 // The magnitude is taken in the unsigned domain, where the negation wraps. Negating the signed
6720 // value is undefined for the most negative one and produces the same bit pattern for the rest.
6721 uint32_t magnitude = (exponent < 0) ? (0u - static_cast<uint32_t>(exponent)) : static_cast<uint32_t>(exponent);
6722
6723 // Ten digits is the widest a uint32_t can be. No exponent this function is handed comes close -
6724 // the largest is 16494, from the hexadecimal form of the smallest subnormal - but the buffer is
6725 // sized for the type rather than for the callers, so the loops below cannot run past it.
6726 //
6727 // The digits are produced least significant first and so are written from the end of the
6728 // buffer backwards, which leaves them already in order and lets the whole run be appended at
6729 // once. Filling forwards and reversing afterwards needs three loops over one shared counter,
6730 // and MSVC's code analysis cannot see that the counter stays in range across all of them.
6731 constexpr int32_t max_digits = 10;
6732 char digits[max_digits];
6733 int32_t index = max_digits;
6734 while (index > 0) {
6735 digits[--index] = static_cast<char>('0' + (magnitude % 10));
6736 magnitude /= 10;
6737 if (magnitude == 0)
6738 break;
6739 }
6740
6741 // The exponent shows at least min_digits digits.
6742 while (index > max_digits - min_digits)
6743 digits[--index] = '0';
6744
6745 out.append(digits + index, static_cast<size_t>(max_digits - index));
6746}
6747
6748/**
6749 * @brief Fewest significant digits that read back as the same value.
6750 *
6751 * The search is a bisection rather than a scan because the property is monotone: a decimal with
6752 * more digits is at least as close to the value as one with fewer, so if some length reads back
6753 * correctly then every longer one does too.
6754 *
6755 * @param value Finite, non zero value
6756 * @return Digit count in [1, 36].
6757 */
6758[[nodiscard]] inline int32_t shortest_digit_count(const float128& value)
6759{
6760 uint64_t low = 0, high = 0;
6761 int32_t exponent = 0;
6762 uint32_t sign = 0;
6763 value.get_components(low, high, exponent, sign);
6764 uint64_t want_low = 0, want_high = 0;
6765 value.get_bits(want_low, want_high);
6766 want_high &= ~(1ull << 63);
6767
6768 // The trial conversions raise exceptions that belong to none of the caller's operations.
6769 const flag_quiet quiet;
6770 char digits[40];
6771 int32_t lower = 1;
6772 int32_t upper = 36; // max_digits10, which always reads back
6773
6774 while (lower < upper) {
6775 const int32_t middle = (lower + upper) / 2;
6776 const int32_t exponent10 = to_decimal_digits(low, high, exponent, middle, digits);
6777
6778 // Read back the way from_chars() reads, rounded once to the final width, which for a
6779 // subnormal is fewer than 113 bits: comparing 113 bit mantissas instead demanded more
6780 // digits than a subnormal needs.
6781 uint64_t back_low = 0, back_high = 0, extra = 0;
6782 int32_t back_exponent = 0;
6783 bool same = false;
6784 if (from_decimal_digits(digits, middle, exponent10 - middle, back_low, back_high, back_exponent, &extra)) {
6785 const float128 back = float128::round_pack(0, back_exponent, back_low, back_high, extra, rounding::nearest_even);
6786 uint64_t got_low = 0, got_high = 0;
6787 back.get_bits(got_low, got_high);
6788 same = got_low == want_low && got_high == want_high;
6789 }
6790 if (same)
6791 upper = middle;
6792 else
6793 lower = middle + 1;
6794 }
6795 return lower;
6796}
6797
6798/**
6799 * @brief Renders a float128 as text.
6800 *
6801 * The one place the character form of a value is produced. std::format, the stream inserter,
6802 * to_chars and the conversion to std::string all come through here so that they cannot disagree
6803 * with each other.
6804 *
6805 * @param value Value to render
6806 * @param style One of 'a', 'e', 'f' or 'g', or '\0' for the shortest form that reads back exactly
6807 * @param precision Digits after the point, or significant digits for 'g'. Negative selects the
6808 * default for the style
6809 * @param uppercase Emit the digits, the exponent marker and the special values in upper case
6810 * @param alternate Keep the decimal point and, for 'g', the trailing zeros
6811 * @param sign_char Character to emit for a non negative value: '-' means emit nothing
6812 * @param bare_hex For the 'a' style, the form std::to_chars writes: no 0x prefix and the binary
6813 * exponent with as few digits as it needs, 1.8p+1, which std::from_chars with
6814 * chars_format::hex reads back. Otherwise the printf form, 0x1.8p+01.
6815 * @return The rendered text.
6816 */
6817[[nodiscard]] inline std::string render(const float128& value, char style, int32_t precision, bool uppercase, bool alternate, char sign_char,
6818 bool bare_hex)
6819{
6820 std::string out;
6821 if (value.is_negative())
6822 out += '-';
6823 else if (sign_char != '-')
6824 out += sign_char;
6825
6826 if (value.is_nan()) {
6827 out += uppercase ? "NAN" : "nan";
6828 return out;
6829 }
6830 if (value.is_inf()) {
6831 out += uppercase ? "INF" : "inf";
6832 return out;
6833 }
6834
6835 const char* const hex_digits = uppercase ? "0123456789ABCDEF" : "0123456789abcdef";
6836
6837 // The hexadecimal form is a direct reading of the encoding, so it needs none of the decimal
6838 // machinery and is exact by construction at any precision.
6839 if (style == 'a') {
6840 if (!bare_hex) {
6841 out += uppercase ? "0X" : "0x";
6842 }
6843 const int32_t exponent_digits = bare_hex ? 1 : 2;
6844 if (value.is_zero()) {
6845 out += '0';
6846 if (alternate || precision > 0) {
6847 out += '.';
6848 for (int32_t i = 0; i < precision; ++i)
6849 out += '0';
6850 }
6851 append_exponent(out, 0, uppercase ? 'P' : 'p', exponent_digits);
6852 return out;
6853 }
6854
6855 uint64_t low = 0, high = 0;
6856 int32_t exponent = 0;
6857 uint32_t sign = 0;
6858 value.get_components(low, high, exponent, sign);
6859
6860 // 28 hex digits hold the whole fraction, and the leading one sits above the point.
6861 char fraction[28];
6862 for (int32_t i = 0; i < 28; ++i) {
6863 const int32_t shift = 108 - 4 * i;
6864 const uint64_t nibble = (shift >= 64) ? ((high >> (shift - 64)) & 0xF) : ((low >> shift) & 0xF);
6865 fraction[i] = hex_digits[nibble];
6866 }
6867
6868 const auto hex_value = [](char c) {
6869 if (c >= '0' && c <= '9')
6870 return c - '0';
6871 return ((c >= 'a') ? (c - 'a') : (c - 'A')) + 10;
6872 };
6873
6874 int32_t kept = (precision >= 0) ? precision : 28;
6875 if (kept > 28)
6876 kept = 28;
6877 // Rounding a shortened fraction, in the current direction: to nearest the first dropped
6878 // digit decides and a tie goes to the even digit (it used to go up). A carry can run
6879 // through the fraction and into the leading one, which is the next power of two.
6880 bool leading_two = false;
6881 if (precision >= 0 && precision < 28) {
6882 const int32_t first_dropped = hex_value(fraction[precision]);
6883 bool rest = false;
6884 for (int32_t i = precision + 1; i < 28; ++i)
6885 rest = rest || fraction[i] != '0';
6886 const int32_t last_kept = (precision > 0) ? hex_value(fraction[precision - 1]) : 1;
6887 bool up = false;
6888 switch (digit_rounding_for(sign)) {
6889 case digit_rounding::nearest_even: up = first_dropped > 8 || (first_dropped == 8 && (rest || (last_kept & 1) != 0)); break;
6890 case digit_rounding::away_from_zero: up = first_dropped != 0 || rest; break;
6891 default: break;
6892 }
6893 if (first_dropped != 0 || rest)
6894 raise_flags(FE_INEXACT);
6895 if (up) {
6896 int32_t index = precision - 1;
6897 while (index >= 0) {
6898 const int32_t digit = hex_value(fraction[index]);
6899 if (digit != 15) {
6900 fraction[index] = hex_digits[digit + 1];
6901 break;
6902 }
6903 fraction[index] = '0';
6904 --index;
6905 }
6906 if (index < 0)
6907 leading_two = true;
6908 }
6909 }
6910 if (precision < 0) {
6911 // Trailing zeros carry no information in the shortest form.
6912 while (kept > 0 && fraction[kept - 1] == '0')
6913 --kept;
6914 }
6915
6916 out += leading_two ? '2' : '1';
6917 if (kept > 0 || alternate || precision > 28) {
6918 out += '.';
6919 out.append(fraction, static_cast<size_t>(kept));
6920 // The 28 digits are the whole fraction; a longer precision is padded with zeros, as
6921 // printf pads it. It used to stop at 28 digits whatever was asked for.
6922 if (precision > 28) {
6923 out.append(static_cast<size_t>(precision - 28), '0');
6924 }
6925 }
6926 append_exponent(out, exponent, uppercase ? 'P' : 'p', exponent_digits);
6927 return out;
6928 }
6929
6930 if (value.is_zero()) {
6931 out += '0';
6932 // The fixed and scientific layouts always show the digits asked for; the general one shows
6933 // none unless the alternate form wanted them.
6934 int32_t zeros = 0;
6935 if (style == 'f' || style == 'e')
6936 zeros = (precision >= 0) ? precision : DEFAULT_PRECISION;
6937 else if (alternate)
6938 zeros = (precision > 0) ? precision - 1 : DEFAULT_PRECISION - 1;
6939
6940 if (zeros > 0 || alternate) {
6941 out += '.';
6942 out.append(static_cast<size_t>(zeros), '0');
6943 }
6944 if (style == 'e')
6945 append_exponent(out, 0, uppercase ? 'E' : 'e');
6946 return out;
6947 }
6948
6949 uint64_t low = 0, high = 0;
6950 int32_t exponent = 0;
6951 uint32_t sign = 0;
6952 value.get_components(low, high, exponent, sign);
6953
6954 char digits[MAX_OUTPUT_DIGITS];
6955 int32_t significant = 0;
6956 int32_t exponent10 = 0;
6957 // The digits are rounded in the current direction, except for the shortest form, which is
6958 // defined by reading back to nearest. Either way a conversion that drops something is inexact.
6959 const digit_rounding direction = digit_rounding_for(sign);
6960 bool exact = false;
6961
6962 if (style == '\0') {
6963 significant = shortest_digit_count(value);
6964 exponent10 = to_decimal_digits(low, high, exponent, significant, digits, &exact);
6965 } else if (style == 'e') {
6966 significant = ((precision >= 0) ? precision : DEFAULT_PRECISION) + 1;
6967 if (significant > MAX_OUTPUT_DIGITS)
6968 significant = MAX_OUTPUT_DIGITS;
6969 exponent10 = to_decimal_digits(low, high, exponent, significant, digits, &exact, direction);
6970 } else if (style == 'g') {
6971 significant = (precision > 0) ? precision : ((precision == 0) ? 1 : DEFAULT_PRECISION);
6972 if (significant > MAX_OUTPUT_DIGITS)
6973 significant = MAX_OUTPUT_DIGITS;
6974 exponent10 = to_decimal_digits(low, high, exponent, significant, digits, &exact, direction);
6975 } else {
6976 // Fixed notation asks for a count of digits after the point rather than significant ones,
6977 // and how many that is depends on where the value sits. One digit is generated first to
6978 // find that out, then the real request is made.
6979 const int32_t after_point = (precision >= 0) ? precision : DEFAULT_PRECISION;
6980 int32_t probe_exponent10 = to_decimal_digits(low, high, exponent, 1, digits, &exact);
6981 significant = probe_exponent10 + after_point;
6982
6983 // A single digit probe rounds, and a value just below a power of ten rounds up into the
6984 // next one: 99 comes back as 1e2 and claims one more digit than it has. Generating the
6985 // digits reveals the true exponent, and one retry with it is always enough because the
6986 // rounding can only move the exponent by one.
6987 if (significant > 0 && significant <= MAX_OUTPUT_DIGITS) {
6988 const int32_t actual_exponent10 = to_decimal_digits(low, high, exponent, significant, digits, nullptr, direction);
6989 if (actual_exponent10 != probe_exponent10) {
6990 probe_exponent10 = actual_exponent10;
6991 significant = actual_exponent10 + after_point;
6992 }
6993 }
6994
6995 if (significant <= 0) {
6996 // Every digit asked for is zero, and the value lies below the last of them. To nearest,
6997 // it rounds up only from above half a place - a tie goes to the even digit, the zero
6998 // already there; away from zero it always does.
6999 //
7000 // Half a place is decided on the leading digit truncated, with whether anything follows
7001 // it. The probe above rounded that digit, which made every value from 0.45 of a place up
7002 // look like 0.5 and above: 0.046 printed with one decimal as 0.1.
7003 raise_flags(FE_INEXACT);
7004 bool round_up = false;
7005 if (direction == digit_rounding::away_from_zero) {
7006 round_up = true;
7007 } else if (direction == digit_rounding::nearest_even) {
7008 bool rest_is_zero = false;
7009 const int32_t leading_exponent10 = to_decimal_digits(low, high, exponent, 1, digits, &rest_is_zero, digit_rounding::toward_zero);
7010 round_up = (leading_exponent10 == -after_point) && (digits[0] > '5' || (digits[0] == '5' && !rest_is_zero));
7011 }
7012 // With no digits after the point the unit that rounding up adds is the integer one. It
7013 // used to be dropped, so 0.7 printed as 0 with no decimals.
7014 out += (round_up && after_point == 0) ? '1' : '0';
7015 if (after_point > 0 || alternate) {
7016 out += '.';
7017 for (int32_t i = 0; i < after_point; ++i)
7018 out += (round_up && i == after_point - 1) ? '1' : '0';
7019 }
7020 return out;
7021 }
7022
7023 if (significant > MAX_OUTPUT_DIGITS) {
7024 // Past MAX_OUTPUT_DIGITS the exact expansion is no longer produced and the rest of
7025 // the request is filled with zeros. The expansion of a subnormal runs to 16494 places
7026 // after the point; the cap is set at what writing the widest finite value out in full
7027 // needs, which is 4933.
7028 exponent10 = to_decimal_digits(low, high, exponent, MAX_OUTPUT_DIGITS, digits, &exact, direction);
7029 if (!exact)
7030 raise_flags(FE_INEXACT);
7031 const int32_t padding = significant - MAX_OUTPUT_DIGITS;
7032 significant = MAX_OUTPUT_DIGITS;
7033 std::string body(digits, static_cast<size_t>(significant));
7034 body.append(static_cast<size_t>(padding), '0');
7035 // Lay the point out from the exponent the generator returned.
7036 if (exponent10 <= 0) {
7037 out += "0.";
7038 out.append(static_cast<size_t>(-exponent10), '0');
7039 out += body;
7040 } else {
7041 out.append(body, 0, static_cast<size_t>(exponent10));
7042 out += '.';
7043 out.append(body, static_cast<size_t>(exponent10), std::string::npos);
7044 }
7045 return out;
7046 }
7047
7048 exponent10 = to_decimal_digits(low, high, exponent, significant, digits, &exact, direction);
7049 }
7050 if (!exact)
7051 raise_flags(FE_INEXACT);
7052
7053 const int32_t scientific_exponent = exponent10 - 1;
7054
7055 int32_t kept = significant;
7056 if ((style == 'g' || style == '\0') && !alternate) {
7057 while (kept > 1 && digits[kept - 1] == '0')
7058 --kept;
7059 }
7060
7061 bool scientific = (style == 'e');
7062 if (style == 'g') {
7063 // printf's rule for %g, which std::format keeps for the g type.
7064 scientific = (scientific_exponent < -4) || (scientific_exponent >= significant);
7065 } else if (style == '\0') {
7066 // The default is whichever layout is shorter, with a tie going to the fixed one, which is
7067 // what std::to_chars produces and therefore what std::format gives a double. The rule for
7068 // %g would print 100 as 1e+02: it compares the exponent against the digit count, and the
7069 // shortest form of a round number has very few digits.
7070 int32_t fixed_length = 0;
7071 if (exponent10 <= 0)
7072 fixed_length = 2 - exponent10 + kept;
7073 else if (exponent10 >= kept)
7074 fixed_length = exponent10;
7075 else
7076 fixed_length = kept + 1;
7077
7078 int32_t exponent_digits = 2;
7079 for (int32_t magnitude = (scientific_exponent < 0) ? -scientific_exponent : scientific_exponent; magnitude >= 100; magnitude /= 10)
7080 ++exponent_digits;
7081 const int32_t scientific_length = kept + ((kept > 1) ? 1 : 0) + 2 + exponent_digits;
7082
7083 scientific = scientific_length < fixed_length;
7084 }
7085
7086 if (scientific) {
7087 out += digits[0];
7088 if (kept > 1 || alternate) {
7089 out += '.';
7090 out.append(digits + 1, static_cast<size_t>(kept - 1));
7091 }
7092 append_exponent(out, scientific_exponent, uppercase ? 'E' : 'e');
7093 return out;
7094 }
7095
7096 if (exponent10 <= 0) {
7097 out += "0.";
7098 out.append(static_cast<size_t>(-exponent10), '0');
7099 out.append(digits, static_cast<size_t>(kept));
7100 } else if (exponent10 >= kept) {
7101 out.append(digits, static_cast<size_t>(kept));
7102 out.append(static_cast<size_t>(exponent10 - kept), '0');
7103 if (alternate)
7104 out += '.';
7105 } else {
7106 out.append(digits, static_cast<size_t>(exponent10));
7107 out += '.';
7108 out.append(digits + exponent10, static_cast<size_t>(kept - exponent10));
7109 }
7110
7111 // Fixed notation pads out to the requested number of digits after the point.
7112 if (style == 'f') {
7113 const int32_t after_point = (precision >= 0) ? precision : DEFAULT_PRECISION;
7114 const size_t point = out.find('.');
7115 const size_t written = (point == std::string::npos) ? 0 : (out.size() - point - 1);
7116 if (after_point > 0) {
7117 if (point == std::string::npos)
7118 out += '.';
7119 for (size_t i = written; i < static_cast<size_t>(after_point); ++i)
7120 out += '0';
7121 }
7122 }
7123 return out;
7124}
7125} // namespace detail
7126
7127/**
7128 * @brief The shortest decimal string that reads back as this exact value.
7129 * @param value Value to convert
7130 * @return Decimal text, in scientific notation when the exponent is far from zero.
7131 */
7132[[nodiscard]] inline std::string to_string(const float128& value)
7133{
7134 return detail::render(value, '\0', -1, false, false, '-');
7135}
7136
7137namespace detail
7138{
7139/**
7140 * @brief Reads one of the special values: inf, infinity, nan, nan(n-char-sequence) or snan.
7141 *
7142 * Case is ignored, as IEEE 754-2008 5.12.1 asks. A payload in parentheses is read the way
7143 * fp128::nan() reads one, and the parentheses are only consumed when they are closed. "snan" reads
7144 * as a signaling NaN, which the standard recommends and strtod() does not offer.
7145 *
7146 * @param cursor Start of the text, past any sign
7147 * @param last End of the text
7148 * @param negative The sign that came before it
7149 * @param value Receives the value
7150 * @return Past what was read, or nullptr when the text is none of these.
7151 */
7152inline const char* parse_special_value(const char* cursor, const char* last, bool negative, float128& value)
7153{
7154 const auto lower = [](char c) { return static_cast<char>((c >= 'A' && c <= 'Z') ? (c - 'A' + 'a') : c); };
7155 const auto matches = [&](const char* word, size_t length) {
7156 if (static_cast<size_t>(last - cursor) < length)
7157 return false;
7158 for (size_t i = 0; i < length; ++i) {
7159 if (lower(cursor[i]) != word[i])
7160 return false;
7161 }
7162 return true;
7163 };
7164
7165 if (matches("inf", 3)) {
7166 cursor += 3;
7167 if (matches("inity", 5))
7168 cursor += 5;
7169 value = negative ? -float128::inf() : float128::inf();
7170 return cursor;
7171 }
7172 if (matches("snan", 4)) {
7173 value = float128::signaling_nan();
7174 value.set_sign(negative ? 1 : 0);
7175 return cursor + 4;
7176 }
7177 if (matches("nan", 3)) {
7178 cursor += 3;
7179 value = float128::nan();
7180 if (cursor < last && *cursor == '(') {
7181 const char* close = cursor + 1;
7182 while (close < last && (isalnum(static_cast<unsigned char>(*close)) || *close == '_'))
7183 ++close;
7184 if (close < last && *close == ')') {
7185 value = fp128::nan(std::string(cursor + 1, close).c_str());
7186 cursor = close + 1;
7187 }
7188 }
7189 value.set_sign(negative ? 1 : 0);
7190 return cursor;
7191 }
7192 return nullptr;
7193}
7194
7195/**
7196 * @brief Reads a hexadecimal significand with an optional binary exponent, such as 1.8p1.
7197 *
7198 * The form printf's %a writes, without its 0x prefix, as std::from_chars reads it for
7199 * chars_format::hex. IEEE 754-2008 5.12.3 requires it, correctly rounded. Every digit is four bits
7200 * of the significand, so the first 32 significant digits are collected exactly and any further
7201 * non zero digit only counts towards the sticky bit; the value is then rounded once.
7202 *
7203 * @param first Start of the text
7204 * @param last One past its end
7205 * @param value Receives the parsed value, untouched when nothing was parsed
7206 * @return As from_chars().
7207 */
7208inline std::from_chars_result from_hex_chars(const char* first, const char* last, float128& value)
7209{
7210 std::from_chars_result result {first, std::errc {}};
7211 const char* cursor = first;
7212 if (cursor == last) {
7213 result.ec = std::errc::invalid_argument;
7214 return result;
7215 }
7216
7217 bool negative = false;
7218 if (*cursor == '-' || *cursor == '+') {
7219 negative = (*cursor == '-');
7220 ++cursor;
7221 }
7222 if (const char* end = parse_special_value(cursor, last, negative, value)) {
7223 result.ptr = end;
7224 return result;
7225 }
7226
7227 const auto hex_digit = [](char c) -> int32_t {
7228 if (c >= '0' && c <= '9')
7229 return c - '0';
7230 if (c >= 'a' && c <= 'f')
7231 return c - 'a' + 10;
7232 if (c >= 'A' && c <= 'F')
7233 return c - 'A' + 10;
7234 return -1;
7235 };
7236
7237 // The value is (h:l) * 2^binary_exponent, plus something below that when sticky is set.
7238 uint64_t l = 0, h = 0;
7239 int32_t bits = 0;
7240 int64_t binary_exponent = 0;
7241 bool sticky = false, any_digit = false, nonzero = false;
7242 const auto take = [&](int32_t digit, bool after_point) {
7243 any_digit = true;
7244 if (!nonzero && digit == 0) {
7245 // a leading zero: nothing to keep, but after the point it still moves the exponent
7246 if (after_point)
7247 binary_exponent -= 4;
7248 return;
7249 }
7250 nonzero = true;
7251 if (bits <= 124) {
7252 h = (h << 4) | (l >> 60);
7253 l = (l << 4) | static_cast<uint64_t>(digit);
7254 bits += 4;
7255 if (after_point)
7256 binary_exponent -= 4;
7257 } else {
7258 sticky = sticky || digit != 0;
7259 if (!after_point)
7260 binary_exponent += 4;
7261 }
7262 };
7263
7264 while (cursor < last && hex_digit(*cursor) >= 0)
7265 take(hex_digit(*cursor++), false);
7266 if (cursor < last && *cursor == '.') {
7267 ++cursor;
7268 while (cursor < last && hex_digit(*cursor) >= 0)
7269 take(hex_digit(*cursor++), true);
7270 }
7271 if (!any_digit) {
7272 result.ec = std::errc::invalid_argument;
7273 return result;
7274 }
7275 result.ptr = cursor;
7276
7277 // The binary exponent is only consumed when it is well formed, so that "1p" reads as 1.
7278 if (cursor < last && (*cursor == 'p' || *cursor == 'P')) {
7279 const char* probe = cursor + 1;
7280 bool exponent_negative = false;
7281 if (probe < last && (*probe == '-' || *probe == '+')) {
7282 exponent_negative = (*probe == '-');
7283 ++probe;
7284 }
7285 if (probe < last && *probe >= '0' && *probe <= '9') {
7286 int64_t magnitude = 0;
7287 while (probe < last && *probe >= '0' && *probe <= '9') {
7288 if (magnitude < 1000000)
7289 magnitude = magnitude * 10 + (*probe - '0');
7290 ++probe;
7291 }
7292 binary_exponent += exponent_negative ? -magnitude : magnitude;
7293 result.ptr = probe;
7294 }
7295 }
7296
7297 if (!nonzero) {
7298 value = float128();
7299 value.set_sign(negative ? 1 : 0);
7300 return result;
7301 }
7302
7303 // Far outside the format's range only an overflow or a zero can come of it, whatever the exact
7304 // exponent; clamping keeps the arithmetic below in range without changing which.
7305 const int64_t clamped = (binary_exponent < -100000) ? -100000 : ((binary_exponent > 100000) ? 100000 : binary_exponent);
7306 value = float128::norm_round_pack(negative ? 1u : 0u, static_cast<int32_t>(clamped) + 112, l, h, sticky);
7307 if (value.is_inf() || value.is_zero())
7308 result.ec = std::errc::result_out_of_range;
7309 return result;
7310}
7311} // namespace detail
7312
7313namespace detail
7314{
7315/**
7316 * @brief Rounds digits * 10^exponent10, with the given sign, to a float128.
7317 * @tparam Capacity Limbs of the workspace
7318 * @param workspace Big integer for decimal_to_binary() to compute in
7319 * @param digits Significant decimal digits, no sign and no point
7320 * @param count Number of digits
7321 * @param max_kept Digits used as such; any after them only count as a sticky bit
7322 * @param exponent10 Power of ten the digits are scaled by
7323 * @param sign 1 for a negative value
7324 * @param value Receives the result
7325 * @return result_out_of_range when it overflowed to an infinity or underflowed to zero, otherwise
7326 * no error.
7327 */
7328template <int32_t Capacity>
7329inline std::errc round_decimal(basic_big_uint<Capacity>& workspace, const char* digits, int32_t count, int32_t max_kept, int32_t exponent10,
7330 uint32_t sign, float128& value) noexcept
7331{
7332 uint64_t low = 0, high = 0, extra = 0;
7333 int32_t exponent = 0;
7334 if (!decimal_to_binary(workspace, digits, count, max_kept, exponent10, low, high, exponent, &extra)) {
7335 if (exponent == 0) {
7336 // the digits were all zeros
7337 value = float128();
7338 value.set_sign(sign);
7339 return std::errc {};
7340 }
7341 // Far beyond the range in one direction or the other. A value of the right size and a
7342 // sticky bit let the rounding decide the result, which depends on the direction: an
7343 // overflow can stop at the largest finite value, an underflow at the smallest subnormal.
7344 value = float128::round_pack(sign, (exponent > 0) ? 20000 : -20000, 0, 1ull << 48, 1);
7345 return std::errc::result_out_of_range;
7346 }
7347
7348 // The mantissa comes back unrounded, so a subnormal result is rounded once, to its own width.
7349 value = float128::round_pack(sign, exponent, low, high, extra);
7350 return (value.is_inf() || value.is_zero()) ? std::errc::result_out_of_range : std::errc {};
7351}
7352} // namespace detail
7353
7354/**
7355 * @brief Converts text to a float128, in the shape of std::from_chars.
7356 *
7357 * Reads the longest prefix of [first, last) that forms a number: an optional sign, decimal digits
7358 * with an optional point and an optional exponent, or one of inf, infinity, nan, nan(payload) and
7359 * snan. The result is the representable value nearest the one the text names, rounded once in the
7360 * current rounding direction - including when it is subnormal, where fewer than 113 bits are kept.
7361 *
7362 * That holds for any number of digits. The first 40 significant ones settle the rounding unless
7363 * the value lies within one unit of the fortieth digit of a point halfway between two binary128
7364 * values; only then are all of them read, up to the 11700 that decide any case, which costs a few
7365 * milliseconds for an input that long. Digits past the fortieth used to be dropped, so
7366 * 10384593717069655257060992658440193.000001, just above the tie between 2^113 and 2^113 + 2,
7367 * read as the tie and rounded down to 2^113.
7368 *
7369 * @param first Start of the text
7370 * @param last One past the end of the text
7371 * @param value Receives the parsed value, untouched when nothing was parsed
7372 * @return ptr points past what was consumed; ec is invalid_argument when no number was found and
7373 * result_out_of_range when the value is beyond the format's range, in which case value is
7374 * set to the infinity or zero it rounded to.
7375 */
7376inline std::from_chars_result from_chars(const char* first, const char* last, float128& value)
7377{
7378 std::from_chars_result result {first, std::errc {}};
7379 const char* cursor = first;
7380 if (cursor == last) {
7381 result.ec = std::errc::invalid_argument;
7382 return result;
7383 }
7384
7385 bool negative = false;
7386 if (*cursor == '-' || *cursor == '+') {
7387 negative = (*cursor == '-');
7388 ++cursor;
7389 }
7390 if (const char* end = detail::parse_special_value(cursor, last, negative, value)) {
7391 result.ptr = end;
7392 return result;
7393 }
7394
7395 // The digits are collected without the point, which only decides the exponent. One extra place
7396 // is left for the digit that stands for the ones past the fortieth.
7397 char digits[detail::MAX_SIGNIFICANT_DIGITS + 1];
7398 int32_t count = 0;
7399 int32_t exponent10 = 0;
7400 bool any_digit = false;
7401 bool seen_significant = false;
7402 bool dropped = false; // a non zero digit past the fortieth significant one
7403 const char* const significand = cursor;
7404
7405 // What is being built is `digits` read as an integer, times 10^exponent10. A digit before the
7406 // point that does not fit raises the exponent, since its place is still there. One after the
7407 // point lowers it when it is kept, and a leading zero after the point lowers it as well even
7408 // though nothing is stored for it.
7409 const auto take_integer = [&](char digit) {
7410 any_digit = true;
7411 seen_significant = seen_significant || (digit != '0');
7412 if (!seen_significant)
7413 return;
7414 if (count < detail::MAX_SIGNIFICANT_DIGITS) {
7415 digits[count++] = digit;
7416 } else {
7417 ++exponent10;
7418 dropped = dropped || (digit != '0');
7419 }
7420 };
7421 const auto take_fraction = [&](char digit) {
7422 any_digit = true;
7423 seen_significant = seen_significant || (digit != '0');
7424 if (!seen_significant) {
7425 --exponent10;
7426 return;
7427 }
7428 if (count < detail::MAX_SIGNIFICANT_DIGITS) {
7429 digits[count++] = digit;
7430 --exponent10;
7431 } else {
7432 dropped = dropped || (digit != '0');
7433 }
7434 };
7435
7436 while (cursor < last && *cursor >= '0' && *cursor <= '9')
7437 take_integer(*cursor++);
7438
7439 if (cursor < last && *cursor == '.') {
7440 ++cursor;
7441 while (cursor < last && *cursor >= '0' && *cursor <= '9')
7442 take_fraction(*cursor++);
7443 }
7444
7445 if (!any_digit) {
7446 result.ec = std::errc::invalid_argument;
7447 return result;
7448 }
7449 result.ptr = cursor;
7450 const char* const significand_end = cursor;
7451 int32_t exponent_part = 0;
7452
7453 // An exponent is only consumed when it is well formed, so that "1e" reads as 1.
7454 if (cursor < last && (*cursor == 'e' || *cursor == 'E')) {
7455 const char* probe = cursor + 1;
7456 bool exponent_negative = false;
7457 if (probe < last && (*probe == '-' || *probe == '+')) {
7458 exponent_negative = (*probe == '-');
7459 ++probe;
7460 }
7461 if (probe < last && *probe >= '0' && *probe <= '9') {
7462 int64_t magnitude = 0;
7463 while (probe < last && *probe >= '0' && *probe <= '9') {
7464 if (magnitude < 1000000)
7465 magnitude = magnitude * 10 + (*probe - '0');
7466 ++probe;
7467 }
7468 exponent_part = static_cast<int32_t>(exponent_negative ? -magnitude : magnitude);
7469 exponent10 += exponent_part;
7470 result.ptr = probe;
7471 }
7472 }
7473
7474 const uint32_t sign = negative ? 1u : 0u;
7475 detail::big_uint workspace;
7476 if (!dropped) {
7477 result.ec = detail::round_decimal(workspace, digits, count, detail::MAX_SIGNIFICANT_DIGITS, exponent10, sign, value);
7478 return result;
7479 }
7480
7481 // The value lies strictly between P, the forty digits kept, and P plus one unit of the fortieth
7482 // digit. A '1' after P stands for the rest: decimal_to_binary() reads it as a sticky bit, which
7483 // gives the rounding of a value just above P. When that agrees with the rounding of P plus one
7484 // unit, everything between them rounds the same way and the remaining digits cannot matter.
7485 digits[count] = '1';
7486 float128 below;
7487 const std::errc below_ec = detail::round_decimal(workspace, digits, count + 1, detail::MAX_SIGNIFICANT_DIGITS, exponent10 - 1, sign, below);
7488
7490 int32_t upper_exponent10 = exponent10;
7491 for (int32_t i = 0; i < count; ++i)
7492 upper[i] = digits[i];
7493 int32_t index = count - 1;
7494 while (index >= 0 && upper[index] == '9')
7495 upper[index--] = '0';
7496 if (index >= 0) {
7497 ++upper[index];
7498 } else {
7499 // 99...9 plus one is 10...0, one digit longer: the same digits with the exponent one higher.
7500 upper[0] = '1';
7501 ++upper_exponent10;
7502 }
7503 float128 above;
7504 (void)detail::round_decimal(workspace, upper, count, detail::MAX_SIGNIFICANT_DIGITS, upper_exponent10, sign, above);
7505
7506 uint64_t below_low = 0, below_high = 0, above_low = 0, above_high = 0;
7507 below.get_bits(below_low, below_high);
7508 above.get_bits(above_low, above_high);
7509 if (below_low == above_low && below_high == above_high) {
7510 value = below;
7511 result.ec = below_ec;
7512 return result;
7513 }
7514
7515 // A rounding boundary lies within the last unit: read every digit. The workspace is twelve
7516 // kilobytes, so it comes from the heap; should that fail, the sticky reading above stands.
7517 std::unique_ptr<detail::wide_big_uint> wide(new (std::nothrow) detail::wide_big_uint);
7518 std::unique_ptr<char[]> all(new (std::nothrow) char[detail::MAX_EXACT_DIGITS + 1]);
7519 if (!wide || !all) {
7520 value = below;
7521 result.ec = below_ec;
7522 return result;
7523 }
7524 int32_t all_count = 0;
7525 int32_t all_exponent10 = exponent_part;
7526 bool in_fraction = false, significant = false, rest = false;
7527 for (const char* q = significand; q < significand_end; ++q) {
7528 if (*q == '.') {
7529 in_fraction = true;
7530 continue;
7531 }
7532 significant = significant || (*q != '0');
7533 if (!significant) {
7534 if (in_fraction)
7535 --all_exponent10;
7536 continue;
7537 }
7538 if (all_count < detail::MAX_EXACT_DIGITS) {
7539 all[static_cast<size_t>(all_count++)] = *q;
7540 if (in_fraction)
7541 --all_exponent10;
7542 } else {
7543 if (!in_fraction)
7544 ++all_exponent10;
7545 rest = rest || (*q != '0');
7546 }
7547 }
7548 if (rest) {
7549 all[static_cast<size_t>(all_count++)] = '1';
7550 --all_exponent10;
7551 }
7552 result.ec = detail::round_decimal(*wide, all.get(), all_count, detail::MAX_EXACT_DIGITS, all_exponent10, sign, value);
7553 return result;
7554}
7555
7556/**
7557 * @brief Converts text to a float128 in a given format, in the shape of std::from_chars.
7558 *
7559 * chars_format::hex reads a hexadecimal significand and a binary exponent without the 0x prefix,
7560 * as std::from_chars does; every other format reads the decimal forms from_chars() above accepts.
7561 *
7562 * @param first Start of the text
7563 * @param last One past the end of the text
7564 * @param value Receives the parsed value, untouched when nothing was parsed
7565 * @param fmt The format to read
7566 * @return As from_chars() above.
7567 */
7568inline std::from_chars_result from_chars(const char* first, const char* last, float128& value, std::chars_format fmt)
7569{
7570 if (fmt == std::chars_format::hex)
7571 return detail::from_hex_chars(first, last, value);
7572 return from_chars(first, last, value);
7573}
7574
7575/**
7576 * @brief Converts a float128 to text, in the shape of std::to_chars.
7577 * @param first Start of the output range
7578 * @param last One past the end of the output range
7579 * @param value Value to convert
7580 * @param fmt Layout to use. chars_format::hex writes what std::to_chars writes for a double - no 0x
7581 * prefix and as few exponent digits as needed, 1.8p+1 - which from_chars() with
7582 * chars_format::hex reads back to the same value. A subnormal is written normalized,
7583 * 1p-16494 for the smallest one.
7584 * @param precision Digits after the point, or significant digits for `general`
7585 * @return ptr points past the last character written; ec is value_too_large when the range was too
7586 * small, in which case nothing was written.
7587 */
7588inline std::to_chars_result to_chars(char* first, char* last, const float128& value, std::chars_format fmt, int precision)
7589{
7590 char style = '\0';
7591 switch (fmt) {
7592 case std::chars_format::scientific: style = 'e'; break;
7593 case std::chars_format::fixed: style = 'f'; break;
7594 case std::chars_format::hex: style = 'a'; break;
7595 default: style = 'g'; break;
7596 }
7597
7598 // The hexadecimal form without the 0x prefix, which from_chars() does not accept either.
7599 const std::string text = detail::render(value, style, precision, false, false, '-', fmt == std::chars_format::hex);
7600 if (text.size() > static_cast<size_t>(last - first))
7601 return {last, std::errc::value_too_large};
7602
7603 for (size_t i = 0; i < text.size(); ++i)
7604 first[i] = text[i];
7605 return {first + text.size(), std::errc {}};
7606}
7607
7608/// @brief Converts a float128 to text with the default precision for the layout.
7609inline std::to_chars_result to_chars(char* first, char* last, const float128& value, std::chars_format fmt)
7610{
7611 return to_chars(first, last, value, fmt, -1);
7612}
7613
7614/// @brief Converts a float128 to the shortest text that reads back as the same value.
7615inline std::to_chars_result to_chars(char* first, char* last, const float128& value)
7616{
7617 const std::string text = detail::render(value, '\0', -1, false, false, '-');
7618 if (text.size() > static_cast<size_t>(last - first))
7619 return {last, std::errc::value_too_large};
7620
7621 for (size_t i = 0; i < text.size(); ++i)
7622 first[i] = text[i];
7623 return {first + text.size(), std::errc {}};
7624}
7625
7626/**
7627 * @brief Writes a float128 to a stream, honouring its formatting state.
7628 *
7629 * The stream's precision, its fixed, scientific and hexfloat flags, showpos, showpoint, uppercase,
7630 * width, fill and adjustfield are all applied, so a float128 behaves in a stream the way a double
7631 * does.
7632 */
7633inline std::ostream& operator<<(std::ostream& os, const float128& value)
7634{
7635 const std::ios_base::fmtflags flags = os.flags();
7636 const std::ios_base::fmtflags style_flags = flags & std::ios_base::floatfield;
7637
7638 char style = '\0';
7639 int32_t precision = static_cast<int32_t>(os.precision());
7640 if (style_flags == std::ios_base::fixed) {
7641 style = 'f';
7642 } else if (style_flags == std::ios_base::scientific) {
7643 style = 'e';
7644 } else if (style_flags == (std::ios_base::fixed | std::ios_base::scientific)) {
7645 style = 'a';
7646 precision = -1; // hexfloat ignores the precision
7647 } else {
7648 // The default floatfield is the general layout, where the precision counts significant
7649 // digits and zero means one.
7650 style = 'g';
7651 }
7652
7653 const char sign_char = (flags & std::ios_base::showpos) ? '+' : '-';
7654 const bool uppercase = (flags & std::ios_base::uppercase) != 0;
7655 const bool alternate = (flags & std::ios_base::showpoint) != 0;
7656 std::string text = detail::render(value, style, precision, uppercase, alternate, sign_char);
7657
7658 const std::streamsize width = os.width();
7659 os.width(0);
7660 if (static_cast<std::streamsize>(text.size()) < width) {
7661 const size_t padding = static_cast<size_t>(width) - text.size();
7662 const std::ios_base::fmtflags adjust = flags & std::ios_base::adjustfield;
7663 if (adjust == std::ios_base::left) {
7664 text.append(padding, os.fill());
7665 } else if (adjust == std::ios_base::internal && !text.empty() && (text[0] == '-' || text[0] == '+')) {
7666 // internal puts the fill between the sign and the digits
7667 text.insert(1, padding, os.fill());
7668 } else {
7669 text.insert(0, padding, os.fill());
7670 }
7671 }
7672 return os << text;
7673}
7674
7675/**
7676 * @brief Reads a float128 from a stream.
7677 *
7678 * Accepts what the constructor from a string does: a decimal number with an optional exponent, a
7679 * hexadecimal one after a 0x prefix with an optional binary exponent (0x1.8p1), and inf, infinity,
7680 * nan, nan(payload) and snan in any case, each with an optional sign. Leading white space is
7681 * skipped unless skipws is off.
7682 *
7683 * Like the builtin extractors it reads only as far as the number goes and leaves the character
7684 * that ends it in the stream, so "1.5,2.5" gives 1.5 and leaves ",2.5" to be read next. It used to
7685 * read up to the next white space and fail the whole token. A value beyond the range is read as the
7686 * infinity or zero it rounds to, as the constructor reads it.
7687 *
7688 * Failure - no number at all, or one that stops halfway, such as "1e" or "0x" - leaves the value
7689 * untouched and sets failbit.
7690 */
7691inline std::istream& operator>>(std::istream& is, float128& value)
7692{
7693 const std::istream::sentry sentry(is);
7694 if (!sentry)
7695 return is;
7696
7697 std::streambuf* const buffer = is.rdbuf();
7698 using traits = std::char_traits<char>;
7699 std::string text;
7700 int c = buffer->sgetc();
7701 const auto take = [&]() {
7702 text += traits::to_char_type(c);
7703 buffer->sbumpc();
7704 c = buffer->sgetc();
7705 };
7706 const auto is_digit = [](int ch) { return ch >= '0' && ch <= '9'; };
7707 const auto is_hex_digit = [](int ch) { return (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F'); };
7708 const auto lower = [](int ch) { return (ch >= 'A' && ch <= 'Z') ? ch - 'A' + 'a' : ch; };
7709
7710 if (c == '+' || c == '-') {
7711 take();
7712 }
7713 const size_t body = text.size();
7714
7715 bool hex = false;
7716 if (c == '0') {
7717 take();
7718 if (c == 'x' || c == 'X') {
7719 take();
7720 hex = true;
7721 }
7722 }
7723
7724 if (text.size() == body && c != traits::eof() && lower(c) >= 'a' && lower(c) <= 'z') {
7725 // inf, infinity, nan, snan: a letter is taken only while the word so far is the start of one
7726 static constexpr const char* words[] = {"infinity", "snan", "nan"};
7727 std::string word;
7728 while (c != traits::eof()) {
7729 const std::string next = word + static_cast<char>(lower(c));
7730 bool prefix = false;
7731 for (const char* candidate : words) {
7732 prefix = prefix || std::string(candidate).compare(0, next.size(), next) == 0;
7733 }
7734 if (!prefix)
7735 break;
7736 word = next;
7737 take();
7738 }
7739 if ((word == "nan" || word == "snan") && c == '(') {
7740 take();
7741 while (c != traits::eof() && (is_digit(c) || (lower(c) >= 'a' && lower(c) <= 'z') || c == '_')) {
7742 take();
7743 }
7744 if (c == ')') {
7745 take();
7746 }
7747 }
7748 } else {
7749 const auto mantissa_digit = [&](int ch) { return hex ? is_hex_digit(ch) : is_digit(ch); };
7750 while (c != traits::eof() && mantissa_digit(c)) {
7751 take();
7752 }
7753 if (c == '.') {
7754 take();
7755 while (c != traits::eof() && mantissa_digit(c)) {
7756 take();
7757 }
7758 }
7759 if (c != traits::eof() && lower(c) == (hex ? 'p' : 'e')) {
7760 take();
7761 if (c == '+' || c == '-') {
7762 take();
7763 }
7764 while (c != traits::eof() && is_digit(c)) {
7765 take();
7766 }
7767 }
7768 }
7769 if (c == traits::eof()) {
7770 is.setstate(std::ios_base::eofbit);
7771 }
7772
7773 // The same reading the constructor makes, which has to consume every character taken.
7774 float128 parsed;
7775 const char* const first = text.data();
7776 const char* const last = first + text.size();
7777 bool ok = false;
7778 if (hex) {
7779 const std::from_chars_result result = from_chars(first + body + 2, last, parsed, std::chars_format::hex);
7780 ok = result.ec != std::errc::invalid_argument && result.ptr == last;
7781 if (ok && body != 0 && text[0] == '-') {
7782 parsed = -parsed;
7783 }
7784 } else {
7785 const std::from_chars_result result = from_chars(first, last, parsed);
7786 ok = result.ec != std::errc::invalid_argument && result.ptr == last;
7787 }
7788 if (!ok) {
7789 is.setstate(std::ios_base::failbit);
7790 return is;
7791 }
7792
7793 value = parsed;
7794 return is;
7795}
7796
7797} // namespace fp128
7798
7799namespace std
7800{
7801/**
7802 * @brief Numeric properties of fp128::float128, the binary128 interchange format.
7803 *
7804 * Specialized so that a function template written against a builtin floating point type - anything
7805 * reaching for numeric_limits<T>::epsilon() to size a tolerance, or for max() to seed a minimum -
7806 * compiles and behaves correctly when instantiated with float128.
7807 *
7808 * The values are given as encodings rather than computed, which keeps every one of them usable in
7809 * a constant expression and independent of the string parser.
7810 *
7811 * The const, volatile and const volatile forms need no specialization of their own: <limits>
7812 * already defines numeric_limits<cv T> to have the members of numeric_limits<T>.
7813 */
7814template <> class numeric_limits<fp128::float128>
7815{
7816public:
7817 static constexpr bool is_specialized = true;
7818 static constexpr bool is_signed = true;
7819 static constexpr bool is_integer = false;
7820 static constexpr bool is_exact = false;
7821 static constexpr bool has_infinity = true;
7822 static constexpr bool has_quiet_NaN = true;
7823 static constexpr bool has_signaling_NaN = true;
7824 static constexpr bool is_bounded = true;
7825 static constexpr bool is_modulo = false;
7826 /// @brief True only with FP128_IEEE_ENV, which adds the rounding directions and the exception
7827 /// flags IEEE 754 requires; the format and the default arithmetic conform either way.
7828 /// See float128::is754version2008().
7830 /// @brief Exceptions raise flags (with FP128_IEEE_ENV) but never trap.
7831 static constexpr bool traps = false;
7832 /// @brief Tininess is detected after rounding, as x86 does for double.
7833 static constexpr bool tinyness_before = false;
7834 static constexpr float_round_style round_style = round_to_nearest;
7835
7836 /// @brief Mantissa bits including the implicit leading one.
7837 static constexpr int digits = 113;
7838 /// @brief Decimal digits that survive a round trip through the type.
7839 static constexpr int digits10 = 33;
7840 /// @brief Decimal digits needed to distinguish every value of the type.
7841 static constexpr int max_digits10 = 36;
7842 static constexpr int radix = 2;
7843 static constexpr int min_exponent = -16381;
7844 static constexpr int max_exponent = 16384;
7845 static constexpr int min_exponent10 = -4931;
7846 static constexpr int max_exponent10 = 4932;
7847
7848 // has_denorm and has_denorm_loss are deprecated since C++23 but remain part of the interface a
7849 // generic caller may read, so they are provided.
7851 static constexpr float_denorm_style has_denorm = denorm_present;
7852 static constexpr bool has_denorm_loss = false;
7854
7855 /// @brief Smallest positive normal value, 2^-16382.
7856 [[nodiscard]] static constexpr fp128::float128 min() noexcept { return fp128::float128(0, 0x0001000000000000ull); }
7857 /// @brief Largest finite value, (2 - 2^-112) * 2^16383.
7858 [[nodiscard]] static constexpr fp128::float128 max() noexcept { return fp128::float128(UINT64_MAX, 0x7FFEFFFFFFFFFFFFull); }
7859 /// @brief Most negative finite value.
7860 [[nodiscard]] static constexpr fp128::float128 lowest() noexcept { return fp128::float128(UINT64_MAX, 0xFFFEFFFFFFFFFFFFull); }
7861 /// @brief Difference between one and the next larger value, 2^-112.
7862 [[nodiscard]] static constexpr fp128::float128 epsilon() noexcept { return fp128::float128(0, 0x3F8F000000000000ull); }
7863 /// @brief Largest rounding error in units in the last place, one half.
7864 [[nodiscard]] static constexpr fp128::float128 round_error() noexcept { return fp128::float128(0, 0x3FFE000000000000ull); }
7865 /// @brief Smallest positive subnormal, 2^-16494.
7866 [[nodiscard]] static constexpr fp128::float128 denorm_min() noexcept { return fp128::float128(1, 0); }
7867 [[nodiscard]] static constexpr fp128::float128 infinity() noexcept { return fp128::float128::inf(); }
7868 [[nodiscard]] static constexpr fp128::float128 quiet_NaN() noexcept { return fp128::float128::nan(); }
7869 [[nodiscard]] static constexpr fp128::float128 signaling_NaN() noexcept { return fp128::float128::signaling_nan(); }
7870};
7871
7872/**
7873 * @brief std::format support for fp128::float128.
7874 *
7875 * Accepts the whole floating point format specification: fill and alignment, a sign, the alternate
7876 * form, zero padding, a width, a precision, and any of the a, A, e, E, f, F, g and G types. An
7877 * empty specification gives the shortest text that reads back as the same value, which is what
7878 * std::format produces for a double.
7879 *
7880 * A width or precision given as a nested replacement field is not supported; both have to be
7881 * written out as digits.
7882 */
7883template <> struct formatter<fp128::float128, char>
7884{
7885 constexpr auto parse(basic_format_parse_context<char>& context)
7886 {
7887 auto it = context.begin();
7888 const auto end = context.end();
7889 if (it == end || *it == '}')
7890 return it;
7891
7892 // [[fill]align]
7893 const auto is_align = [](char c) { return c == '<' || c == '>' || c == '^'; };
7894 if (it + 1 != end && is_align(*(it + 1))) {
7895 fill = *it;
7896 align = *(it + 1);
7897 it += 2;
7898 } else if (is_align(*it)) {
7899 align = *it++;
7900 }
7901
7902 // [sign]
7903 if (it != end && (*it == '+' || *it == '-' || *it == ' '))
7904 sign = *it++;
7905
7906 // [#]
7907 if (it != end && *it == '#') {
7908 alternate = true;
7909 ++it;
7910 }
7911
7912 // [0], which is an alignment rather than a fill in its own right
7913 if (it != end && *it == '0') {
7914 zero_pad = true;
7915 ++it;
7916 }
7917
7918 // [width]
7919 while (it != end && *it >= '0' && *it <= '9')
7920 width = width * 10 + (*it++ - '0');
7921
7922 // [.precision]
7923 if (it != end && *it == '.') {
7924 ++it;
7925 precision = 0;
7926 while (it != end && *it >= '0' && *it <= '9')
7927 precision = precision * 10 + (*it++ - '0');
7928 }
7929
7930 // [type]
7931 if (it != end && *it != '}') {
7932 switch (*it) {
7933 case 'a':
7934 case 'A':
7935 case 'e':
7936 case 'E':
7937 case 'f':
7938 case 'F':
7939 case 'g':
7940 case 'G':
7941 type = *it++;
7942 break;
7943 default:
7944 throw format_error("invalid type in the format specification for float128");
7945 }
7946 }
7947
7948 if (it != end && *it != '}')
7949 throw format_error("unmatched brace in the format specification for float128");
7950 return it;
7951 }
7952
7953 template <typename FormatContext> auto format(const fp128::float128& value, FormatContext& context) const
7954 {
7955 const string text = render(value);
7956 return std::copy(text.begin(), text.end(), context.out());
7957 }
7958
7959 /// @brief Builds the text, including the padding the specification asks for.
7960 [[nodiscard]] string render(const fp128::float128& value) const
7961 {
7962 const bool uppercase = (type >= 'A' && type <= 'Z');
7963 const char style = static_cast<char>(uppercase ? (type - 'A' + 'a') : type);
7964 string text = fp128::detail::render(value, style, precision, uppercase, alternate, sign);
7965
7966 if (static_cast<int>(text.size()) >= width)
7967 return text;
7968
7969 const size_t padding = static_cast<size_t>(width) - text.size();
7970 // Zero padding goes between the sign and the digits, and only when no alignment was given.
7971 // A special value is never zero padded, the way it is not for a double either.
7972 if (zero_pad && align == 0 && !value.is_nan() && !value.is_inf()) {
7973 const size_t offset = (!text.empty() && (text[0] == '-' || text[0] == '+' || text[0] == ' ')) ? 1u : 0u;
7974 text.insert(offset, padding, '0');
7975 return text;
7976 }
7977
7978 switch (align) {
7979 case '<':
7980 text.append(padding, fill);
7981 break;
7982 case '^':
7983 text.insert(0, padding / 2, fill);
7984 text.append(padding - padding / 2, fill);
7985 break;
7986 case '>':
7987 default:
7988 // A number aligns right by default, as every arithmetic type does.
7989 text.insert(0, padding, fill);
7990 break;
7991 }
7992 return text;
7993 }
7994
7995 char fill = ' '; ///< Character the padding is made of.
7996 char align = 0; ///< One of < > ^, or zero when none was given.
7997 char sign = '-'; ///< One of + - space.
7998 char type = 0; ///< One of a A e E f F g G, or zero for the shortest form.
7999 bool alternate = false;///< The # flag: keep the point and the trailing zeros.
8000 bool zero_pad = false; ///< The 0 flag: pad with zeros after the sign.
8001 int width = 0; ///< Minimum field width.
8002 int precision = -1; ///< Digits after the point, or -1 when none was given.
8003};
8004
8005/**
8006 * @brief Hash support, so a float128 can be a key in an unordered container.
8007 *
8008 * The two zeros compare equal and therefore have to hash equal, which the raw encoding would not
8009 * do: they differ in the sign bit.
8010 */
8011template <> struct hash<fp128::float128>
8012{
8013 [[nodiscard]] size_t operator()(const fp128::float128& value) const noexcept
8014 {
8015 uint64_t low = 0, high = 0;
8016 value.get_bits(low, high);
8017 if (value.is_zero())
8018 low = high = 0;
8019
8020 // splitmix64's finalizer, applied to the two halves in turn
8021 uint64_t state = low + 0x9E3779B97F4A7C15ull;
8022 state = (state ^ (state >> 30)) * 0xBF58476D1CE4E5B9ull;
8023 state = (state ^ (state >> 27)) * 0x94D049BB133111EBull;
8024 state ^= high + 0x9E3779B97F4A7C15ull + (state << 6) + (state >> 2);
8025 state = (state ^ (state >> 30)) * 0xBF58476D1CE4E5B9ull;
8026 return static_cast<size_t>(state ^ (state >> 31));
8027 }
8028};
8029
8030/// @name Common type
8031///
8032/// float128 is wider than every builtin arithmetic type, so a mixed expression produces a
8033/// float128. Without these the default common_type would try to form the ternary operator over the
8034/// two, which is ambiguous: float128 converts to double and double converts to float128.
8035/// @{
8036template <typename T>
8037 requires is_arithmetic_v<T>
8038struct common_type<fp128::float128, T>
8039{
8041};
8042template <typename T>
8043 requires is_arithmetic_v<T>
8044struct common_type<T, fp128::float128>
8045{
8047};
8048template <> struct common_type<fp128::float128, fp128::float128>
8049{
8051};
8052/// @}
8053} // namespace std
8054
8055#endif // FP128_FLOAT128_H
Fixed capacity unsigned big integer, 32 bit limbs, least significant first.
Reduces what a math function's internal operations raise to what its result justifies.
Definition float128.h:333
T operator()(const T &result) noexcept
Records the flags a result justifies and passes the result through.
Definition float128.h:370
flag_filter(const flag_filter &)=delete
T inexact(const T &result) noexcept
The same as operator(), for a result known to be inexact without an operation having said so: an over...
Definition float128.h:358
flag_filter & operator=(const flag_filter &)=delete
Sets the exception flags aside for its lifetime, and discards whatever is raised meanwhile.
Definition float128.h:300
flag_quiet(const flag_quiet &)=delete
flag_quiet & operator=(const flag_quiet &)=delete
128 bit floating point class.
Definition float128.h:672
friend constexpr bool islessgreater(const float128 &x, const float128 &y) noexcept
x < y or x > y, false when either is a NaN.
Definition float128.h:6020
static constexpr int32_t LOG1P_TERMS
Terms of the log1p_small() series. |s| stays below 2^-4.9, so s^24 is past the last bit.
Definition float128.h:4460
friend constexpr float128 fmaxmag(const float128 &x, const float128 &y) noexcept
maxNumMag: whichever of x and y has the larger magnitude, or fmax() when they tie.
Definition float128.h:6079
static constexpr void shift_right_jam128_extra(uint64_t &l, uint64_t &h, uint64_t &extra, int32_t dist) noexcept
Shifts a significand and its extra word right, keeping a sticky record of what fell off.
Definition float128.h:2199
friend constexpr bool totalorder(const float128 &x, const float128 &y) noexcept
totalOrder(x, y): true when x precedes y, or equals it, in the IEEE 754 total order.
Definition float128.h:6059
constexpr float128 operator>>(T shift) const noexcept
Performs right shift operation.
Definition float128.h:1429
static constexpr float128 egamma() noexcept
The Euler-Mascheroni constant.
Definition float128.h:2974
friend constexpr float128 fabs(const float128 &x) noexcept
Returns the absolute value of x.
Definition float128.h:3422
static float128 pown_magnitude(const float128 &a, int32_t n) noexcept
a^n by repeated squaring, for a positive finite a.
Definition float128.h:4307
friend constexpr float128 scalbn(const float128 &x, int n) noexcept
x * 2^n, the same operation ldexp performs.
Definition float128.h:6181
friend float128 acos(float128 x) noexcept
Calculate the inverse cosine function.
Definition float128.h:5245
friend class fp128_gtest
Definition float128.h:675
static constexpr int32_t GAMMA_RECURRENCE_LIMIT
Below this magnitude lgamma() and tgamma() move the argument next to two by the recurrence.
Definition float128.h:6394
friend float128 atan2(float128 y, float128 x) noexcept
Calculate the inverse tangent function of the ratio y / x.
Definition float128.h:5339
static constexpr int32_t COS_TERMS
Terms of the cosine series cos1() runs. Up to pi/4, x^32/32! is below 2^-125.
Definition float128.h:4815
friend constexpr bool isfinite(const float128 &x) noexcept
Tests whether x is finite (not infinite and not NaN).
Definition float128.h:5765
static constexpr float128 nan()
Return the quiet (non-signaling) NaN constant.
Definition float128.h:2879
friend float128 log1p(float128 x) noexcept
Calculates the natural Log (base e) of 1 + x: log(1 + x)
Definition float128.h:4744
friend float128 hypot(const float128 &x, const float128 &y) noexcept
Calculates the hypotenuse. i.e. sqrt(x^2 + y^2)
Definition float128.h:3799
static constexpr float128 from_long_double(long double x) noexcept
Converts a long double wider than a double, exactly.
Definition float128.h:1244
static constexpr int32_t SCALE_LIMIT
Largest scaling a shift or ldexp() ever needs: enough to take the largest finite value below half the...
Definition float128.h:1367
static constexpr float128 sqrt_2() noexcept
Returns a value of sqrt(2)
Definition float128.h:2918
constexpr bool is_signaling() const
Tests if this value is a signaling NaN.
Definition float128.h:1917
friend constexpr float128 ldexp(float128 x, int exp) noexcept
Multiplies a floating-point number by an integral power of two.
Definition float128.h:5948
friend constexpr bool operator==(const float128 &lhs, const T &rhs) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition float128.h:3247
static constexpr bool fixed_is_zero(const uint64_t frac[FIXED_WORDS]) noexcept
True when every word of the fixed point fraction is zero.
Definition float128.h:2592
static constexpr bool is754version1985(void)
Returns false; this type does not conform to IEEE 754-1985.
Definition float128.h:3068
friend float128 sinh(const float128 x) noexcept
Calculate the hyperbolic sine function Use the exponent function which produces more accurate results...
Definition float128.h:5393
static constexpr float128 exp10(int32_t e) noexcept
Calculates 10^e.
Definition float128.h:3000
friend constexpr bool operator<=(const T &lhs, const float128 &rhs) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition float128.h:3333
constexpr bool is_positive() const noexcept
Returns true if the value is positive (including zero and NaN)
Definition float128.h:1873
constexpr void set_fraction_bits(uint64_t f) noexcept
Sets the upper 48 bits of the fraction, leaving the exponent and the sign alone.
Definition float128.h:2042
friend constexpr float128 operator<<(const T &lhs, const float128 &rhs) noexcept
Shifts a scalar left by a float128 shift count, scaling it by a power of two.
Definition float128.h:3198
constexpr float128 & operator+=(const T &rhs)
Add a value to this object.
Definition float128.h:1559
constexpr uint64_t truncated_magnitude(bool &overflow) const noexcept
The integer part of |x|, truncated towards zero.
Definition float128.h:1141
static constexpr void wide_add(uint64_t *a, const uint64_t *b) noexcept
Adds b into a. The accumulator is wide enough that the sum cannot carry out.
Definition float128.h:2723
friend float128 pow(const float128 &x, const float128 &y) noexcept
Computes x to the power of y.
Definition float128.h:4359
friend constexpr float128 sqr(float128 x) noexcept
Calculates the square of a value. i.e. x^2.
Definition float128.h:3830
friend void erf_constants(float128 *a, int32_t count)
Calculates the Maclaurin series constants for the erf function. The array will hold 1 / (n!...
Definition float128.h:5607
friend constexpr float128 operator>>(const T &lhs, const float128 &rhs) noexcept
Shifts a scalar right by a float128 shift count, scaling it by a power of two. The left operand is wi...
Definition float128.h:3211
friend constexpr bool issignaling(const float128 &x) noexcept
isSignaling: true for a signaling NaN.
Definition float128.h:6107
constexpr bool is_nan() const
Tests if this value is a NaN.
Definition float128.h:1908
constexpr float128 & operator=(const float128 &rhs) noexcept
Assignment operator.
Definition float128.h:937
friend float128 nan(const char *payload) noexcept
A quiet NaN carrying the payload spelled out in the argument.
Definition float128.h:6124
friend constexpr float128 operator-(float128 lhs, const T &rhs) noexcept
subtracts the right hand side operand to this object to and returns the result.
Definition float128.h:3116
static float128 abs_sin_pi(const float128 &x) noexcept
|sin(pi * x)| for a finite x that is not an integer, without the error of rounding pi * x.
Definition float128.h:6500
constexpr bool is_special() const
return true when the value is either an inf or nan
Definition float128.h:1945
constexpr void set_exponent(int32_t e) noexcept
Set the exponent.
Definition float128.h:2102
constexpr float128 get_fraction() const
Return the fraction part as a float128.
Definition float128.h:1985
friend float128 reciprocal(const float128 &x) noexcept
Calculates the reciprocal of a value, 1 / x, correctly rounded.
Definition float128.h:4017
friend constexpr bool operator>=(const float128 &lhs, const T &rhs) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition float128.h:3389
static constexpr int32_t EXP_TERMS
Calculates the exponent of x: e Using the Maclaurin series expansion, the formula is: 1 2 3 x x x exp...
Definition float128.h:4153
constexpr float128 & operator*=(const float128 &rhs) noexcept
Multiply a value to this object.
Definition float128.h:1577
friend constexpr float128 rint(const float128 &x) noexcept
x rounded to an integral value in the current direction, raising inexact when that changes it.
Definition float128.h:6165
static constexpr float128 log10_e() noexcept
Base 10 logarithm of e.
Definition float128.h:2966
static constexpr bool wide_place(uint64_t *acc, const uint64_t *src, int32_t words, int32_t offset) noexcept
Writes a value into a zeroed accumulator, shifted to a given bit position.
Definition float128.h:2680
constexpr float128(double x) noexcept
Constructor from the double type.
Definition float128.h:765
_float128_bits high_bits
Upper 64 bits (bit-field view).
Definition float128.h:724
constexpr bool operator!() const noexcept
Logical not (!). Opposite of operator bool. Uses is_zero() rather than testing the raw words: negativ...
Definition float128.h:1856
constexpr void set_sign(uint64_t s) noexcept
Sets the sign.
Definition float128.h:2050
friend constexpr bool operator==(const T &lhs, const float128 &rhs) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition float128.h:3252
static void reduce_half_pi(const float128 &x, int64_t n, float128 &hi, float128 &lo) noexcept
Subtracts n*(pi/2) from x, leaving the residual as an unevaluated sum.
Definition float128.h:5113
constexpr float128(uint64_t lf, uint64_t hf, uint32_t e, uint32_t s) noexcept
Low level constructor.
Definition float128.h:757
friend constexpr float128 operator-(const T &lhs, const float128 &rhs) noexcept
Subtracts a float128 from a scalar.
Definition float128.h:3164
friend constexpr bool operator!=(const float128 &lhs, const T &rhs) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition float128.h:3267
constexpr bool is_zero() const noexcept
Returns true if and only if the value is ±0.
Definition float128.h:1883
static constexpr float128 propagate_nan(const float128 &a, const float128 &b, const float128 &c) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition float128.h:2465
static constexpr float128 norm_round_pack(uint32_t sign, int32_t e, uint64_t l, uint64_t h, bool sticky) noexcept
Normalizes an exact non negative 128 bit significand and rounds it once.
Definition float128.h:2388
friend constexpr float128 fdim(const float128 &x, const float128 &y) noexcept
Determines the positive difference between the first and second values.
Definition float128.h:3745
static constexpr float128 half() noexcept
Returns a value of 0.5.
Definition float128.h:2933
static constexpr bool log_special(const float128 &x, float128 &result) noexcept
The arguments every logarithm treats alike (IEEE 754-2008 9.2.1).
Definition float128.h:4435
constexpr float128 & operator*=(const T &rhs)
Multiply a value to this object.
Definition float128.h:1749
friend constexpr bool iszero(const float128 &x) noexcept
isZero: true for either zero.
Definition float128.h:6111
friend constexpr bool islessequal(const float128 &x, const float128 &y) noexcept
x <= y, false when either is a NaN.
Definition float128.h:6015
friend constexpr float128 fmin(const float128 &x, const float128 &y) noexcept
Returns the minimum between x and y.
Definition float128.h:3757
static constexpr bool is754version2008(void)
Whether the type conforms to IEEE 754-2008 (binary128).
Definition float128.h:3078
static constexpr float128 ln10() noexcept
Natural logarithm of 10.
Definition float128.h:2962
static constexpr int32_t square_compare(uint64_t rl, uint64_t rh, const uint64_t n[4]) noexcept
Square of a 113 bit significand compared with a 256 bit value.
Definition float128.h:3838
friend float128 expm1(const float128 &x) noexcept
Calculates the exponent of x and reduces 1 from the result: (e^x) - 1.
Definition float128.h:4269
friend constexpr bool operator<=(const float128 &lhs, const float128 &rhs) noexcept
Return true this object is small or equal than the other.
Definition float128.h:3318
friend constexpr bool operator>(const T &lhs, const float128 &rhs) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition float128.h:3371
constexpr float128() noexcept
Default constructor, creates an instance with a value of zero.
Definition float128.h:732
static constexpr uint64_t norm_product(uint64_t &l, uint64_t &h, int32_t &e, bool sticky) noexcept
Normalizes the product of two mantissas to bit 112, handing back the bits it drops.
Definition float128.h:2779
friend constexpr bool operator<(const float128 &lhs, const T &rhs) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition float128.h:3308
static constexpr float128 from_fraction128(uint64_t low, uint64_t high) noexcept
Builds a float128 from a 128 bit fraction, a value in [0,1).
Definition float128.h:2414
static int32_t reduce_large(const float128 &x, float128 &hi, float128 &lo) noexcept
Reduces an argument of any size: x = n * pi/2 + r, with |r| <= pi/4 (Payne and Hanek).
Definition float128.h:4948
friend constexpr bool isless(const float128 &x, const float128 &y) noexcept
x < y, false when either is a NaN.
Definition float128.h:6010
friend float128 tan(float128 x) noexcept
Calculate the tangent function tan(x) = sin(x)/cos(x)
Definition float128.h:5267
friend float128 exp2(const float128 &x) noexcept
Computes 2 to the power of x.
Definition float128.h:4232
static float128 lgamma_near_two(const float128 &z) noexcept
lgamma(2 + z) for |z| <= 1/2, accurate relative to the result.
Definition float128.h:6418
static void quick_two_sum(const float128 &a, const float128 &b, float128 &sum, float128 &err) noexcept
Exact sum of two values whose magnitudes are ordered.
Definition float128.h:4898
friend constexpr float128 copysign(const float128 &x, const float128 &y) noexcept
returns the value of x with the sign of y.
Definition float128.h:3633
constexpr float128 & operator-=(const float128 &rhs) noexcept
Subtract a value from this object.
Definition float128.h:1565
constexpr float128 & operator-=(const T &rhs)
Subtract a value from this object.
Definition float128.h:1571
friend float128 double_factorial(int x) noexcept
Returns the double factorial of a number, x!! = x * (x - 2) * (x - 4) * ...
Definition float128.h:4109
static constexpr float128 round_integral(const float128 &x, detail::rounding mode, bool ties_away, bool signal_inexact) noexcept
Rounds to an integral value (IEEE 754-2008 roundToIntegral, 5.3.1).
Definition float128.h:3448
static constexpr float128 propagate_nan(const float128 &a, const float128 &b) noexcept
The result of an operation with a NaN operand (IEEE 754-2008 6.2).
Definition float128.h:2458
friend constexpr int32_t lrint(const float128 &x) noexcept
Rounds x to an integer in the current rounding direction and returns it as int32_t.
Definition float128.h:3589
friend float128 operator/(const T &lhs, const float128 &rhs)
Divides a scalar by a float128.
Definition float128.h:3178
friend constexpr float128 fma(float128 x, float128 y, float128 z) noexcept
Computes (x * y) + z with a single rounding at the end.
Definition float128.h:5785
friend float128 tanh(const float128 x) noexcept
Calculates the hyperbolic tangent e^x - e^(-x) tanh(x) = ---------— e^x + e^(-x)
Definition float128.h:5533
constexpr bool is_subnormal() const noexcept
Tests if the value is subnormal: non zero, and below the smallest normal magnitude.
Definition float128.h:1898
static constexpr float128 inv_sqrt_3() noexcept
1/sqrt(3)
Definition float128.h:2972
constexpr int32_t get_exponent() const noexcept
Returns the exponent of the object - like the base 2 exponent of a floating point A value of 2....
Definition float128.h:2097
constexpr float128_class_t get_class() const noexcept
Classifies the float128 value according to IEEE 754.
Definition float128.h:2075
static constexpr int32_t wide_cmp(const uint64_t *a, const uint64_t *b) noexcept
Three way comparison of two accumulators.
Definition float128.h:2752
friend float128 cos(float128 x) noexcept
Calculate the cosine function Ultimately uses sin1() with a reduced range of [-pi/4,...
Definition float128.h:5210
friend float128 operator/(float128 lhs, const T &rhs)
Divides this object by the right hand side operand and returns the result.
Definition float128.h:3138
constexpr bool is_inf() const
Tests if this value is an Infinite (negative or positive)
Definition float128.h:1927
static constexpr float128 log10_2() noexcept
Base 10 logarithm of 2.
Definition float128.h:2968
friend constexpr bool operator!=(const T &lhs, const float128 &rhs) noexcept
Definition float128.h:3272
constexpr void total_order_key(uint64_t &l, uint64_t &h) const noexcept
The encoding as a key whose unsigned order is the total order of IEEE 754-2008 5.10.
Definition float128.h:6041
friend constexpr float128 operator+(float128 lhs, const T &rhs) noexcept
Adds 2 values and returns the result.
Definition float128.h:3105
friend float128 pow(const float128 &x, int32_t y) noexcept
Computes x to the power of y (IEEE 754-2008 pown)
Definition float128.h:4333
static int32_t reduce_trig(const float128 &x, float128 &hi, float128 &lo) noexcept
Reduces x to [-pi/4, pi/4], as an unevaluated sum, and returns the quadrant.
Definition float128.h:5082
uint64_t high
Upper 64 bits (raw).
Definition float128.h:723
static constexpr float128 round_pack(uint32_t sign, int32_t e, uint64_t l, uint64_t h, uint64_t extra, detail::rounding mode) noexcept
Definition float128.h:2354
friend constexpr bool isinf(const float128 &x)
Tests if the value is an Infinite (negative or positive)
Definition float128.h:3415
static constexpr float128 round_pack(uint32_t sign, int32_t e, uint64_t l, uint64_t h, uint64_t extra) noexcept
Rounds an exact result once, in the current rounding direction, and encodes it.
Definition float128.h:2342
friend constexpr bool iscanonical(const float128 &) noexcept
isCanonical: always true, every binary128 encoding is canonical.
Definition float128.h:6105
friend float128 tgamma(float128 x) noexcept
The gamma function.
Definition float128.h:6626
friend float128 acosh(const float128 x) noexcept
Calculates the inverse hyperbolic cosine For x >= 1: acosh(x) = log(x + sqrt(x^2 - 1)) For x < 1,...
Definition float128.h:5498
static float128 log1p_small(const float128 &t) noexcept
Natural logarithm of 1+t for |t| <= 2^-4, accurate relative to the result.
Definition float128.h:4479
static constexpr void mul128to256(uint64_t al, uint64_t ah, uint64_t bl, uint64_t bh, uint64_t res[4]) noexcept
Full 256 bit product of two 128 bit values.
Definition float128.h:2630
friend float128 cos1(const float128 &x) noexcept
Calculate the cosine function over a limited range [-0.5pi, 0.5pi].
Definition float128.h:4839
constexpr bool is_exponent_of_2() const
Tests if the value is an exponent of 2 (fraction part is zero)
Definition float128.h:1936
void to_e_format(char *str, int32_t buff_size) const
Writes the value in scientific notation into a caller supplied buffer.
Definition float128.h:1349
constexpr bool is_normal() const noexcept
Tests if the value is normal (not zero, subnormal, infinite, or NaN)
Definition float128.h:1903
friend float128 remainder(const float128 &x, const float128 &y) noexcept
IEEE 754 remainder: x - n*y with n the quotient rounded to the nearest even integer.
Definition float128.h:6305
friend float128 cbrt(const float128 x, uint32_t iterations) noexcept
Calculates the cube root. Uses the Halley's method.
Definition float128.h:3958
friend constexpr float128 operator*(const T &lhs, const float128 &rhs) noexcept
Multiplies a scalar and a float128, in that order.
Definition float128.h:3171
friend constexpr bool operator<=(const float128 &lhs, const T &rhs) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition float128.h:3330
static constexpr bool round_increment(detail::rounding mode, uint32_t sign, uint64_t extra) noexcept
Whether rounding should add one unit in the last place.
Definition float128.h:2267
constexpr void set_components(uint64_t l, uint64_t h, int32_t e, uint32_t s) noexcept
Stores a significand and exponent, rounding when the value is subnormal.
Definition float128.h:2430
friend constexpr float128 fminmag(const float128 &x, const float128 &y) noexcept
minNumMag: whichever of x and y has the smaller magnitude, or fmin() when they tie.
Definition float128.h:6092
constexpr uint64_t get_fraction_bits() const noexcept
Reads the upper 48 bits of the fraction out of the high QWORD.
Definition float128.h:2037
constexpr float128 & square() noexcept
Squares this object in place.
Definition float128.h:1684
friend void fact_reciprocal(int x, float128 &res) noexcept
Factorial reciprocal (inverse). Calculates 1 / x! Maximum supported value of x is 50.
Definition float128.h:4029
friend float128 sqrt(const float128 &x, uint32_t iterations) noexcept
Calculates the square root, correctly rounded.
Definition float128.h:3872
static constexpr float128 signaling_nan()
Return a signaling NaN.
Definition float128.h:2888
static float128 fmod_magnitude(const float128 &x, const float128 &y, uint64_t &quotient, int32_t &half) noexcept
|x| mod |y|, along with the low bits of the quotient it implies.
Definition float128.h:6235
constexpr float128 & operator+=(const float128 &rhs) noexcept
Add a value to this object.
Definition float128.h:1451
static constexpr float128 quarter_pi()
Return the value of pi / 4.
Definition float128.h:2903
friend constexpr float128 modf(const float128 &x, float128 *iptr) noexcept
Split into integer and fraction parts. Both results carry the sign of the input variable.
Definition float128.h:3720
static constexpr float128 log2_e() noexcept
Base 2 logarithm of e.
Definition float128.h:2964
static constexpr int32_t LGAMMA_NEAR_TWO_TERMS
Terms of the series lgamma_near_two() runs. For |z| <= 1/2 the last is below 2^-120 of the sum.
Definition float128.h:6392
static constexpr float128 phi() noexcept
The golden ratio.
Definition float128.h:2976
friend float128 log10(float128 x) noexcept
Calculates Log base 10 of x: log10(x)
Definition float128.h:4700
static constexpr float128 sqrt_3() noexcept
Square root of 3.
Definition float128.h:2970
friend float128 atanh(const float128 x) noexcept
Calculates the inverse hyperbolic tangent 1 + x atanh(x) = 0.5 * log( --—) 1 - x.
Definition float128.h:5569
constexpr float128 & operator=(float128 &&rhs) noexcept
Move assignment operator.
Definition float128.h:948
float128 & operator/=(const T &rhs)
Divide this object by a value.
Definition float128.h:1842
friend constexpr bool isgreaterequal(const float128 &x, const float128 &y) noexcept
x >= y, false when either is a NaN.
Definition float128.h:6005
static constexpr float128 ln2() noexcept
Natural logarithm of 2.
Definition float128.h:2960
constexpr bool fraction_to_fixed(uint64_t frac[FIXED_WORDS]) const noexcept
Expands the fraction part of this value into an exact fixed point number.
Definition float128.h:2524
friend constexpr float128 nan(const float128 &)
Return the NaN constant.
Definition float128.h:3399
constexpr ~float128()=default
Destructor.
static constexpr int32_t wide_msb(const uint64_t *a, int32_t words) noexcept
Index of the highest set bit of a multi word value, or -1 when it is zero.
Definition float128.h:2658
constexpr void invert_sign() noexcept
Inverts the sign.
Definition float128.h:2046
constexpr float128(uint64_t l, uint64_t h) noexcept
Low level constructor.
Definition float128.h:749
friend constexpr bool operator!=(const float128 &lhs, const float128 &rhs) noexcept
Return true when objects are not equal. Can be used as logical XOR.
Definition float128.h:3262
static constexpr float128 inv_sqrt_pi() noexcept
1/sqrt(pi)
Definition float128.h:2958
friend constexpr float128 operator*(float128 lhs, const T &rhs) noexcept
Multiplies the right hand side operand with this object to and returns the result.
Definition float128.h:3127
friend float128 lgamma(float128 x) noexcept
Natural logarithm of the absolute value of the gamma function.
Definition float128.h:6534
static constexpr float128 quiet_nan(const float128 &x) noexcept
x with its quiet bit set. The payload, and the sign, are kept.
Definition float128.h:2445
friend constexpr float128 scalbln(const float128 &x, long n) noexcept
x * 2^n for a long exponent, clamped to what the format can reach.
Definition float128.h:6183
friend constexpr float128 fmax(const float128 &x, const float128 &y) noexcept
Returns the maximum between x and y.
Definition float128.h:3781
friend constexpr int32_t ilogb(const float128 &x) noexcept
Retrieves an integer that represents the base-2 exponent of the specified value.
Definition float128.h:3609
friend float128 exp(const float128 &x) noexcept
Computes e to the power of x.
Definition float128.h:4190
friend constexpr float128 frexp(float128 x, int *expptr) noexcept
Gets the mantissa and exponent of a floating-point number.
Definition float128.h:5923
static constexpr float128 propagate_nan(const float128 &a) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition float128.h:2472
static constexpr int32_t WIDE_TOP
Bit the leading one of the larger operand is placed on.
Definition float128.h:2620
constexpr float128 operator-() const noexcept
Unary -. Returns a copy of the object with sign inverted.
Definition float128.h:1864
uint64_t low
Lower 64 bits of the float128 encoding.
Definition float128.h:721
constexpr I to_integer() const noexcept
Converts to an integer type, truncating towards zero.
Definition float128.h:1162
friend constexpr bool operator>(const float128 &lhs, const T &rhs) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition float128.h:3368
constexpr void get_bits(uint64_t &l, uint64_t &h) const noexcept
Reads the raw binary128 encoding.
Definition float128.h:2066
float128(const std::string &x) noexcept
Constructor from std::string. Allows creating very high precision values. Much slower than the other ...
Definition float128.h:922
constexpr uint64_t nan_payload_top(int32_t shift) const noexcept
The top of a NaN's payload, for a narrower format to carry.
Definition float128.h:1058
friend float128 cosh(const float128 x) noexcept
Calculate the hyperbolic cosine function over a limited range [-0.5pi, 0.5pi] e^x + e^(-x) cosh(x) = ...
Definition float128.h:5474
constexpr uint64_t get_exponent_bits() const noexcept
Reads the biased exponent field out of the high QWORD.
Definition float128.h:2027
static constexpr float128 nextDown(float128 x)
Produces the closest value smaller than x.
Definition float128.h:2837
friend float128 log(float128 x) noexcept
Calculates the natural Log (base e) of x: log(x)
Definition float128.h:4513
static constexpr float128 one() noexcept
Returns a value of 1.
Definition float128.h:2928
constexpr float128 operator<<(T shift) const noexcept
Performs left shift operation. Hinted rather than forced, see operator>> above.
Definition float128.h:1440
static constexpr float128 exp10_double_word(int32_t e) noexcept
The power of exp10(), for an e whose result is inside the range of the format.
Definition float128.h:3023
static constexpr float128 inv_pi() noexcept
1/pi
Definition float128.h:2956
constexpr bool is_int() const
Returns if the value is an integer (fraction is zero).
Definition float128.h:1954
static constexpr float128 pi()
Return the value of pi.
Definition float128.h:2893
friend float128 sin1(float128 x) noexcept
Calculate the sine function over a limited range [-0.5pi, 0.5pi] Using the Maclaurin series expansion...
Definition float128.h:4790
friend constexpr bool totalordermag(const float128 &x, const float128 &y) noexcept
totalOrderMag(x, y): totalorder() of the absolute values.
Definition float128.h:6067
friend constexpr float128 nearbyint(const float128 &x) noexcept
x rounded to an integral value in the current direction.
Definition float128.h:6170
constexpr narrowed narrow() const noexcept
Rounds this finite, non zero value to a narrower binary format.
Definition float128.h:990
static void two_sum(const float128 &a, const float128 &b, float128 &sum, float128 &err) noexcept
Exact sum of two values, as a rounded sum and the error it made.
Definition float128.h:4884
static constexpr float128 e()
Return the value of e.
Definition float128.h:2908
friend constexpr bool isgreater(const float128 &x, const float128 &y) noexcept
x > y, false rather than unordered when either is a NaN.
Definition float128.h:6000
static constexpr uint64_t MAX_SIG_HIGH
The largest finite magnitude's significand, high QWORD, with its leading one at bit 48.
Definition float128.h:2277
friend constexpr bool operator>(const float128 &lhs, const float128 &rhs) noexcept
Return true this object is larger than the other.
Definition float128.h:3340
static constexpr int32_t WIDE_WORDS
Words in the accumulator.
Definition float128.h:2614
static constexpr int32_t STIRLING_TERMS
Terms of the Stirling series lgamma() runs. Sixteen reach 2^-119 for an argument of 32.
Definition float128.h:6390
static constexpr void wide_dec(uint64_t *a) noexcept
Subtracts one from the accumulator, which must not be zero.
Definition float128.h:2743
constexpr float128(T x) noexcept
Generic constructor for integral and floating-point types.
Definition float128.h:828
static int64_t quadrant_of(const float128 &x) noexcept
Nearest integer to x / (pi/2), the quadrant the argument falls in.
Definition float128.h:4916
static constexpr float128 inf()
Return the infinite constant.
Definition float128.h:2874
constexpr float128(float128 &&rhs) noexcept
Move constructor Doesn't modify the right hand side object. Acts like a copy constructor.
Definition float128.h:743
constexpr float128 & operator>>=(int32_t shift) noexcept
Shift right this object, dividing it by a power of two.
Definition float128.h:1374
constexpr void get_components(uint64_t &l, uint64_t &h, int32_t &e, uint32_t &s) const noexcept
break the float into its components. Normalizes subnormal values
Definition float128.h:2129
constexpr int32_t get_bit(uint32_t bit) const noexcept
get a specific bit within the float128 data
Definition float128.h:1975
friend float128 fmod(const float128 &x, const float128 &y) noexcept
Performs the fmod() function, similar to libc's fmod(), returns the remainder of a division x/root.
Definition float128.h:3645
friend constexpr float128 round(const float128 &x) noexcept
Rounds towards the nearest integer. The halfway value (0.5) is rounded away from zero.
Definition float128.h:3564
friend constexpr float128 nexttoward(const float128 &x, const float128 &y) noexcept
The neighbour of x towards y. The same as nextafter: there is no wider type to convert from.
Definition float128.h:6214
static constexpr float128 two_pi() noexcept
2*pi
Definition float128.h:2954
static constexpr float128 round_pack_edge(uint32_t sign, int32_t exp, uint64_t l, uint64_t h, uint64_t extra, detail::rounding mode) noexcept
The slow half of round_pack(): results that overflow or are subnormal.
Definition float128.h:2289
constexpr float128 operator+() const noexcept
Unary +. Returns a copy of the object.
Definition float128.h:1860
static constexpr float128 nextUp(float128 x)
Produces the closest value larger than x nextUp(x) is the least floating-point number in the format o...
Definition float128.h:2800
friend float128 erf(float128 x) noexcept
Computes the error function of a value. The erf function return a value in the range -1....
Definition float128.h:5626
friend float128 asin(float128 x) noexcept
Calculate the inverse sine function.
Definition float128.h:5177
friend constexpr int64_t llround(const float128 &x) noexcept
Rounds towards the nearest integer. The halfway value (0.5) is rounded away from zero.
Definition float128.h:3583
friend constexpr bool isunordered(const float128 &x, const float128 &y) noexcept
True when either operand is a NaN, so that the two do not compare in any order.
Definition float128.h:5993
static float128 exp_reduced(const float128 &r) noexcept
e to the power of a reduced argument, |r| <= ln2/2.
Definition float128.h:4160
friend float128 hypot(const float128 &x, const float128 &y, const float128 &z) noexcept
Length of the diagonal of a box, computed without an intermediate overflow.
Definition float128.h:6365
friend constexpr int fpclassify(const float128 &x) noexcept
One of FP_NAN, FP_INFINITE, FP_ZERO, FP_SUBNORMAL or FP_NORMAL.
Definition float128.h:5975
friend float128 log2(float128 x) noexcept
Calculates the Log base 2 of x: y = log2(x)
Definition float128.h:4542
friend constexpr int32_t lround(const float128 &x) noexcept
Rounds towards the nearest integer. The halfway value (0.5) is rounded away from zero.
Definition float128.h:3597
friend float128 erfc(float128 x) noexcept
Computes the complementary error function, 1 - erf(x).
Definition float128.h:5708
static constexpr float128 tenth() noexcept
Return 0.1 using maximum precision.
Definition float128.h:2938
static constexpr int32_t FIXED_WORDS
Normalize the fraction so the msb (unity bit) is on bit 112. The fraction value must contain the unit...
Definition float128.h:2507
constexpr void set_exponent_bits(uint64_t e) noexcept
Sets the biased exponent field, leaving the fraction and the sign alone.
Definition float128.h:2032
float128(const char *x) noexcept
Construct from a string Allows creating very high precision values, approximately 34 decimal digits....
Definition float128.h:884
static constexpr float128 log1p_small_limit() noexcept
Largest |t| the log1p_small() series is used for. Chosen so twelve terms suffice.
Definition float128.h:4458
friend constexpr int64_t llrint(const float128 &x) noexcept
Rounds x to an integer in the current rounding direction and returns it as int64_t.
Definition float128.h:3575
constexpr float128 & operator<<=(int32_t shift) noexcept
Shift left this object, multiplying it by a power of two.
Definition float128.h:1398
static constexpr float128 invalid_operation() noexcept
The result of an invalid operation on non NaN operands, such as inf - inf or 0 / 0.
Definition float128.h:2483
friend constexpr float128 abs(const float128 &x) noexcept
Absolute value, the name <cmath> gives the floating point overload alongside fabs.
Definition float128.h:6690
float128 & operator/=(const float128 &rhs)
Divide this object by a value.
Definition float128.h:1755
static constexpr bool is_odd_int(const float128 &x) noexcept
True when x is an integer whose last place is one, which is the parity a tie needs.
Definition float128.h:6140
static constexpr float128 half_pi()
Return the value of pi / 2.
Definition float128.h:2898
friend constexpr bool signbit(const float128 &x) noexcept
True when the sign bit is set, including for -0 and for a negative NaN.
Definition float128.h:5971
friend constexpr float128 floor(const float128 &x) noexcept
Performs the floor() function, similar to libc's floor(), rounds down towards -infinity.
Definition float128.h:3536
friend constexpr float128 operator+(const T &lhs, const float128 &rhs) noexcept
Adds a scalar and a float128, in that order.
Definition float128.h:3157
static constexpr uint64_t fixed_mul_extract(uint64_t frac[FIXED_WORDS], uint64_t mul) noexcept
Multiplies the fixed point fraction by a small value and returns the part that crossed the binary poi...
Definition float128.h:2579
friend constexpr bool operator>=(const float128 &lhs, const float128 &rhs) noexcept
Return true this object is larger or equal than the other.
Definition float128.h:3378
static constexpr I integral_to(const float128 &x) noexcept
Converts an integral value to an integer type, the way the C rounding functions do.
Definition float128.h:3522
friend float128 sin(float128 x) noexcept
Definition float128.h:5140
friend constexpr float128 ceil(const float128 &x) noexcept
Performs the ceil() function, similar to libc's ceil(), rounds up towards infinity.
Definition float128.h:3545
static float128 exp10_filtered(int32_t e) noexcept
exp10_double_word() at run time, raising only the exceptions the result justifies.
Definition float128.h:3061
constexpr bool is_negative() const noexcept
Returns true if the value is negative (including zero and NaN).
Definition float128.h:1878
friend constexpr bool operator<(const T &lhs, const float128 &rhs) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition float128.h:3311
friend float128 remquo(const float128 &x, const float128 &y, int *quo) noexcept
The IEEE remainder together with the low bits of the quotient.
Definition float128.h:6318
friend constexpr bool operator<(const float128 &lhs, const float128 &rhs) noexcept
Return true if this object is small than the other.
Definition float128.h:3279
friend constexpr bool operator>=(const T &lhs, const float128 &rhs) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition float128.h:3392
friend float128 logb(float128 x) noexcept
Calculates Log base 2 of x as an integer ignoring the sign of x. Similar to: floor(log2(fabs(x)))
Definition float128.h:4720
friend constexpr bool isnormal(const float128 &x) noexcept
True when x is neither zero, subnormal, infinite nor NaN.
Definition float128.h:5973
friend constexpr bool issubnormal(const float128 &x) noexcept
isSubnormal: true for a subnormal value, which zero is not.
Definition float128.h:6109
static constexpr void shift_right_jam128(uint64_t &l, uint64_t &h, int32_t dist) noexcept
Shifts a 128 bit value right, jamming any set bit that falls off into the lowest bit.
Definition float128.h:2243
friend constexpr bool isnan(const float128 &x)
Tests if the value is a NaN.
Definition float128.h:3405
static constexpr uint32_t exact_zero_sign() noexcept
The sign of an exact zero sum of two operands of opposite sign (IEEE 754-2008 6.3).
Definition float128.h:2493
constexpr float128(const float128 &rhs) noexcept
Copy constructor.
Definition float128.h:737
static constexpr int32_t LOG2_TERMS
Number of Mercator series terms log2() needs.
Definition float128.h:2165
constexpr uint32_t get_sign() const noexcept
Gets the sign.
Definition float128.h:2054
friend constexpr float128 trunc(const float128 &x) noexcept
Rounds towards zero.
Definition float128.h:3554
friend constexpr bool operator==(const float128 &lhs, const float128 &rhs) noexcept
Compare logical/bitwise equal.
Definition float128.h:3226
static constexpr void wide_sub(uint64_t *a, const uint64_t *b) noexcept
Subtracts b from a, which must not be smaller.
Definition float128.h:2731
friend float128 asinh(const float128 x) noexcept
Calculates the inverse hyperbolic sine For positive x: asinh(x) = log(x + sqrt(x^2 + 1)) For negative...
Definition float128.h:5429
static constexpr int32_t WIDE_BITS
Definition float128.h:2615
friend float128 atan(float128 x) noexcept
Calculate the inverse tangent function.
Definition float128.h:5273
friend constexpr float128 nextafter(const float128 &x, const float128 &y) noexcept
The representable value next to x in the direction of y.
Definition float128.h:6205
constexpr bool is_finite() const noexcept
Returns true if and only if x is zero, subnormal or normal (not infinite or NaN).
Definition float128.h:1888
constexpr bool is_zero() const noexcept
Returns true if the value is zero.
constexpr void get_components(uint64_t &l, uint64_t &h) const noexcept
Extracts the low and high QWORD.
static constexpr bool has_denorm_loss
Definition float128.h:7852
static constexpr fp128::float128 quiet_NaN() noexcept
Definition float128.h:7868
static constexpr bool has_quiet_NaN
Definition float128.h:7822
static constexpr fp128::float128 denorm_min() noexcept
Smallest positive subnormal, 2^-16494.
Definition float128.h:7866
static constexpr bool tinyness_before
Tininess is detected after rounding, as x86 does for double.
Definition float128.h:7833
static constexpr bool is_specialized
Definition float128.h:7817
static constexpr float_round_style round_style
Definition float128.h:7834
static constexpr fp128::float128 lowest() noexcept
Most negative finite value.
Definition float128.h:7860
static constexpr bool has_infinity
Definition float128.h:7821
static constexpr fp128::float128 signaling_NaN() noexcept
Definition float128.h:7869
static constexpr int digits10
Decimal digits that survive a round trip through the type.
Definition float128.h:7839
static constexpr int min_exponent10
Definition float128.h:7845
static constexpr bool is_iec559
True only with FP128_IEEE_ENV, which adds the rounding directions and the exception flags IEEE 754 re...
Definition float128.h:7829
static constexpr fp128::float128 infinity() noexcept
Definition float128.h:7867
static constexpr fp128::float128 epsilon() noexcept
Difference between one and the next larger value, 2^-112.
Definition float128.h:7862
static constexpr bool has_signaling_NaN
Definition float128.h:7823
static constexpr bool traps
Exceptions raise flags (with FP128_IEEE_ENV) but never trap.
Definition float128.h:7831
static constexpr int digits
Mantissa bits including the implicit leading one.
Definition float128.h:7837
static constexpr int max_digits10
Decimal digits needed to distinguish every value of the type.
Definition float128.h:7841
static constexpr fp128::float128 round_error() noexcept
Largest rounding error in units in the last place, one half.
Definition float128.h:7864
static FP128_SUPPRESS_DEPRECATED_BEGIN constexpr float_denorm_style has_denorm
Definition float128.h:7851
static constexpr fp128::float128 max() noexcept
Largest finite value, (2 - 2^-112) * 2^16383.
Definition float128.h:7858
static constexpr int max_exponent10
Definition float128.h:7846
static FP128_SUPPRESS_DEPRECATED_END constexpr fp128::float128 min() noexcept
Smallest positive normal value, 2^-16382.
Definition float128.h:7856
Exact conversion between binary128 and decimal.
Shared definitions, intrinsics, and helper functions for 128-bit fixed-point arithmetic.
#define FP128_SUPPRESS_DEPRECATED_END
Closes the region opened by FP128_SUPPRESS_DEPRECATED_BEGIN.
#define FP128_SUPPRESS_DEPRECATED_BEGIN
Opens a region in which the use of a deprecated declaration is not reported.
#define FP128_ONE_SHIFT(x)
#define FP128_ASSERT(x)
#define FP128_GET_BIT(x, n)
#define FP128_INLINE
#define FP128_MAX_VALUE_64(x)
#define FP128_FORCE_INLINE
Marks a function the compiler must inline rather than merely may.
#define FP128_ALIGN16
int32_t to_decimal_digits(uint64_t mantissa_low, uint64_t mantissa_high, int32_t exponent, int32_t requested, char *digits, bool *exact=nullptr, digit_rounding direction=digit_rounding::nearest_even) noexcept
Correctly rounded decimal digits of a finite, non zero binary128 value.
std::from_chars_result from_hex_chars(const char *first, const char *last, float128 &value)
Reads a hexadecimal significand with an optional binary exponent, such as 1.8p1.
Definition float128.h:7208
digit_rounding digit_rounding_for(uint32_t sign) noexcept
The digit rounding the current direction comes down to for a value of a given sign.
Definition float128.h:396
constexpr int32_t MAX_EXACT_DIGITS
Significant digits that settle the rounding of any decimal input exactly.
int32_t shortest_digit_count(const float128 &value)
Fewest significant digits that read back as the same value.
Definition float128.h:6758
digit_rounding
How to_decimal_digits() rounds the last digit it keeps.
@ nearest_even
to the nearest digit, a tie to the even one
@ away_from_zero
up whenever anything was discarded
basic_big_uint< 3072 > wide_big_uint
The big integer that holds MAX_EXACT_DIGITS digits scaled to the smallest subnormal,...
void append_exponent(std::string &out, int32_t exponent, char marker, int32_t min_digits=2)
Appends the decimal exponent of a scientific or hexadecimal form, with a sign.
Definition float128.h:6715
basic_big_uint< 560 > big_uint
The big integer every conversion uses, 560 limbs or 17920 bits.
constexpr void raise_flags(int flags) noexcept
Raises exception flags. Does nothing without FP128_IEEE_ENV or during constant evaluation.
Definition float128.h:284
rounding
The rounding-direction attributes IEEE 754-2008 requires of a binary format.
Definition float128.h:241
@ toward_zero
roundTowardZero
Definition float128.h:243
@ nearest_even
roundTiesToEven, the default
Definition float128.h:242
@ upward
roundTowardPositive
Definition float128.h:244
@ downward
roundTowardNegative
Definition float128.h:245
constexpr int32_t MAX_OUTPUT_DIGITS
Largest number of digits to_decimal_digits() produces.
constexpr int32_t MAX_SIGNIFICANT_DIGITS
Largest number of significant digits any conversion here produces.
constexpr int32_t DEFAULT_PRECISION
Default precision the e, f and g styles use when none is given, as in printf.
Definition float128.h:6705
bool decimal_to_binary(basic_big_uint< Capacity > &value, const char *digits, int32_t count, int32_t max_kept, int32_t exponent10, uint64_t &mantissa_low, uint64_t &mantissa_high, int32_t &exponent, uint64_t *extra) noexcept
Reads a decimal mantissa and exponent back to the nearest binary128.
constexpr uint64_t two_over_pi_bits[]
The binary expansion of 2/pi after the binary point, most significant word first.
Definition float128.h:533
std::string render(const float128 &value, char style, int32_t precision, bool uppercase, bool alternate, char sign_char, bool bare_hex=false)
Renders a float128 as text. Defined below, declared here because the conversions to a string delegate...
Definition float128.h:6817
const char * parse_special_value(const char *cursor, const char *last, bool negative, float128 &value)
Reads one of the special values: inf, infinity, nan, nan(n-char-sequence) or snan.
Definition float128.h:7152
std::errc round_decimal(basic_big_uint< Capacity > &workspace, const char *digits, int32_t count, int32_t max_kept, int32_t exponent10, uint32_t sign, float128 &value) noexcept
Rounds digits * 10^exponent10, with the given sign, to a float128.
Definition float128.h:7329
bool from_decimal_digits(const char *digits, int32_t count, int32_t exponent10, uint64_t &mantissa_low, uint64_t &mantissa_high, int32_t &exponent, uint64_t *extra=nullptr) noexcept
Reads a decimal mantissa and exponent back to the nearest binary128.
constexpr rounding current_rounding() noexcept
The rounding direction every float128 operation applies.
Definition float128.h:271
Everything the library provides.
constexpr bool isunordered(const float128 &x, const float128 &y) noexcept
Definition float128.h:5993
constexpr float128 fmaxmag(const float128 &x, const float128 &y) noexcept
Definition float128.h:6079
constexpr bool islessequal(const float128 &x, const float128 &y) noexcept
Definition float128.h:6015
constexpr bool iszero(const float128 &x) noexcept
Definition float128.h:6111
constexpr float128 fminmag(const float128 &x, const float128 &y) noexcept
Definition float128.h:6092
void fact_reciprocal(int x, fixed_point128< I > &res) noexcept
int fegetexceptflag(std::fexcept_t *flagp, int excepts) noexcept
Saves the state of float128 exception flags (IEEE 754 saveAllFlags).
Definition float128.h:495
fixed_point128< I > sqrt(const fixed_point128< I > &x, uint32_t iterations=3) noexcept
constexpr uint32_t array_length(const T &a)
Calculates the element count of a C style array at build time Example: int a[5]; constexpr int len = ...
fixed_point128< I > atan(fixed_point128< I > x) noexcept
constexpr void mul128_high(uint64_t a_low, uint64_t a_high, uint64_t b_low, uint64_t b_high, uint64_t &res_low, uint64_t &res_high) noexcept
Upper 128 bits of the product of two 128 bit unsigned values.
fixed_point128< I > ceil(const fixed_point128< I > &x) noexcept
constexpr int64_t llrint(const float128 &x) noexcept
Definition float128.h:3575
constexpr bool iscanonical(const float128 &x) noexcept
Definition float128.h:6105
fixed_point128< I > hypot(const fixed_point128< I > &x, const fixed_point128< I > &y) noexcept
fixed_point128< I > asin(fixed_point128< I > x) noexcept
fixed_point128< I > cos(fixed_point128< I > x) noexcept
fixed_point128< I > exp2(const fixed_point128< I > &x) noexcept
constexpr int32_t log2_reduction_bits
Bits of argument reduction fixed_point128::log2() applies; log2_recip_table has 2^this entries.
fixed_point128< I > log2(fixed_point128< I > x) noexcept
constexpr int32_t lround(const float128 &x) noexcept
Definition float128.h:3597
constexpr bool isfinite(const float128 &x) noexcept
Definition float128.h:5765
constexpr void twos_complement128(uint64_t &l, uint64_t &h) noexcept
converts a 128 integer to negative via 2's complement.
int32_t ilogb(const fixed_point128< I > &x) noexcept
float128 nan(const char *payload) noexcept
Definition float128.h:6124
int fesetexceptflag(const std::fexcept_t *flagp, int excepts) noexcept
Restores float128 exception flags saved by fegetexceptflag (IEEE 754 restoreFlags).
Definition float128.h:511
std::to_chars_result to_chars(char *first, char *last, const float128 &value, std::chars_format fmt, int precision)
Converts a float128 to text, in the shape of std::to_chars.
Definition float128.h:7588
static bool div_128bit(uint64_t *q, uint64_t *r, const uint64_t *u, const uint64_t *v) noexcept
Divides an unsigned integer of up to 256 bits by a 128 bit one. Knuth algorithm D,...
constexpr int32_t lrint(const float128 &x) noexcept
Definition float128.h:3589
int feclearexcept(int excepts) noexcept
Lowers float128 exception flags (IEEE 754 lowerFlags).
Definition float128.h:466
constexpr float128 abs(const float128 &x) noexcept
Definition float128.h:6690
constexpr bool totalorder(const float128 &x, const float128 &y) noexcept
Definition float128.h:6059
constexpr float128 scalbln(const float128 &x, long n) noexcept
Definition float128.h:6183
constexpr bool islessgreater(const float128 &x, const float128 &y) noexcept
Definition float128.h:6020
constexpr int fpclassify(const float128 &x) noexcept
Definition float128.h:5975
std::istream & operator>>(std::istream &is, fixed_point128< I > &value)
Reads a fixed_point128 from a stream, the way the builtin arithmetic extractors do.
constexpr uint64_t log2_recip_table[][2]
1/(1 + j/64) as a 128 bit fraction, the reciprocals fixed_point128::log2() reduces with.
float128 cbrt(const float128 x, uint32_t iterations=2) noexcept
Definition float128.h:3958
std::string to_string(const float128 &value)
The shortest decimal string that reads back as this exact value.
Definition float128.h:7132
std::from_chars_result from_chars(const char *first, const char *last, float128 &value)
Reads a decimal string into a float128. Defined below, declared here because the constructor from a s...
Definition float128.h:7376
fixed_point128< I > fmax(const fixed_point128< I > &x, const fixed_point128< I > &y) noexcept
constexpr float128 scalbn(const float128 &x, int n) noexcept
Definition float128.h:6181
fixed_point128< I > exp(const fixed_point128< I > &x) noexcept
fixed_point128< I > asinh(const fixed_point128< I > &x) noexcept
fixed_point128< I > atan2(fixed_point128< I > y, fixed_point128< I > x) noexcept
constexpr bool isgreaterequal(const float128 &x, const float128 &y) noexcept
Definition float128.h:6005
fixed_point128< I > modf(const fixed_point128< I > &x, fixed_point128< I > *iptr) noexcept
float128 tgamma(float128 x) noexcept
Definition float128.h:6626
constexpr bool isless(const float128 &x, const float128 &y) noexcept
Definition float128.h:6010
int fegetround() noexcept
The rounding direction float128 arithmetic uses on the calling thread.
Definition float128.h:411
fixed_point128< I > tan(fixed_point128< I > x) noexcept
constexpr float128 frexp(float128 x, int *expptr) noexcept
Definition float128.h:5923
constexpr bool issubnormal(const float128 &x) noexcept
Definition float128.h:6109
constexpr float128 rint(const float128 &x) noexcept
Definition float128.h:6165
constexpr float128 fma(float128 x, float128 y, float128 z) noexcept
Definition float128.h:5785
fixed_point128< I > logb(fixed_point128< I > x) noexcept
constexpr bool isnormal(const float128 &x) noexcept
Definition float128.h:5973
int128_base< false > uint128_t
128 bit unsigned integer type.
Definition uint128_t.h:73
float128 erf(float128 x) noexcept
Definition float128.h:5626
fixed_point128< I > floor(const fixed_point128< I > &x) noexcept
fixed_point128< I > fmod(const fixed_point128< I > &x, const fixed_point128< I > &y)
fixed_point128< I > sinh(const fixed_point128< I > &x) noexcept
constexpr bool totalordermag(const float128 &x, const float128 &y) noexcept
Definition float128.h:6067
fixed_point128< I > fdim(const fixed_point128< I > &x, const fixed_point128< I > &y) noexcept
fixed_point128< I > round(const fixed_point128< I > &x) noexcept
fixed_point128< I > log1p(fixed_point128< I > x) noexcept
constexpr int64_t llround(const float128 &x) noexcept
Definition float128.h:3583
int fetestexcept(int excepts) noexcept
Tests float128 exception flags (IEEE 754 testFlags).
Definition float128.h:452
constexpr bool issignaling(const float128 &x) noexcept
Definition float128.h:6107
fixed_point128< I > sin(fixed_point128< I > x) noexcept
constexpr float128 nearbyint(const float128 &x) noexcept
Definition float128.h:6170
fixed_point128< I > copysign(const fixed_point128< I > &x, const fixed_point128< I > &y) noexcept
fixed_point128< I > log10(fixed_point128< I > x) noexcept
constexpr bool isgreater(const float128 &x, const float128 &y) noexcept
Definition float128.h:6000
static constexpr int32_t dbl_frac_bits
Mantissa bit count of an IEEE 754 double.
fixed_point128< I > cosh(const fixed_point128< I > &x) noexcept
int feraiseexcept(int excepts) noexcept
Raises float128 exception flags (IEEE 754 raiseFlags).
Definition float128.h:479
constexpr void shift_left128_inplace_safe(uint64_t &l, uint64_t &h, int shift) noexcept
Left shift a 128 bit integer (inplace). Handles any positive shift value.
std::ostream & operator<<(std::ostream &os, const fixed_point128< I > &value)
Writes a fixed_point128 to a stream, honouring its width, fill and adjustment.
constexpr float128 nexttoward(const float128 &x, const float128 &y) noexcept
Definition float128.h:6214
constexpr float128 nextafter(const float128 &x, const float128 &y) noexcept
Definition float128.h:6205
fixed_point128< I > acos(fixed_point128< I > x) noexcept
fixed_point128< I > pow(const fixed_point128< I > &x, const fixed_point128< I > &y) noexcept
float128 remainder(const float128 &x, const float128 &y) noexcept
Definition float128.h:6305
float128 double_factorial(int x) noexcept
Definition float128.h:4109
fixed_point128< I > tanh(const fixed_point128< I > &x) noexcept
fixed_point128< I > fabs(const fixed_point128< I > &x) noexcept
constexpr bool signbit(const float128 &x) noexcept
Definition float128.h:5971
constexpr uint64_t log2_inv_n_table[][2]
1/(n*ln2) for n = 1 upwards, as a raw 128 bit value with 127 fraction bits; entry [i] holds 1/((i+1)*...
constexpr uint64_t shift_right128(uint64_t l, uint64_t h) noexcept
Right shift a 128 bit integer. When shift is a compile time constant, this function generates optimal...
float128 remquo(const float128 &x, const float128 &y, int *quo) noexcept
Definition float128.h:6318
constexpr uint64_t log2_value_table[][2]
-log2 of the matching log2_recip_table entry, as a 128 bit fraction.
float128 erfc(float128 x) noexcept
Definition float128.h:5708
fixed_point128< I > acosh(const fixed_point128< I > &x) noexcept
float128 lgamma(float128 x) noexcept
Definition float128.h:6534
fixed_point128< I > trunc(const fixed_point128< I > &x) noexcept
fixed_point128< I > reciprocal(const fixed_point128< I > &x) noexcept
int fesetround(int round) noexcept
Selects the rounding direction float128 arithmetic uses on the calling thread.
Definition float128.h:427
fixed_point128< I > fmin(const fixed_point128< I > &x, const fixed_point128< I > &y) noexcept
fixed_point128< I > expm1(const fixed_point128< I > &x) noexcept
fixed_point128< I > atanh(const fixed_point128< I > &x) noexcept
constexpr float128 ldexp(float128 x, int exp) noexcept
Definition float128.h:5948
fixed_point128< I > log(fixed_point128< I > x) noexcept
STL namespace.
Bit level view of an IEEE 754 double-precision value.
constexpr uint64_t f() const noexcept
Mantissa (fraction) bits.
constexpr uint64_t s() const noexcept
Sign bit (0 = positive, 1 = negative).
constexpr uint64_t e() const noexcept
Biased exponent bits.
The per thread state behind the float128 environment.
Definition float128.h:249
int flags
Raised exceptions, as FE_ bits.
Definition float128.h:251
rounding mode
Rounding direction in effect.
Definition float128.h:250
A finite value rounded to a narrower binary format, see narrow().
Definition float128.h:970
bool to_inf
The value overflowed to infinity.
Definition float128.h:974
int32_t lsb
Weight of the significand's lowest bit, as a power of two.
Definition float128.h:972
uint64_t sig
Significand, below 2^P. Zero for a zero result.
Definition float128.h:971
uint32_t sign
Sign of the result.
Definition float128.h:973
auto format(const fp128::float128 &value, FormatContext &context) const
Definition float128.h:7953
bool zero_pad
The 0 flag: pad with zeros after the sign.
Definition float128.h:8000
char align
One of < > ^, or zero when none was given.
Definition float128.h:7996
constexpr auto parse(basic_format_parse_context< char > &context)
Definition float128.h:7885
string render(const fp128::float128 &value) const
Builds the text, including the padding the specification asks for.
Definition float128.h:7960
int precision
Digits after the point, or -1 when none was given.
Definition float128.h:8002
char type
One of a A e E f F g G, or zero for the shortest form.
Definition float128.h:7998
char fill
Character the padding is made of.
Definition float128.h:7995
bool alternate
The # flag: keep the point and the trailing zeros.
Definition float128.h:7999
size_t operator()(const fp128::float128 &value) const noexcept
Definition float128.h:8013
128-bit unsigned integer type.