fixed_point128 1.0.1.0
128 bit integer, fixed point and floating point arithmetic for C++20
Loading...
Searching...
No Matches
fixed_point128.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 fixed_point128.h
41 * @brief Header-only 128-bit fixed-point arithmetic library.
42 *
43 * Provides the `fixed_point128<I>` template class where I is the number of
44 * integer bits (range [1, 63]), with one bit used for the sign and the
45 * remaining 127-I for the fractional part. Supports full arithmetic (+, -, *, /, %, shifts),
46 * comparison operators, type conversions (int, float, double, string), and
47 * a comprehensive set of math functions (sqrt, sin, cos, tan, atan, atan2,
48 * sinh, cosh, tanh, exp, log, pow, etc.).
49 *
50 * Platform-specific intrinsics are used for MSVC and GCC/Clang to maximize
51 * performance. All methods are inline. The library is 64-bit only.
52 *
53 * @tparam I Number of integer bits in [1, 63]. The fraction uses 127-I bits and the sign takes one.
54 *
55 * @see fp128_shared.h for supporting intrinsics and utilities.
56 */
57
58#pragma once
59
60// override some static analysis checks
61#if defined(_MSC_VER)
62#pragma warning(push)
63#pragma warning(disable : 26472) // Don't use a static_cast for arithmetic conversions. Use brace initialization
64#pragma warning(disable : 26485) // No array to pointer decay
65#pragma warning(disable : 26481) // Don't use pointer arithmetic. Use span instead
66#pragma warning(disable : 26446) // Prefer to use gsl::at() instead of unchecked subscript operator
67#pragma warning(disable : 26482) // Only index into arrays using constant expressions
68#pragma warning(disable : 26408) // Avoid malloc() and free(), prefer the nothrow version of new with delete
69#endif
70
71#ifndef FP128_FIXED_POINT128_T_H
72#define FP128_FIXED_POINT128_T_H
73
74#include <cmath> // std::sqrt, std::ldexp, std::frexp, FP_ILOGB0
75#include <format> // std::formatter
76#include <functional> // std::hash
77#include <limits>
78#include <istream>
79#include <ostream>
80#include "fp128_shared.h"
81#include "fp128_decimal.h"
82
83namespace fp128
84{
85
86/***********************************************************************************
87 * Forward declarations
88 ************************************************************************************/
89class fp128_gtest; ///< Google test class (friend).
90template <int32_t I> class fixed_point128; ///< Forward declaration of the main template class.
91
92// Note: Release builds will fail without these forward declarations. Hints towards compiler a bug (VS2022 v17.4)
93// The compiler and IntelliSense don't match these functions in some cases and try to use the CRT versions which
94// causes a compilation error.
95
96/// @name CRT-Style Math Functions (Forward Declarations)
97/// @brief Free functions providing standard math library equivalents for fixed_point128.
98/// @{
99template <int32_t I> [[nodiscard]] fixed_point128<I> fabs(const fixed_point128<I>& x) noexcept;
100template <int32_t I> [[nodiscard]] fixed_point128<I> floor(const fixed_point128<I>& x) noexcept;
101template <int32_t I> [[nodiscard]] fixed_point128<I> ceil(const fixed_point128<I>& x) noexcept;
102template <int32_t I> [[nodiscard]] fixed_point128<I> trunc(const fixed_point128<I>& x) noexcept;
103template <int32_t I> [[nodiscard]] fixed_point128<I> round(const fixed_point128<I>& x) noexcept;
104template <int32_t I> [[nodiscard]] int32_t ilogb(const fixed_point128<I>& x) noexcept;
105template <int32_t I> [[nodiscard]] fixed_point128<I> copysign(const fixed_point128<I>& x, const fixed_point128<I>& y) noexcept;
106template <int32_t I> [[nodiscard]] fixed_point128<I> fmod(const fixed_point128<I>& x, const fixed_point128<I>& y);
107template <int32_t I> [[nodiscard]] fixed_point128<I> modf(const fixed_point128<I>& x, fixed_point128<I>* iptr) noexcept;
108template <int32_t I> [[nodiscard]] fixed_point128<I> fdim(const fixed_point128<I>& x, const fixed_point128<I>& y) noexcept;
109template <int32_t I> [[nodiscard]] fixed_point128<I> fmin(const fixed_point128<I>& x, const fixed_point128<I>& y) noexcept;
110template <int32_t I> [[nodiscard]] fixed_point128<I> fmax(const fixed_point128<I>& x, const fixed_point128<I>& y) noexcept;
111template <int32_t I> [[nodiscard]] fixed_point128<I> hypot(const fixed_point128<I>& x, const fixed_point128<I>& y) noexcept;
112template <int32_t I> [[nodiscard]] fixed_point128<I> sqrt(const fixed_point128<I>& x, uint32_t iterations = 3) noexcept;
113template <int32_t I> [[nodiscard]] fixed_point128<I> sin(fixed_point128<I> x) noexcept;
114template <int32_t I> [[nodiscard]] fixed_point128<I> asin(fixed_point128<I> x) noexcept;
115template <int32_t I> [[nodiscard]] fixed_point128<I> cos(fixed_point128<I> x) noexcept;
116template <int32_t I> [[nodiscard]] fixed_point128<I> acos(fixed_point128<I> x) noexcept;
117template <int32_t I> [[nodiscard]] fixed_point128<I> tan(fixed_point128<I> x) noexcept;
118template <int32_t I> [[nodiscard]] fixed_point128<I> atan(fixed_point128<I> x) noexcept;
119template <int32_t I> [[nodiscard]] fixed_point128<I> atan2(fixed_point128<I> y, fixed_point128<I> x) noexcept;
120template <int32_t I> [[nodiscard]] fixed_point128<I> sinh(const fixed_point128<I>& x) noexcept;
121template <int32_t I> [[nodiscard]] fixed_point128<I> asinh(const fixed_point128<I>& x) noexcept;
122template <int32_t I> [[nodiscard]] fixed_point128<I> cosh(const fixed_point128<I>& x) noexcept;
123template <int32_t I> [[nodiscard]] fixed_point128<I> acosh(const fixed_point128<I>& x) noexcept;
124template <int32_t I> [[nodiscard]] fixed_point128<I> tanh(const fixed_point128<I>& x) noexcept;
125template <int32_t I> [[nodiscard]] fixed_point128<I> atanh(const fixed_point128<I>& x) noexcept;
126template <int32_t I> [[nodiscard]] fixed_point128<I> exp(const fixed_point128<I>& x) noexcept;
127template <int32_t I> [[nodiscard]] fixed_point128<I> exp2(const fixed_point128<I>& x) noexcept;
128template <int32_t I> [[nodiscard]] fixed_point128<I> expm1(const fixed_point128<I>& x) noexcept;
129template <int32_t I> [[nodiscard]] fixed_point128<I> pow(const fixed_point128<I>& x, const fixed_point128<I>& y) noexcept;
130template <int32_t I> [[nodiscard]] fixed_point128<I> log(fixed_point128<I> x) noexcept;
131template <int32_t I> [[nodiscard]] fixed_point128<I> log2(fixed_point128<I> x) noexcept;
132template <int32_t I> [[nodiscard]] fixed_point128<I> log10(fixed_point128<I> x) noexcept;
133template <int32_t I> [[nodiscard]] fixed_point128<I> logb(fixed_point128<I> x) noexcept;
134template <int32_t I> [[nodiscard]] fixed_point128<I> log1p(fixed_point128<I> x) noexcept;
135/// @}
136
137/// @name Non-CRT Utility Functions (Forward Declarations)
138/// @{
139template <int32_t I> [[nodiscard]] uint64_t lzcnt128(const fixed_point128<I>& x) noexcept;
140template <int32_t I> [[nodiscard]] fixed_point128<I> reciprocal(const fixed_point128<I>& x) noexcept;
141template <int32_t I> void fact_reciprocal(int x, fixed_point128<I>& res) noexcept;
142/// @}
143
144/**
145 * @brief Divides a 256 bit numerator by a 128 bit divisor: the one call of div_128bit() in this header.
146 *
147 * The long division, the remainder and the integer square root of fixed_point128 all divide by a
148 * divisor that needs both QWORDs, and all of them come through here. The word count is fixed at four
149 * by the template argument of div_128bit<4>(), so its loops are unrolled for this shape whether the
150 * compiler inlines it or not. That used to depend on inlining: with the count an ordinary argument
151 * and callers in int128_shared.h and float128.h sharing one out of line copy, clang++ compiled a
152 * generic division and the long division here lost 15%.
153 *
154 * @param q (output) Quotient, three words, q[0] lowest.
155 * @param r (output, optional) Remainder, two words. Can be nullptr.
156 * @param u Numerator, four words, u[0] lowest.
157 * @param v Divisor, two words; v[1] must not be zero.
158 * @return true on success, false when v[1] is zero or a pointer is null.
159 */
160[[nodiscard]] inline bool Divide256By128(uint64_t* q, uint64_t* r, const uint64_t* u, const uint64_t* v) noexcept
161{
162 return div_128bit<4>(q, r, u, v);
163}
164
165/**
166 * @brief 1 / (n(n+1)) for n = 1..40, with 125 fraction bits rounded to nearest, {high, low}.
167 *
168 * The ratio of consecutive terms of the sine and cosine series: the sine term after x^n / n! is the
169 * previous one times x^2 / ((n+1)(n+2)), entries 2, 4, 6, ... of this table, and the cosine terms use
170 * entries 1, 3, 5, ... Generated with Python fractions (exact), see fixed_point128::TrigSeries().
171 */
172inline constexpr uint64_t fp128_trig_series_table[][2] = {
173 {0x1000000000000000ull, 0x0000000000000000ull}, // 1 / (1 * 2)
174 {0x0555555555555555ull, 0x5555555555555555ull}, // 1 / (2 * 3)
175 {0x02AAAAAAAAAAAAAAull, 0xAAAAAAAAAAAAAAABull}, // 1 / (3 * 4)
176 {0x0199999999999999ull, 0x999999999999999Aull}, // 1 / (4 * 5)
177 {0x0111111111111111ull, 0x1111111111111111ull}, // 1 / (5 * 6)
178 {0x00C30C30C30C30C3ull, 0x0C30C30C30C30C31ull}, // 1 / (6 * 7)
179 {0x0092492492492492ull, 0x4924924924924925ull}, // 1 / (7 * 8)
180 {0x0071C71C71C71C71ull, 0xC71C71C71C71C71Cull}, // 1 / (8 * 9)
181 {0x005B05B05B05B05Bull, 0x05B05B05B05B05B0ull}, // 1 / (9 * 10)
182 {0x004A7904A7904A79ull, 0x04A7904A7904A790ull}, // 1 / (10 * 11)
183 {0x003E0F83E0F83E0Full, 0x83E0F83E0F83E0F8ull}, // 1 / (11 * 12)
184 {0x0034834834834834ull, 0x8348348348348348ull}, // 1 / (12 * 13)
185 {0x002D02D02D02D02Dull, 0x02D02D02D02D02D0ull}, // 1 / (13 * 14)
186 {0x0027027027027027ull, 0x0270270270270270ull}, // 1 / (14 * 15)
187 {0x0022222222222222ull, 0x2222222222222222ull}, // 1 / (15 * 16)
188 {0x001E1E1E1E1E1E1Eull, 0x1E1E1E1E1E1E1E1Eull}, // 1 / (16 * 17)
189 {0x001AC5701AC5701Aull, 0xC5701AC5701AC570ull}, // 1 / (17 * 18)
190 {0x0017F405FD017F40ull, 0x5FD017F405FD017Full}, // 1 / (18 * 19)
191 {0x00158ED2308158EDull, 0x2308158ED2308159ull}, // 1 / (19 * 20)
192 {0x0013813813813813ull, 0x8138138138138138ull}, // 1 / (20 * 21)
193 {0x0011BB4A4046ED29ull, 0x011BB4A4046ED290ull}, // 1 / (21 * 22)
194 {0x00103091B51F5E1Aull, 0x4EECC652F8EAC041ull}, // 1 / (22 * 23)
195 {0x000ED7303B5CC0EDull, 0x7303B5CC0ED7303Bull}, // 1 / (23 * 24)
196 {0x000DA740DA740DA7ull, 0x40DA740DA740DA74ull}, // 1 / (24 * 25)
197 {0x000C9A633FCD9673ull, 0x00C9A633FCD96730ull}, // 1 / (25 * 26)
198 {0x000BAB656100BAB6ull, 0x56100BAB656100BBull}, // 1 / (26 * 27)
199 {0x000AD602B580AD60ull, 0x2B580AD602B580ADull}, // 1 / (27 * 28)
200 {0x000A16B312EA8FC3ull, 0x77CD8E80A16B312Full}, // 1 / (28 * 29)
201 {0x00096A850096A850ull, 0x096A850096A85009ull}, // 1 / (29 * 30)
202 {0x0008CF008CF008CFull, 0x008CF008CF008CF0ull}, // 1 / (30 * 31)
203 {0x0008421084210842ull, 0x1084210842108421ull}, // 1 / (31 * 32)
204 {0x0007C1F07C1F07C1ull, 0xF07C1F07C1F07C1Full}, // 1 / (32 * 33)
205 {0x00074D1E92F0074Dull, 0x1E92F0074D1E92F0ull}, // 1 / (33 * 34)
206 {0x0006E25006E25006ull, 0xE25006E25006E250ull}, // 1 / (34 * 35)
207 {0x0006806806806806ull, 0x8068068068068068ull}, // 1 / (35 * 36)
208 {0x000626703D806267ull, 0x03D80626703D8062ull}, // 1 / (36 * 37)
209 {0x0005D392C1005D39ull, 0x2C1005D392C1005Dull}, // 1 / (37 * 38)
210 {0x0005871513005871ull, 0x5130058715130058ull}, // 1 / (38 * 39)
211 {0x0005405405405405ull, 0x4054054054054054ull}, // 1 / (39 * 40)
212 {0x0004FEC04FEC04FEull, 0xC04FEC04FEC04FECull}, // 1 / (40 * 41)
213};
214
215/***********************************************************************************
216 * Main Code
217 ************************************************************************************/
218
219/**
220 * @brief 128 bit fixed point class template.
221 *
222 * This template provides a floating point-like type that performs various math operations quickly compared to traditional high precision libraries.
223 * The only template parameter <B>I</B> is the bit count of the integer part, not counting the sign.
224 * The sign takes one bit and the fraction takes the remaining 127 - <B>I</B>.<BR>
225 * <B>I</B> is limited to the range [1,63] in order to simplify the implementation and increase performance.<BR>
226 * This restriction is enforced at compile time.
227 * All of fixed_point128's methods are inline for maximum performance.
228 *
229 * <B>Representation:</B><BR>
230 * The object is exactly 128 bits wide and holds nothing but the value. Those bits are a two's
231 * complement integer, held as the QWORD pair (high:low) with the sign in the MSB of <B>high</B>,
232 * and the value they stand for is that integer divided by 2^<B>F</B>:
233 * @code
234 * value = (int128)(high:low) / 2^F, where F = 127 - I
235 * @endcode
236 * The representable range is therefore [-2^I, 2^I - 2^-F], which is the asymmetric range of every
237 * two's complement type: the most negative value has no positive counterpart, so negating it (and
238 * fabs of it) wraps back to itself.
239 *
240 * <B>Minimum integer bits:</B><BR>
241 * Some of the constants and functions cannot work in the narrowest instantiations, and each one
242 * says so with a static_assert in its body rather than by overflowing quietly or failing to link.
243 * The bound is the smallest <B>I</B> that works, not a safe margin:
244 * <UL>
245 * <LI><B>I >= 2</B>: pi(), e(), and the exponential family exp(), exp2(), expm1(), pow() and
246 * tanh(), which all reach e().</LI>
247 * <LI><B>I >= 3</B>: pi2(), which is 6.28.</LI>
248 * <LI><B>I >= 4</B>: the trigonometric group sin1(), cos1(), sin(), cos(), tan(), asin(), acos(),
249 * atan(), atan2(), and the hyperbolic sinh() and cosh().</LI>
250 * </UL>
251 * Everything else works for every <B>I</B>, including half_pi(), sqrt_2() and golden_ratio(), which
252 * are all below two. A function whose <I>result</I> leaves the range - exp() of a large argument,
253 * log() of a tiny one - is a matter of the argument rather than of the type, and overflows silently
254 * like any other operation.
255 *
256 * <B>Implementation notes:</B>
257 * <UL>
258 * <LI>Overflow is handled silently, similar to builtin integer operations.</LI>
259 * <LI>The sign is part of the value rather than a separate field, so addition, subtraction, the
260 * comparisons and the bitwise operators are the plain 128 bit integer operations and there is
261 * no negative zero to normalize away.</LI>
262 * <LI>Multiplication and division work on magnitudes internally and restore the sign afterwards.</LI>
263 * <LI><B>Rounding:</B> every result that does not fit the grid is rounded to the nearest grid value,
264 * and an exact tie goes away from zero (the magnitude is rounded half up). This holds for the
265 * multiplication, the division by a fixed_point128 or by an integer, the right shifts, and the
266 * conversion to an instantiation with more integer bits. The conversion from a floating point
267 * value is the exception: it truncates towards zero, as the conversion to an integer does.</LI>
268 * <LI>A fixed_point128 object is not thread safe. Accessing a const object from multiple threads is safe.</LI>
269 * <LI>fixed_point128 is <B>conditionally safe</B>, 2 different non const objects can be accessed concurrently.</LI>
270 * <LI>Only 64 bit builds are supported.</LI>
271 * </UL>
272 *
273 * <B>Compile time evaluation:</B><BR>
274 * Everything that stays within integer arithmetic is constexpr:
275 * <UL>
276 * <LI>Construction from and conversion to the integer types and the floating point types, copy,
277 * move and the cross-template conversions between two fixed_point128 instantiations.</LI>
278 * <LI>Addition, subtraction, multiplication, square(), the increment and decrement operators,
279 * the shifts, the bitwise operators, the unary operators and the comparisons.</LI>
280 * <LI>The queries: is_int(), is_positive(), is_negative(), is_zero(), get_bit() and
281 * get_exponent(), and the exact constants one(), half() and epsilon().</LI>
282 * <LI>The math functions fabs, floor, ceil, trunc, round, copysign, modf, fmin, fmax, fdim, sqr,
283 * ilogb, lzcnt128, log2 and logb.</LI>
284 * </UL>
285 *
286 * The bit counting and extended arithmetic intrinsics these rest on are not constant expressions,
287 * so fp128_shared.h wraps each one in a constexpr function that serves a constant
288 * evaluated call from a portable implementation of the same operation. A runtime call still
289 * reaches the bare intrinsic and generates the same code it did before.
290 *
291 * The rest cannot be constexpr, for one of two reasons:
292 * <UL>
293 * <LI>Division and modulo: div_64bit rests on the _udiv128 intrinsic. div_128bit does not, and
294 * nothing in it is barred from a constant expression, but the function that calls it is still
295 * bound by the rest of this list.</LI>
296 * <LI>Function local statics, which a constexpr function may not declare. The transcendental
297 * constants (pi, e, sqrt_2, ...) and the factorial reciprocal table are parsed from strings
298 * into them. reciprocal is a division. sqrt and hypot seed their integer square root with the
299 * CRT's sqrt().</LI>
300 * </UL>
301 */
302template <int32_t I> class fixed_point128
303{
304 // build time validation of template parameters
305 static_assert(1 <= I && I <= 63, "Template parameter <I> must be in the [1,63] range!");
306 static_assert(sizeof(void*) == 8, "fixed_point128 is supported in 64 bit builds only!");
307
308 // friends
309 template <int32_t I2> friend class fixed_point128; // this class is a friend of all its template instances. Avoids awkward getter/setter functions.
310 friend class fp128_gtest;
311 // the stream extractor reads with ParseDecimal(), which reports a value out of range
312 template <int32_t J> friend std::istream& operator>>(std::istream& is, fixed_point128<J>& value);
313
314private:
315 /// @name Data Members
316 /// @{
317 uint64_t low; ///< Lower 64-bit QWORD of the 128-bit two's complement value.
318 uint64_t high; ///< Upper 64-bit QWORD of the 128-bit two's complement value. Bit 63 holds the sign.
319 /// @}
320
321public:
322 static constexpr int32_t F = 127 - I; ///< Fraction bit count (127 - I). The remaining bit is the sign.
323
324private:
325 /// @name Internal Constants
326 /// @{
327 static constexpr int32_t upper_frac_bits = F - 64; ///< Fraction bits residing in the upper QWORD (63 - I).
328 static constexpr uint64_t unity = 1ull << upper_frac_bits; ///< Upper QWORD value representing 1.0.
329 static inline const double upper_unity = ::pow(2, 64 - F); ///< Scale factor for upper QWORD to double conversion.
330 static inline const double lower_unity_l = ::pow(2, -F); ///< Scale factor for lower QWORD (low 32 bits) to double.
331 static inline const double lower_unity_h = ::pow(2, 32 - F); ///< Scale factor for lower QWORD (high 32 bits) to double.
332 static constexpr uint64_t int_mask = UINT64_MAX << upper_frac_bits; ///< Bitmask for the sign and integer bits in the upper QWORD.
333 /// Decimal places the text form shows: ceil(F * log10(2)), the fewest that tell every pair of
334 /// neighbouring values apart, 10^-max_frac_digits being the first power of ten below the grid
335 /// spacing 2^-F. F * log10(2) is never an integer, so the floor plus one is that ceiling. It used
336 /// to be F / 3.3, one short for most I: 1 - epsilon printed as 1 and max() as 2^I.
337 static constexpr int32_t max_frac_digits = static_cast<int32_t>(F * 0.30102999566398119521) + 1;
338 /// Fraction digits the string constructor reads. A point halfway between two grid values has F + 1
339 /// decimal places, so 130 settle every rounding; the digits after them cannot reach a halfway
340 /// point and, ties going away from zero, cannot change the outcome at one either.
341 static constexpr int32_t parsed_frac_digits = 130;
342 static constexpr uint64_t sign_mask = 1ull << 63; ///< Bitmask of the sign bit within the upper QWORD.
343 /// @}
344
345 /**
346 * @brief Reads a decimal number to the nearest grid value, a tie going away from zero.
347 *
348 * Grammar: an optional sign, decimal digits, and an optional point followed by more digits; at
349 * least one digit in all. The integer part is kept modulo 2^64, which is all that reaches the
350 * 128 bit result: shifted into place it is the integer part modulo 2^(I+1). The fraction is
351 * kept exactly, as the integer N of its first parsed_frac_digits digits over 10^D, and rounded
352 * as q = floor(N * 2^(F+1) / 10^D), the grid value being (q + 1) / 2 rounded down, which
353 * rounds half away from zero. Both steps are exact big integer arithmetic.
354 *
355 * @param first Start of the text, at the sign or the first digit
356 * @param last One past the end of the text
357 * @param l Receives the low QWORD of the raw value, wrapped modulo 2^128
358 * @param h Receives the high QWORD
359 * @param end Receives a pointer past the last character read, first when nothing was read
360 * @return 0 when there were no digits (the value is zero), 1 when the value is in range, 2 when
361 * it is outside [lowest(), max()] and wrapped.
362 */
363 [[nodiscard]] static int32_t ParseDecimal(const char* first, const char* last, uint64_t& l, uint64_t& h, const char*& end) noexcept
364 {
365 l = h = 0;
366 end = first;
367 const char* p = first;
368 bool negative = false;
369 if (p < last && (*p == '-' || *p == '+')) {
370 negative = (*p == '-');
371 ++p;
372 }
373
374 // The integer part, modulo 2^64, and whether it reached 2^64 at all.
375 uint64_t integer = 0;
376 bool integer_overflow = false;
377 bool any_digit = false;
378 while (p < last && *p >= '0' && *p <= '9') {
379 const uint64_t digit = static_cast<uint64_t>(*p - '0');
380 if (integer > (UINT64_MAX - digit) / 10) {
381 integer_overflow = true;
382 }
383 integer = integer * 10 + digit;
384 any_digit = true;
385 ++p;
386 }
387
388 // The fraction as an exact integer over 10^digits.
389 detail::big_uint fraction;
390 int32_t digits = 0;
391 if (p < last && *p == '.') {
392 ++p;
393 while (p < last && *p >= '0' && *p <= '9') {
394 if (digits < parsed_frac_digits) {
395 fraction.mul_small(10u);
396 fraction.add_small(static_cast<uint32_t>(*p - '0'));
397 ++digits;
398 }
399 any_digit = true;
400 ++p;
401 }
402 }
403 if (!any_digit)
404 return 0;
405 end = p;
406
407 // q = floor(fraction * 2^(F+1) / 10^digits), below 2^(F+1), so it fits the 128 bits read out.
408 bool remainder = false;
409 fraction.shift_left(F + 1);
410 fraction.div_pow10(digits, remainder);
411 uint64_t q_low = static_cast<uint64_t>(fraction.at(0)) | (static_cast<uint64_t>(fraction.at(1)) << 32);
412 uint64_t q_high = static_cast<uint64_t>(fraction.at(2)) | (static_cast<uint64_t>(fraction.at(3)) << 32);
413 // (q + 1) / 2: half away from zero, applied to the magnitude
414 const uint8_t carry = addcarryx_u64(0, q_low, 1, &q_low);
415 addcarryx_u64(carry, q_high, 0, &q_high);
416 shift_right128_inplace(q_low, q_high, 1);
417
418 // magnitude = integer * 2^F + fraction, which F >= 64 puts in the upper QWORD for the integer
419 uint64_t m_low = q_low, m_high = 0;
420 const uint8_t carry2 = addcarryx_u64(0, q_high, integer << upper_frac_bits, &m_high);
421 // Out of range: an integer part above 2^I can only wrap; at 2^I and below the 128 bit
422 // magnitude is exact and compares against 2^127 - 1, or 2^127 for a negative value.
423 const bool integer_too_large = integer_overflow || integer > (1ull << I);
424 const uint64_t limit_high = negative ? (1ull << 63) : (UINT64_MAX >> 1);
425 const uint64_t limit_low = negative ? 0 : UINT64_MAX;
426 const bool too_large = integer_too_large || carry2 != 0 || m_high > limit_high || (m_high == limit_high && m_low > limit_low);
427 if (negative) {
428 twos_complement128(m_low, m_high);
429 }
430 l = m_low;
431 h = m_high;
432 return too_large ? 2 : 1;
433 }
434
435 /**
436 * @brief Reads the magnitude of this object into a QWORD pair.
437 *
438 * The multiply, divide and floating point conversions all need |x| as an unsigned 128 bit
439 * value; this is the one place that knows how to produce it. The most negative value is its own
440 * two's complement, and 2^127 is exactly what its magnitude is as an unsigned pair, so that
441 * case needs no special handling.
442 *
443 * The sign is returned as a mask rather than a bool so that two of them combine with xor. The
444 * negation is left as a branch on purpose: two branchless spellings were measured, the two's
445 * complement as (x ^ -1) + 1 against (x ^ 0) + 0, and computing both forms for a conditional
446 * move to pick between. Both are slower - by 30% and 20% respectively on the multiply and on
447 * everything built on it - MSVC putting the pair through memory rather than keeping it in
448 * registers.
449 *
450 * @param l Receives the low QWORD of the magnitude
451 * @param h Receives the high QWORD of the magnitude
452 * @return The sign as a mask, all ones when the object was negative and all zeros otherwise.
453 * Two of them can be combined with xor to give the sign of a quotient, and NegateIf()
454 * takes one.
455 */
456 [[nodiscard]] FP128_FORCE_INLINE constexpr uint64_t GetMagnitude(uint64_t& l, uint64_t& h) const noexcept
457 {
458 l = low;
459 h = high;
460 const uint64_t sign_bits = static_cast<uint64_t>(static_cast<int64_t>(high) >> 63);
461 if (sign_bits != 0)
462 twos_complement128(l, h);
463
464 return sign_bits;
465 }
466
467 /**
468 * @brief Negates this object in place, in the two's complement sense.
469 * The most negative value has no positive counterpart and is left unchanged, which is the same
470 * silent wrap the builtin integer types perform.
471 */
472 FP128_FORCE_INLINE constexpr void Negate() noexcept { twos_complement128(low, high); }
473
474 /**
475 * @brief Negates this object when the mask says to, without branching.
476 * The counterpart of GetMagnitude(), which produces the masks this takes.
477 * @param sign_bits All ones to negate, all zeros to leave the object alone.
478 */
479 FP128_FORCE_INLINE constexpr void NegateIf(uint64_t sign_bits) noexcept
480 {
481 if (sign_bits != 0)
482 twos_complement128(low, high);
483 }
484
485 /**
486 * @brief Replaces this object with its magnitude, in place.
487 * What the division does to its numerator: the work below it is unsigned and the sign goes back
488 * on at the end.
489 * @return The sign as a mask, in the form NegateIf() takes.
490 */
491 [[nodiscard]] FP128_FORCE_INLINE constexpr uint64_t TakeMagnitude() noexcept
492 {
493 const uint64_t sign_bits = static_cast<uint64_t>(static_cast<int64_t>(high) >> 63);
494 NegateIf(sign_bits);
495 return sign_bits;
496 }
497
498 /**
499 * @brief The decimal digit that ten times a fraction carries into the integer part.
500 *
501 * Ten times a value below one needs four integer bits, which fixed_point128<1> to <3> do not
502 * have: their multiply by ten wraps the integer part away. The digit is therefore read from the
503 * full 192 bit product of the raw fraction and ten, and truncated - a digit is the floor of the
504 * product, never rounded, or 0.25 would print as 0.35 and 0.96 would produce the character after
505 * '9'.
506 *
507 * @param low Low QWORD of the fraction, a non negative value below one.
508 * @param high High QWORD of the fraction.
509 * @return floor(10 * fraction), in [0, 9].
510 */
511 [[nodiscard]] FP128_INLINE static constexpr uint64_t DigitTimesTen(uint64_t low, uint64_t high) noexcept
512 {
513 uint64_t carry_low = 0, carry_high = 0;
514 (void)mulx_u64(low, 10ull, &carry_low);
515 uint64_t middle = mulx_u64(high, 10ull, &carry_high);
516 const uint64_t top = carry_high + addcarryx_u64(0, middle, carry_low, &middle);
517 // the product carries F fraction bits; what is above them is the digit
518 return shift_right128(middle, top, upper_frac_bits);
519 }
520
521 /**
522 * @brief Extracts the mantissa of a floating point representation of this object, rounded.
523 *
524 * Keeps the frac_bits+1 most significant bits of the magnitude and rounds the dropped
525 * remainder to nearest, ties going to even. This is what IEEE 754 mandates and what the
526 * builtin conversions do.<BR>
527 * Rounding needs three pieces of information: the bits that survive, the highest dropped bit
528 * (which chooses the direction) and whether anything below it is set (the sticky bit, which
529 * distinguishes an exact tie from a remainder larger than half). The caller passes the
530 * magnitude, so the sign plays no part here.
531 *
532 * @param low Low QWORD of the magnitude.
533 * @param high High QWORD of the magnitude.
534 * @param msb Bit position of the most significant set bit. Must be larger than frac_bits.
535 * @param frac_bits Fraction bit count of the target type, 23 for float or 52 for double.
536 * @return The rounded mantissa. Holds frac_bits+1 bits, or frac_bits+2 when rounding carried
537 * into the next power of 2.
538 */
539 [[nodiscard]] FP128_INLINE static constexpr uint64_t RoundedMantissa(uint64_t low, uint64_t high, int32_t msb, int32_t frac_bits) noexcept
540 {
541 const int32_t shift = msb - frac_bits; // count of dropped bits, at least 1
542 uint64_t mant = shift_right128(low, high, shift);
543
544 // the highest dropped bit sits just below the mantissa
545 const uint64_t round_bit = (shift <= 64) ? FP128_GET_BIT(low, shift - 1) : FP128_GET_BIT(high, shift - 65);
546 if (round_bit == 0)
547 return mant; // remainder is below half, round down
548
549 // is anything set below the rounding bit? Each branch below shifts the bits of interest
550 // to the top of the QWORD, which avoids building a mask of a variable width.
551 bool sticky;
552 if (shift < 2) {
553 sticky = false; // the rounding bit is the only dropped bit
554 } else if (shift <= 64) {
555 sticky = (low << (65 - shift)) != 0; // bits [shift-2:0] of low
556 } else if (shift == 65) {
557 sticky = low != 0; // all of low, nothing of high
558 } else {
559 sticky = low != 0 || (high << (129 - shift)) != 0; // all of low plus bits [shift-66:0] of high
560 }
561
562 // above half always rounds up, an exact tie rounds towards the even mantissa
563 if (sticky || (mant & 1))
564 ++mant;
565
566 return mant;
567 }
568
569public:
570 /**
571 * @brief Reads the raw representation: the two QWORDs of the 128 bit two's complement value.
572 * @param l Receives the low QWORD
573 * @param h Receives the high QWORD, sign included
574 */
575 FP128_FORCE_INLINE constexpr void get_components(uint64_t& l, uint64_t& h) const noexcept
576 {
577 l = low;
578 h = high;
579 }
580
581 static constexpr uint64_t max_int_value = FP128_MAX_VALUE_64(I); ///< Largest representable positive integer, 2^I - 1.
582 typedef fixed_point128<I> type; ///< Self type alias.
583 typedef fixed_point128<I>* ptr_type; ///< Pointer type alias.
584 typedef fixed_point128<I>& ref_type; ///< Reference type alias.
585
586 /// @name Constructors
587 /// @{
588
589 /**
590 * @brief Default constructor, creates an instance with a value of zero.
591 */
592 FP128_FORCE_INLINE constexpr fixed_point128() noexcept : low(0), high(0) {}
593 /**
594 * @brief Copy constructor
595 * @param rhs Object to copy from
596 */
597 FP128_FORCE_INLINE constexpr fixed_point128(const fixed_point128& rhs) noexcept : low(rhs.low), high(rhs.high) {}
598 /**
599 * @brief cross-template Copy constructor, can be used between two different fixed_point128 templates
600 * A value too large for the destination wraps silently, as everywhere else in this class. Fraction
601 * bits the destination cannot hold are rounded to nearest, a tie going away from zero.
602 * @param rhs fixed_point128 instance with from a different template instance.
603 */
604 template <int32_t I2> FP128_FORCE_INLINE constexpr fixed_point128(const fixed_point128<I2>& rhs) noexcept
605 {
606 if constexpr (I == I2) {
607 high = rhs.high;
608 low = rhs.low;
609 }
610 // rhs has less integer bits and more fraction bits
611 else if constexpr (I < I2) {
612 // shift left by I2 - I bits
613 constexpr int shift = I2 - I;
614 low = rhs.low << shift;
615 high = shift_left128(rhs.low, rhs.high, shift);
616 }
617 // rhs has more integer bits and less fraction bits
618 else { // I > I2
619 // shift right by I - I2 bits, replicating the sign bit so a negative value stays negative,
620 // and round the dropped fraction bits to nearest
621 constexpr int shift = I - I2;
622 low = rhs.low;
623 high = rhs.high;
624 shift_right128_inplace_safe_signed(low, high, shift);
625 }
626 }
627
628 /**
629 * @brief Move constructor
630 * Doesn't modify the right hand side object. Acts like a copy constructor.
631 * @param rhs Object to copy from
632 */
633 FP128_FORCE_INLINE constexpr fixed_point128(fixed_point128&& rhs) noexcept : low(rhs.low), high(rhs.high) {}
634 /**
635 * @brief Constructor from the double type
636 * Underflow goes to zero. Overflow, NaN and +-INF saturate to the extreme value carrying the
637 * sign of the input: max() for a positive one and lowest() for a negative one.
638 * Not constexpr: the exponent and mantissa are read through the Double union, and reading the
639 * inactive member of a union is not allowed during constant evaluation.
640 * @param x Input value
641 */
642 FP128_INLINE constexpr fixed_point128(double x) noexcept
643 {
644 // very common case
645 if (x == 0) {
646 low = high = 0;
647 return;
648 }
649
650 // hack the double bit fields
651 const Double d(x);
652
653 const uint32_t negative = static_cast<uint32_t>(d.s());
654 const int32_t e = static_cast<int32_t>(d.e()) - 1023;
655 uint64_t f = d.f();
656
657 // overflow which also catches NaN and Inf
658 if (e >= I) {
659 low = (negative) ? 0 : UINT64_MAX;
660 high = (negative) ? sign_mask : ~sign_mask;
661 return;
662 }
663
664 // normal number, produces non zero value
665 if (e >= -F) {
666 // bit 52 in f is the unity value of the float. it needs to move to the unity position in fixed point
668 // the leading one of f sits at bit 52 and belongs at bit F + e, which is this many bits
669 // into the upper QWORD. The magnitude is built first and negated below if needed.
670 int32_t bits_to_shift = F - 64 - dbl_frac_bits + e;
671
672 // f fits in high QWORD
673 if (bits_to_shift >= 0) {
674 high = f << bits_to_shift;
675 low = 0;
676 }
677 // shift right
678 else {
679 bits_to_shift = -bits_to_shift;
680 // f has some bits in high QWORD
681 if (bits_to_shift <= 53) {
682 high = f >> bits_to_shift;
683 low = FP128_GET_BITS(f, 0, bits_to_shift);
684 low <<= 64ll - bits_to_shift;
685 }
686 // shift f into low QWORD
687 else {
688 high = 0;
689 // f has bit 52 high, shift it left to moves to bit 63
690 f <<= 63 - dbl_frac_bits;
691 bits_to_shift -= 64 - (63 - dbl_frac_bits);
692 low = f >> bits_to_shift;
693 }
694 }
695
696 if (negative)
697 Negate();
698 }
699 // too small to be represented, no need to bother.
700 else {
701 high = low = 0;
702 }
703 }
704 /**
705 * @brief Constructor from uint64_t type
706 * A value of 2^I or above overflows into the sign and wraps silently.
707 * @param x Input value
708 */
709 FP128_FORCE_INLINE constexpr fixed_point128(uint64_t x) noexcept
710 {
711 low = 0;
712 high = x << upper_frac_bits;
713 }
714 /**
715 * @brief Constructor from int64_t type
716 * The shift is done in the unsigned domain, where it wraps rather than overflowing, and a
717 * negative value carries its sign bits along with it: scaling a two's complement value by a
718 * power of two is the same left shift its magnitude needs.
719 * @param x Input value
720 */
721 FP128_FORCE_INLINE constexpr fixed_point128(int64_t x) noexcept
722 {
723 low = 0;
724 high = static_cast<uint64_t>(x) << upper_frac_bits;
725 }
726 /**
727 * @brief Constructor from uint32_t type
728 * @param x Input value
729 */
730 FP128_FORCE_INLINE constexpr fixed_point128(uint32_t x) noexcept
731 {
732 low = 0;
733 high = static_cast<uint64_t>(x) << upper_frac_bits;
734 }
735 /**
736 * @brief Constructor from int32_t type
737 * @param x Input value
738 */
739 FP128_FORCE_INLINE constexpr fixed_point128(int32_t x) noexcept
740 {
741 low = 0;
742 // sign extended to 64 bits first, see the int64_t constructor
743 high = static_cast<uint64_t>(static_cast<int64_t>(x)) << upper_frac_bits;
744 }
745 /**
746 * @brief Constructor from const char* (C string).
747 *
748 * Reads optional leading white space, an optional sign, decimal digits and an optional point
749 * followed by more digits, and stops at the first character that is not part of that. The value
750 * is the grid value nearest the decimal one, a tie going away from zero - correctly rounded
751 * for any number of digits and any I, which is what lets every value survive the trip through
752 * its own text form.
753 *
754 * The digits after the point are read as one exact integer and scaled by 2^F / 10^digits in big
755 * integer arithmetic, see ParseDecimal(). They used to be summed as a series of powers of ten held
756 * to 126 bits each, which was 22.8 ulp off at I = 1 and 3 ulp off at I = 4.
757 *
758 * Much slower than the other constructors. A value too large for the type wraps silently, modulo
759 * 2^(I+1) in its integer part, which unlike the saturation the double constructor performs can
760 * land on either sign; the stream extractor reports it instead.
761 * @param x Input string
762 */
763 fixed_point128(const char* x) noexcept
764 {
765 low = high = 0;
766 if (x == nullptr)
767 return;
768
769 // skip leading white space. The cast keeps a negative char from reaching isspace, which
770 // only accepts values representable as unsigned char (or EOF).
771 while (*x && isspace(static_cast<unsigned char>(*x)))
772 ++x;
773
774 const char* end = nullptr;
775 (void)ParseDecimal(x, x + strlen(x), low, high, end);
776 }
777 /**
778 * @brief Constructor from std::string.
779 * Accurate to 37 digits after the decimal point.
780 * Allows creating very high precision values. Much slower than the rhs constructors.
781 * @param x Input string
782 */
783 FP128_INLINE fixed_point128(const std::string& x) noexcept
784 {
785 fixed_point128 temp = x.c_str();
786 *this = temp;
787 }
788 /**
789 * @brief Constructor from the two QWORDs of the raw value, useful for creating very small constants.
790 * The pair is read as a 128 bit two's complement integer scaled by 2^-F, so a negative value is
791 * spelled with the MSB of h set rather than with a separate sign.
792 * @param l Low QWORD
793 * @param h High QWORD, sign included
794 */
795 FP128_FORCE_INLINE constexpr fixed_point128(uint64_t l, uint64_t h) noexcept : low(l), high(h) {}
796
797 /**
798 * @brief Destructor
799 */
800 constexpr ~fixed_point128() noexcept = default;
801 /**
802 * @brief Assignment operator
803 * @param rhs Object to copy from
804 * @return This object.
805 */
806 FP128_FORCE_INLINE constexpr fixed_point128& operator=(const fixed_point128& rhs) noexcept
807 {
808 high = rhs.high;
809 low = rhs.low;
810 return *this;
811 }
812 /**
813 * @brief Move assignment operator
814 * @param rhs Object to copy from
815 * @return This object.
816 */
818 {
819 high = rhs.high;
820 low = rhs.low;
821 return *this;
822 }
823 /**
824 * @brief cross-template assignment operator, can be used between two different fixed_point128 templates
825 * Behaves as the cross-template constructor: a value too large for this instantiation wraps, and
826 * fraction bits it cannot hold are rounded to nearest, a tie going away from zero.
827 * @param rhs fixed_point128 instance with from a different template instance.
828 * @return This object.
829 */
830 template <int32_t I2> FP128_FORCE_INLINE constexpr fixed_point128<I>& operator=(const fixed_point128<I2>& rhs) noexcept
831 {
832 if constexpr (I == I2) {
833 high = rhs.high;
834 low = rhs.low;
835 }
836 // rhs has less integer bits and more fraction bits
837 else if constexpr (I < I2) {
838 // shift left by I2 - I bits
839 constexpr int shift = I2 - I;
840 low = rhs.low << shift;
841 high = shift_left128(rhs.low, rhs.high, shift);
842 }
843 // rhs has more integer bits and less fraction bits
844 else { // I > I2
845 // shift right by I - I2 bits, replicating the sign bit and rounding to nearest
846 constexpr int shift = I - I2;
847 low = rhs.low;
848 high = rhs.high;
849 shift_right128_inplace_safe_signed(low, high, shift);
850 }
851
852 return *this;
853 }
854
855 //
856 /// @}
857
858 /// @name Conversion Operators
859 /// @{
860
861 /**
862 * @brief operator int64_t - converts to a int64_t
863 * The fraction is truncated towards zero, as the builtin floating point to integer conversions
864 * do, rather than shifted away - which would round a negative value towards minus infinity.
865 * @return Object value.
866 */
867 [[nodiscard]] FP128_FORCE_INLINE constexpr operator int64_t() const noexcept
868 {
869 uint64_t l = 0, h = 0;
870 const uint64_t sign_bits = GetMagnitude(l, h);
871 const uint64_t magnitude = h >> upper_frac_bits;
872 // negated in the unsigned domain, which wraps instead of overflowing for the most negative
873 // value of a 64 bit result. (x ^ -1) - -1 is that negation, and (x ^ 0) - 0 leaves it.
874 return static_cast<int64_t>((magnitude ^ sign_bits) - sign_bits);
875 }
876 /**
877 * @brief operator uint64_t - converts to a uint64_t
878 * A negative value wraps modulo 2^64, the way a builtin signed to unsigned conversion does.
879 * @return Object value.
880 */
881 [[nodiscard]] FP128_FORCE_INLINE constexpr operator uint64_t() const noexcept { return static_cast<uint64_t>(operator int64_t()); }
882 /**
883 * @brief operator int32_t - converts to a int32_t
884 * @return Object value, truncated towards zero and wrapped to 32 bits.
885 */
886 [[nodiscard]] FP128_FORCE_INLINE constexpr operator int32_t() const noexcept { return static_cast<int32_t>(operator int64_t()); }
887 /**
888 * @brief operator uint32_t - converts to a uint32_t
889 * @return Object value, truncated towards zero and wrapped to 32 bits.
890 */
891 [[nodiscard]] FP128_FORCE_INLINE constexpr operator uint32_t() const noexcept { return static_cast<uint32_t>(operator int64_t()); }
892 /**
893 * @brief operator float - converts to a float
894 * Not constexpr: the result is assembled through the Float union, and writing one member of a
895 * union and reading another is not allowed during constant evaluation.
896 * @return Object value.
897 */
898 [[nodiscard]] FP128_INLINE constexpr operator float() const noexcept
899 {
900 if (!*this)
901 return 0.0f;
902
903 // the conversion is done on the magnitude, the sign is put back by Float::make()
904 uint64_t l = 0, h = 0;
905 const uint32_t s = static_cast<uint32_t>(GetMagnitude(l, h) & 1);
906 const int32_t msb = 127 - static_cast<int32_t>(lzcnt128(l, h));
907 const int32_t expo = msb - F; // base 2 exponent of the value
908
909 // A float only reaches down to 2^-126 before going denormal. The smallest value of any
910 // instantiation is 2^-F, and F peaks at 126, so no value here is denormal as a float.
911
912 // the value fits in the fraction, no bits are lost so no rounding is needed.
913 // float doesn't hold the msb, it's implicit, so bit [22:0] hold the rest of the value
914 if (msb <= flt_frac_bits) {
915 return Float::make(s, static_cast<uint32_t>(expo + 127), static_cast<uint32_t>(l << (flt_frac_bits - msb)));
916 }
917
918 // more bits than the fraction can hold, drop the extra ones with rounding.
919 // rounding up can carry into the next power of 2, costing a fraction bit and
920 // incrementing the exponent
921 const uint64_t mant = RoundedMantissa(l, h, msb, flt_frac_bits);
922 const uint64_t carry = mant >> (flt_frac_bits + 1);
923 return Float::make(s, static_cast<uint32_t>(expo + static_cast<int32_t>(carry) + 127), static_cast<uint32_t>(mant >> carry));
924 }
925 /**
926 * @brief operator double - converts to a double
927 * The whole value range is within reach of a double's exponent, so nothing overflows or
928 * goes denormal.
929 * Not constexpr: the result is assembled through the Double union, and writing one member of a
930 * union and reading another is not allowed during constant evaluation.
931 * @return Object value, rounded to nearest with ties going to even.
932 */
933 [[nodiscard]] FP128_INLINE constexpr operator double() const noexcept
934 {
935 if (!*this)
936 return 0.0;
937
938 // the conversion is done on the magnitude, the sign is put back by Double::make()
939 uint64_t l = 0, h = 0;
940 const uint64_t s = GetMagnitude(l, h) & 1;
941 const int32_t msb = 127 - static_cast<int32_t>(lzcnt128(l, h));
942 const int32_t expo = msb - F; // base 2 exponent of the value
943
944 // the value fits in the fraction, no bits are lost so no rounding is needed.
945 // double doesn't hold the msb, it's implicit, so bit [51:0] hold the rest of the value
946 if (msb <= dbl_frac_bits) {
947 return Double::make(s, static_cast<uint64_t>(expo + 1023), l << (dbl_frac_bits - msb));
948 }
949
950 // more bits than the fraction can hold, drop the extra ones with rounding.
951 // rounding up can carry into the next power of 2, costing a fraction bit and
952 // incrementing the exponent
953 const uint64_t mant = RoundedMantissa(l, h, msb, dbl_frac_bits);
954 const uint64_t carry = mant >> (dbl_frac_bits + 1);
955 return Double::make(s, static_cast<uint64_t>(expo + static_cast<int32_t>(carry) + 1023), mant >> carry);
956 }
957 /**
958 * @brief operator long double - converts to a long double
959 * @return Object value.
960 */
961 [[nodiscard]] FP128_FORCE_INLINE constexpr operator long double() const noexcept { return operator double(); }
962 /**
963 * @brief Converts to a std::string (slow) string holds all meaningful fraction bits.
964 * @return object string representation
965 */
966 [[nodiscard]] FP128_INLINE operator std::string() const noexcept { return operator char*(); }
967 /**
968 * @brief Converts to a C string (slow) string holds all meaningful fraction bits.
969 * @return object string representation
970 */
971 [[nodiscard]] explicit FP128_INLINE operator char*() const noexcept
972 {
973 static thread_local char str[128]; // need roughly a (meaningful) decimal digits per 3.2 bits
974
975 char* p = &str[0];
976 // the digits are produced from the magnitude, the sign is written out separately
977 uint64_t l = 0, h = 0;
978 if (GetMagnitude(l, h))
979 *p++ = '-';
980
981 uint64_t integer = FP128_GET_BITS(h, upper_frac_bits, I + 1);
982 // the size argument is what is left of the buffer, not its total size plus the offset
983 p += snprintf(p, sizeof(str) - static_cast<size_t>(p - str), "%llu", integer);
984 // what is left is the fraction, which is below one and so always a positive value of this type
985 fixed_point128 temp(l, h & ~int_mask);
986 // check if temp has additional digits (not zero)
987 if (temp) {
988 *p++ = '.';
989 }
990 // the faster way, requires temp *= 10 not overflowing
991 int digits = 0;
992 while (digits++ < max_frac_digits && temp) {
993 if constexpr (I < 4) {
994 integer = DigitTimesTen(temp.low, temp.high);
995 temp *= 10; // move another digit to the integer area, the integer part wraps
996 } else {
997 temp *= 10; // move another digit to the integer area
998 integer = FP128_GET_BITS(temp.high, upper_frac_bits, I + 1);
999 }
1000 *p++ = '0' + (char)integer;
1001 temp.high &= ~int_mask;
1002 }
1003 // round: if we stopped due to max_frac_digits and there's still a remaining
1004 // fraction, peek at the next digit and round up if >= 5
1005 if (temp) {
1006 uint64_t next_digit;
1007 if constexpr (I < 4) {
1008 next_digit = DigitTimesTen(temp.low, temp.high);
1009 } else {
1010 fixed_point128 t = temp;
1011 t *= 10;
1012 next_digit = FP128_GET_BITS(t.high, upper_frac_bits, I + 1);
1013 }
1014 if (next_digit >= 5) {
1015 // carry-propagate backwards through the digit string
1016 char* q = p - 1;
1017 bool carry = true;
1018 while (carry && q >= &str[0]) {
1019 if (*q >= '0' && *q <= '9') {
1020 if (*q == '9') {
1021 *q-- = '0';
1022 } else {
1023 ++(*q);
1024 carry = false;
1025 }
1026 } else {
1027 --q; // skip '.' or '-'
1028 }
1029 }
1030 if (carry) {
1031 // all digits were 9 (e.g. "9.999" → "10.000")
1032 // insert '1' before the integer digits, after any '-'
1033 char* start = str + (str[0] == '-' ? 1 : 0);
1034 memmove(start + 1, start, p - start + 1); // +1 for '\0'
1035 *start = '1';
1036 ++p;
1037 }
1038 }
1039 }
1040 *p = '\0';
1041 // remove trailing zeros after the decimal point
1042 if (char* dot = strchr(str + (str[0] == '-' ? 1 : 0), '.')) {
1043 char* last = p - 1;
1044 while (last > dot && *last == '0')
1045 --last;
1046 if (last == dot)
1047 --last; // remove the dot too if no fraction remains
1048 *(last + 1) = '\0';
1049 }
1050 return str;
1051 }
1052 /// @}
1053
1054 /// @name Arithmetic Operators
1055 /// @{
1056
1057 /**
1058 * @brief Performs right shift operation.
1059 *
1060 * Hinted rather than forced, unlike the other one line forwarders (see FP128_FORCE_INLINE).
1061 * operator>>= is itself forced, so forcing this one too would expand the whole shift, its
1062 * rounding included, at every use of the by value form. The equivalent pair in float128
1063 * measurably hurt a loop that shifts alongside other arithmetic; this one is left hinted for
1064 * the same reason. The callee being forced means the shift is inlined either way once the
1065 * compiler decides to inline this wrapper.
1066 *
1067 * @param shift bits to shift
1068 * @return Temporary object with the result of the operation
1069 */
1070 template <typename T> [[nodiscard]] FP128_INLINE constexpr fixed_point128 operator>>(T shift) const noexcept
1071 {
1072 fixed_point128 temp(*this);
1073 return temp >>= static_cast<int32_t>(shift);
1074 }
1075 /**
1076 * @brief Performs left shift operation.
1077 * Hinted rather than forced, see operator>> above.
1078 * @param shift bits to shift
1079 * @return Temporary object with the result of the operation
1080 */
1081 template <typename T> [[nodiscard]] FP128_INLINE constexpr fixed_point128 operator<<(T shift) const noexcept
1082 {
1083 fixed_point128 temp(*this);
1084 return temp <<= static_cast<int32_t>(shift);
1085 }
1086 /**
1087 * @brief Add a value to this object
1088 * @param rhs Right hand side operand
1089 * @return This object.
1090 */
1092 {
1093 // a two's complement addition needs no attention to the signs at all: the sum of the two
1094 // 128 bit patterns is the pattern of the sum, and a result outside the range wraps silently
1095 const uint8_t carry = addcarryx_u64(0, low, rhs.low, &low);
1096 addcarryx_u64(carry, high, rhs.high, &high);
1097 return *this;
1098 }
1099 /**
1100 * @brief Add a value to this object
1101 * @param rhs Right hand side operand
1102 * @return This object.
1103 */
1104 template <typename T> FP128_FORCE_INLINE constexpr fixed_point128& operator+=(const T& rhs) noexcept { return operator+=(fixed_point128(rhs)); }
1105 /**
1106 * @brief Subtract a value to this object
1107 * @param rhs Right hand side operand
1108 * @return This object.
1109 */
1111 {
1112 // subtracted directly rather than by adding the two's complement of rhs, which would cost
1113 // a negation that the borrow chain gets for free. Both wrap on overflow.
1114 const uint8_t borrow = subborrow_u64(0, low, rhs.low, &low);
1115 subborrow_u64(borrow, high, rhs.high, &high);
1116 return *this;
1117 }
1118 /**
1119 * @brief Subtract a value to this object
1120 * @param rhs Right hand side operand
1121 * @return This object.
1122 */
1123 template <typename T> FP128_FORCE_INLINE constexpr fixed_point128& operator-=(const T& rhs) noexcept { return operator-=(fixed_point128(rhs)); }
1124 /**
1125 * @brief Multiplies a value to this object
1126 * @param rhs Right hand side operand
1127 * @return This object.
1128 */
1130 {
1131 // The 256 bit intermediate product lives in four named locals rather than an array. Both
1132 // spellings hand the address of a QWORD to the extended arithmetic intrinsics, but MSVC
1133 // promotes the scalars into registers more readily than array elements and stops parking
1134 // a couple of the partial products on the stack.
1135 // They are left uninitialized to get 10-50% extra performance. Zero initialization is a
1136 // 10% penalty and using a thread_local static variable lowers performance by >50%.
1137 uint64_t r0, r1, r2, r3; // 256 bit of result, low QWORD first
1138
1139 // The magnitudes are multiplied and the sign is put back at the end. Multiplying the two's
1140 // complement patterns directly is possible - the signed product is the unsigned one less
1141 // 2^128 times each negative operand, and the window kept below reaches that far - but it
1142 // rounds the tie of a negative product towards positive infinity, and correcting that back
1143 // to away from zero costs more than it saves. Three spellings of the correction were
1144 // measured against this one and every one of them was slower, by 20% here and by up to 20%
1145 // again in the functions built on it.
1146 uint64_t lhs_low = 0, lhs_high = 0, rhs_low = 0, rhs_high = 0;
1147 const uint64_t result_sign = GetMagnitude(lhs_low, lhs_high) ^ rhs.GetMagnitude(rhs_low, rhs_high);
1148
1149 // multiply low QWORDs
1150 r0 = mulx_u64(lhs_low, rhs_low, &r1);
1151
1152 // multiply high QWORDs (overflow can happen)
1153 r2 = mulx_u64(lhs_high, rhs_high, &r3);
1154
1155 // Each cross product is folded in as one unbroken carry chain across r1, r2 and r3.
1156 // Spelling the last link as a third addcarryx_u64 of zero rather than as `r3 += carry`
1157 // is what keeps it a chain: MSVC cannot fold an added carry return value back into an
1158 // ADC and emits SETB, MOVZX and ADD in its place, three instructions and three cycles of
1159 // latency where the chain wants one. Clang folds either spelling into ADC and is
1160 // unaffected. Together with the named locals above this took the Mandelbrot escape-time
1161 // loop from 212 to 195 instructions (25 to 19 stack accesses, 9 to 15 ADCX, 6 to 0 MOVZX)
1162 // and about 6% off the fp128 render under MSVC, on both P and E cores. The results are
1163 // bit identical either way.
1164
1165 // multiply low this and high rhs
1166 uint64_t cross_high = 0;
1167 uint64_t cross_low = mulx_u64(lhs_low, rhs_high, &cross_high);
1168 uint8_t carry = addcarryx_u64(0, r1, cross_low, &r1);
1169 carry = addcarryx_u64(carry, r2, cross_high, &r2);
1170 addcarryx_u64(carry, r3, 0, &r3);
1171
1172 // multiply high this and low rhs
1173 cross_low = mulx_u64(lhs_high, rhs_low, &cross_high);
1174 carry = addcarryx_u64(0, r1, cross_low, &r1);
1175 carry = addcarryx_u64(carry, r2, cross_high, &r2);
1176 addcarryx_u64(carry, r3, 0, &r3);
1177
1178 // extract the bits from the product keeping the precision the same as this object
1179 // shift result by F
1180 constexpr int32_t index = (F == 64) ? 0 : F / 64;
1181 constexpr int32_t lsb = (F == 64) ? 64 : (F & FP128_MAX_VALUE_64(6)); // bit within the 64bit QWORD at `index`
1182 constexpr uint64_t half = 1ull << (lsb - 1); // used for rounding
1183
1184 // The three consecutive QWORDs the result is read from, starting at `index`. I is
1185 // constrained to [1,63], so F is in [64,126] and `index` is 0 or 1: what was an array
1186 // subscript is a compile time choice between two triples.
1187 const uint64_t w0 = (index == 0) ? r0 : r1;
1188 const uint64_t w1 = (index == 0) ? r1 : r2;
1189 const uint64_t w2 = (index == 0) ? r2 : r3;
1190 const bool need_rounding = (w0 & half) != 0;
1191
1192 // copy block #1 (lowest)
1193 low = shift_right128<lsb>(w0, w1);
1194 high = shift_right128<lsb>(w1, w2);
1195
1196 FP128_ADD_ROUND_BIT(low, high, need_rounding);
1197 NegateIf(result_sign);
1198 return *this;
1199 }
1200 /**
1201 * @brief Squares this object in place.
1202 *
1203 * Cheaper than operator*=(*this): a square is symmetric, so the two cross products
1204 * low*high and high*low are the same value and only one 64x64->128 bit multiply is
1205 * needed instead of two. The sign is also known in advance - a magnitude times itself is
1206 * the answer as it stands - which removes the sign combination and the negation.
1207 *
1208 * The 256 bit intermediate product is accumulated exactly as in operator*=, so the
1209 * result is bit identical to (*this) * (*this), including rounding.
1210 *
1211 * @return This object.
1212 */
1214 {
1215 // Named locals rather than arrays, and one unbroken carry chain per cross product, for
1216 // the reasons spelled out in operator*=. They are left uninitialized to get extra
1217 // performance, same as there.
1218 uint64_t r0, r1, r2, r3; // 256 bit of result, low QWORD first
1219
1220 // squared on the magnitude, as operator*= multiplies on it, which is what makes the two
1221 // agree bit for bit for a negative value as well as a positive one
1222 uint64_t l = 0, h = 0;
1223 (void)GetMagnitude(l, h);
1224
1225 // multiply the low QWORD by itself
1226 r0 = mulx_u64(l, l, &r1);
1227
1228 // multiply the high QWORD by itself (overflow can happen)
1229 r2 = mulx_u64(h, h, &r3);
1230
1231 // the low * high cross product, which appears twice in the sum
1232 uint64_t cross_high = 0;
1233 const uint64_t cross_low = mulx_u64(l, h, &cross_high);
1234
1235 uint8_t carry = addcarryx_u64(0, r1, cross_low, &r1);
1236 carry = addcarryx_u64(carry, r2, cross_high, &r2);
1237 addcarryx_u64(carry, r3, 0, &r3);
1238
1239 carry = addcarryx_u64(0, r1, cross_low, &r1);
1240 carry = addcarryx_u64(carry, r2, cross_high, &r2);
1241 addcarryx_u64(carry, r3, 0, &r3);
1242
1243 // extract the bits from the product keeping the precision the same as this object
1244 // shift result by F
1245 constexpr int32_t index = (F == 64) ? 0 : F / 64;
1246 constexpr int32_t lsb = (F == 64) ? 64 : (F & FP128_MAX_VALUE_64(6)); // bit within the 64bit QWORD at `index`
1247 constexpr uint64_t half = 1ull << (lsb - 1); // used for rounding
1248
1249 // the three consecutive QWORDs the result is read from, see the note in operator*=
1250 const uint64_t w0 = (index == 0) ? r0 : r1;
1251 const uint64_t w1 = (index == 0) ? r1 : r2;
1252 const uint64_t w2 = (index == 0) ? r2 : r3;
1253 const bool need_rounding = (w0 & half) != 0;
1254
1255 // copy block #1 (lowest)
1256 low = shift_right128<lsb>(w0, w1);
1257 high = shift_right128<lsb>(w1, w2);
1258
1259 FP128_ADD_ROUND_BIT(low, high, need_rounding);
1260 return *this;
1261 }
1262 /**
1263 * @brief Multiplies a value to this object
1264 * @param x Right hand side operand
1265 * @return This object.
1266 */
1267 template <typename T> FP128_FORCE_INLINE constexpr fixed_point128& operator*=(T x) noexcept
1268 {
1269 // floating point
1270 if constexpr (std::is_floating_point_v<T>) {
1271 return operator*=(fixed_point128(x));
1272 } else {
1273 // integers: convert to uint64 for a simpler operation. The magnitude is taken in the
1274 // unsigned domain, where the negation wraps; negating the signed value is undefined
1275 // for the most negative one.
1276 uint64_t magnitude = static_cast<uint64_t>(x);
1277 bool negate_result = false;
1278 if constexpr (std::is_signed_v<T>) {
1279 // always do positive multiplication
1280 if (x < 0) {
1281 magnitude = 0ull - magnitude;
1282 negate_result = true;
1283 }
1284 }
1285
1286 operator*=(magnitude);
1287 if (negate_result)
1288 Negate();
1289
1290 return *this;
1291 }
1292 }
1293 /**
1294 * @brief Multiplies a 64 bit value to this object
1295 * The product is taken modulo 2^128, which is the signed product of a two's complement value by
1296 * an unsigned one: multiplying is repeated addition and addition already wraps correctly.
1297 * @param x Right hand side operand
1298 * @return This object.
1299 */
1300 template <> FP128_FORCE_INLINE constexpr fixed_point128& operator*= <uint64_t>(uint64_t x) noexcept
1301 {
1302 uint64_t temp;
1303
1304 // multiply low QWORDs
1305 low = mulx_u64(low, x, &temp);
1306 high = high * x + temp;
1307 return *this;
1308 }
1309 /**
1310 * @brief Divide this object by x.
1311 * The quotient is rounded to nearest, a tie going away from zero, whichever of the three paths
1312 * below computes it.
1313 * @param rhs Right hand side operator (denominator)
1314 * @return this object.
1315 * @throws std::logic_error when rhs is zero - zero divided by zero included - leaving this object
1316 * in an unspecified state: the magnitude of what it held, the sign not yet put back.
1317 */
1319 {
1320 bool need_rounding = false;
1321 // A zero numerator needs no shortcut: every path below produces zero for it. Taking one here
1322 // used to return zero for 0 / 0 too, where the division by zero has to throw.
1323
1324 // The sign of the quotient is settled here and everything below works on magnitudes: the
1325 // shift, div_64bit and the long division are all unsigned. Taking the magnitude of the
1326 // numerator in place leaves this object holding it until the sign is put back at the end.
1327 uint64_t denom_low = 0, denom_high = 0;
1328 const uint64_t result_sign = TakeMagnitude() ^ rhs.GetMagnitude(denom_low, denom_high);
1329
1330 // exponent of 2, convert to a much faster shift operation
1331 if (1 == popcnt128(denom_low, denom_high)) {
1332 // the leading one of the magnitude sits at bit 127 - lzcnt and stands for 2^(that - F)
1333 const int32_t expo = I - static_cast<int32_t>(lzcnt128(denom_low, denom_high));
1334 if (expo > 0)
1335 shift_right128_inplace_safe(low, high, expo);
1336 else if (expo < 0)
1337 shift_left128_inplace_safe(low, high, -expo);
1338 }
1339 // optimization for when dividing by an integer. The integer part of a magnitude is at most
1340 // 2^63, so it always fits in the QWORD div_64bit takes.
1341 else if (rhs.is_int()) {
1342 uint64_t q[2] {};
1343 const uint64_t nom[2] = {low, high};
1344 const uint64_t denom = denom_high >> upper_frac_bits;
1345 uint64_t r;
1346 if (div_64bit((uint64_t*)q, &r, (uint64_t*)nom, denom, 2)) {
1347 // round half up on the magnitude, the rule the long division and the multiply use:
1348 // 2r >= denom, spelled so that it cannot overflow
1349 need_rounding = r >= denom - r;
1350 high = q[1];
1351 low = q[0];
1352 } else { // error
1354 }
1355 } else {
1356 bool use_long_division = true;
1357 if constexpr (FP128_USE_RECIPROCAL_FOR_DIVISION != 0) {
1358 // A numerator magnitude of 2^127 is what lowest() leaves behind. It reads as a
1359 // negative value of this type, so the multiply cannot be used for it and the long
1360 // division, which works on the raw QWORDs, takes over. Every other magnitude, and
1361 // the divisor's - which is not a power of two here, so it is not 2^127 either -
1362 // is an ordinary positive value.
1363 use_long_division = high >= sign_mask;
1364 if (!use_long_division)
1365 *this *= reciprocal(fixed_point128(denom_low, denom_high));
1366 }
1367
1368 if (use_long_division)
1369 need_rounding = DivideMagnitude(denom_low, denom_high);
1370 }
1371
1372 // Left as a branch, unlike the carry propagating form operator*= and square() use. Both
1373 // spellings were measured here: this one is 9% faster on the 128 bit divisor benchmark,
1374 // because a division reaches it once rather than once per result bit and the branch is
1375 // predictable enough to be free, while the unconditional add sits on the dependency chain.
1376 if (need_rounding) {
1377 ++low;
1378 high += low == 0;
1379 }
1380 NegateIf(result_sign);
1381 return *this;
1382 }
1383 /**
1384 * @brief Divide this object by x.
1385 * @param x Denominator.
1386 * @return This object.
1387 */
1389 {
1390 if constexpr (std::is_floating_point_v<T>) {
1391 return operator/=(static_cast<double>(x));
1392 } else {
1393 // integers: convert to uint64 for a simpler operation. The magnitude is taken in the
1394 // unsigned domain, where the negation wraps; negating the signed value is undefined
1395 // for the most negative one.
1396 uint64_t magnitude = static_cast<uint64_t>(x);
1397 bool negate_result = false;
1398 if constexpr (std::is_signed_v<T>) {
1399 // always do positive division
1400 if (x < 0) {
1401 magnitude = 0ull - magnitude;
1402 negate_result = true;
1403 }
1404 }
1405
1406 operator/=(magnitude);
1407 if (negate_result)
1408 Negate();
1409
1410 return *this;
1411 }
1412 }
1413 /**
1414 * @brief Divide this object by x.
1415 * @param x Denominator.
1416 * @return This object.
1417 */
1418 template <> FP128_FORCE_INLINE fixed_point128& operator/= <double>(double x)
1419 {
1420 if (0 == x)
1422
1423 // Simple and common case, the value is an exponent of 2
1424 // Convert to a much faster shift operation
1425 const Double d(x);
1426 if (0 == d.f()) {
1427 if (d.s())
1428 Negate();
1429 const int32_t e = static_cast<int32_t>(d.e()) - 1023;
1430 return (e >= 0) ? *this >>= e : *this <<= -e;
1431 }
1432
1433 // normal division
1434 return *this /= fixed_point128(x);
1435 }
1436 /**
1437 * @brief Divide this object by x.
1438 * The quotient is rounded to nearest, a tie going away from zero: the same result as dividing by
1439 * fixed_point128(x), which the integer divisor only makes cheaper.
1440 * @param x Denominator.
1441 * @return This object.
1442 * @throws std::logic_error when x is zero.
1443 */
1444 template <> FP128_INLINE fixed_point128& operator/= <uint64_t>(uint64_t x)
1445 {
1446 if (0 == x)
1448
1449 // div_64bit is unsigned, so the magnitude is divided and the sign put back afterwards
1450 const uint64_t sign_bits = TakeMagnitude();
1451
1452 const uint64_t nom[2] = {low, high};
1453 // div_64bit shortcuts a numerator that is smaller than the divisor and returns without
1454 // writing the quotient at all, so the quotient has to start at zero. Otherwise a value whose
1455 // raw 128 bit form is below the divisor would be left completely unchanged.
1456 uint64_t q[2] {};
1457 uint64_t r = 0;
1458 // x is not zero and the pointers are valid, which are the only ways div_64bit can fail
1459 (void)div_64bit(q, &r, nom, x, 2);
1460
1461 // round half up on the magnitude: 2r >= x, spelled so that it cannot overflow
1462 low = q[0];
1463 high = q[1];
1464 FP128_ADD_ROUND_BIT(low, high, r >= x - r);
1465 NegateIf(sign_bits);
1466 return *this;
1467 }
1468 /**
1469 * @brief %= operator, the remainder of a truncating division: x - y * trunc(x / y).
1470 *
1471 * The result is exact and keeps the sign of the numerator, as fmod() does. Two values on the same
1472 * grid of 2^-F are integers scaled by the same power of two, so their remainder is the remainder
1473 * of the raw 128 bit integers, scaled the same way: no quotient is formed, so it can neither
1474 * overflow nor be rounded onto the wrong integer.
1475 *
1476 * @param rhs Modulo operand.
1477 * @return This object.
1478 * @throws std::logic_error when rhs is zero, zero modulo zero included.
1479 */
1481 {
1482 if (!rhs)
1484
1485 // magnitudes, the remainder takes the sign of this object. lowest() has the magnitude 2^127,
1486 // which an unsigned QWORD pair holds as it is.
1487 uint64_t denom_low = 0, denom_high = 0;
1488 (void)rhs.GetMagnitude(denom_low, denom_high);
1489 const uint64_t sign_bits = TakeMagnitude();
1490
1491 uint64_t rem[2] {};
1492 if (denom_high != 0) {
1493 // a divisor that needs both QWORDs; the numerator is widened to the four words
1494 // Divide256By128() takes, which costs two passes over leading zero words
1495 const uint64_t nom[4] = {low, high, 0, 0};
1496 const uint64_t denom[2] = {denom_low, denom_high};
1497 uint64_t q[3] {};
1498 (void)Divide256By128(q, rem, nom, denom);
1499 } else {
1500 const uint64_t nom[2] = {low, high};
1501 uint64_t q[2] {};
1502 (void)div_64bit(q, rem, nom, denom_low, 2);
1503 }
1504
1505 low = rem[0];
1506 high = rem[1];
1507 NegateIf(sign_bits);
1508 return *this;
1509 }
1510 /**
1511 * @brief Performs modulo with a generic type by converting to fixed_point128.
1512 * @tparam T Right hand side type
1513 * @param rhs Divisor
1514 * @return This object.
1515 */
1516 template <typename T> FP128_FORCE_INLINE fixed_point128& operator%=(T rhs) { return operator%=(fixed_point128(rhs)); }
1517 /**
1518 * @brief Shift right this object.
1519 * The shift is arithmetic: the sign bit is replicated, so the result is the value divided by
1520 * 2^shift and rounded to nearest, a tie going away from zero - the rounding rule of the multiply
1521 * and the divisions.
1522 *
1523 * That rule makes +-epsilon() a fixed point of a shift by one: epsilon() >> 1 is exactly half an
1524 * epsilon, a tie, and rounds back up to epsilon(). A loop that halves a value until it reaches
1525 * zero has to bound its iterations or test for epsilon() instead.
1526 * @param shift Bits to shift. A negative count causes undefined behavior; 128 or more leaves
1527 * zero, apart from lowest() >> 128, which is the tie -epsilon() / 2 and so -epsilon().
1528 * @return This object.
1529 */
1530 FP128_FORCE_INLINE constexpr fixed_point128& operator>>=(int32_t shift) noexcept
1531 {
1532 shift_right128_inplace_safe_signed(low, high, shift);
1533 return *this;
1534 }
1535 /**
1536 * @brief Shift left this object.
1537 * A value shifted past the range of the type wraps silently, sign included.
1538 * @param shift Bits to shift. Negative or very high values cause undefined behavior.
1539 * @return This object.
1540 */
1541 FP128_FORCE_INLINE constexpr fixed_point128& operator<<=(int32_t shift) noexcept
1542 {
1543 shift_left128_inplace_safe(low, high, shift);
1544 return *this;
1545 }
1546 /**
1547 * @brief Bitwise AND=
1548 * The operators below work on all 128 bits, the sign bit included.
1549 * @param rhs AND mask.
1550 * @return This object.
1551 */
1553 {
1554 low &= rhs.low;
1555 high &= rhs.high;
1556 return *this;
1557 }
1558 /**
1559 * @brief Bitwise AND=
1560 * @param rhs Right hand side operand
1561 * @return This object.
1562 */
1563 template <typename T> FP128_FORCE_INLINE constexpr fixed_point128& operator&=(const T& rhs) { return operator&=(fixed_point128(rhs)); }
1564 /**
1565 * @brief Bitwise OR=
1566 * @param rhs OR mask.
1567 * @return This object.
1568 */
1570 {
1571 low |= rhs.low;
1572 high |= rhs.high;
1573 return *this;
1574 }
1575 /**
1576 * @brief Bitwise OR=
1577 * @param rhs Right hand side operand
1578 * @return This object.
1579 */
1580 template <typename T> FP128_FORCE_INLINE constexpr fixed_point128& operator|=(const T& rhs) { return operator|=(fixed_point128(rhs)); }
1581 /**
1582 * @brief Bitwise XOR=
1583 * @param rhs XOR mask.
1584 * @return This object.
1585 */
1587 {
1588 low ^= rhs.low;
1589 high ^= rhs.high;
1590 return *this;
1591 }
1592 /**
1593 * @brief Bitwise XOR=
1594 * @param rhs Right hand side operand
1595 * @return This object.
1596 */
1597 template <typename T> FP128_FORCE_INLINE constexpr fixed_point128& operator^=(const T& rhs) { return operator^=(fixed_point128(rhs)); }
1598 /**
1599 * @brief Prefix ++ operation (++a)
1600 * @return This object.
1601 */
1603 {
1604 *this += one();
1605 return *this;
1606 }
1607 /**
1608 * @brief Postfix ++ operation (a++)
1609 * @return This object.
1610 */
1612 {
1613 fixed_point128 temp(*this);
1614 ++*this; // call the prefix implementation
1615 return temp;
1616 }
1617 /**
1618 * @brief Prefix -- operation (--a)
1619 * @return This object.
1620 */
1622 {
1623 *this -= one();
1624 return *this;
1625 }
1626 /**
1627 * @brief Postfix -- operation (a--)
1628 * @return This object.
1629 */
1631 {
1632 fixed_point128 temp(*this);
1633 --*this; // call the prefix implementation
1634 return temp;
1635 }
1636
1637 //
1638 // unary operations
1639 //
1640 /**
1641 * @brief Convert to bool
1642 */
1643 [[nodiscard]] FP128_FORCE_INLINE constexpr operator bool() const noexcept { return high != 0 || low != 0; }
1644 /**
1645 * @brief Logical not (!). Opposite of operator bool.
1646 */
1647 [[nodiscard]] FP128_FORCE_INLINE constexpr bool operator!() const noexcept { return high == 0 && low == 0; }
1648 /**
1649 * @brief Bitwise not (~). Flips all 128 bits, the sign included, which makes it -x - epsilon().
1650 */
1651 [[nodiscard]] FP128_FORCE_INLINE constexpr fixed_point128 operator~() const noexcept
1652 {
1653 fixed_point128 temp(*this);
1654 temp.high = ~high;
1655 temp.low = ~low;
1656 return temp;
1657 }
1658 /**
1659 * @brief Unary +. Returns a copy of the object.
1660 */
1661 [[nodiscard]] FP128_FORCE_INLINE constexpr fixed_point128 operator+() const noexcept
1662 {
1663 fixed_point128 temp(*this);
1664 return temp;
1665 }
1666 /**
1667 * @brief Unary -. Returns the two's complement of the object.
1668 * The most negative value has no positive counterpart and is returned unchanged, the same
1669 * silent wrap the builtin integer types perform.
1670 */
1671 [[nodiscard]] FP128_FORCE_INLINE constexpr fixed_point128 operator-() const noexcept
1672 {
1673 fixed_point128 temp(*this);
1674 temp.Negate();
1675 return temp;
1676 }
1677
1678 /// @}
1679
1680 /// @name Query and Utility Functions
1681 /// @{
1682
1683 /**
1684 * @brief Returns true if the value is an int (fraction is zero)
1685 * @return True when the fraction is zero.
1686 */
1687 [[nodiscard]] FP128_FORCE_INLINE constexpr bool is_int() const noexcept {
1688 if constexpr (I == 63) {
1689 // the fraction is exactly the low QWORD, shifting high by 64 would be undefined
1690 return 0 == low;
1691 } else {
1692 // the fraction bits of the upper QWORD are the ones below the integer part and the sign
1693 return 0 == low && 0 == (high << (I + 1));
1694 }
1695 }
1696 /**
1697 * @brief Returns true if the value is positive (including zero)
1698 * @return True when the value is positive
1699 */
1700 [[nodiscard]] FP128_FORCE_INLINE constexpr bool is_positive() const noexcept { return 0 == (high & sign_mask); }
1701 /**
1702 * @brief Returns true if the value negative (smaller than zero)
1703 * @return True when the value is negative
1704 */
1705 [[nodiscard]] FP128_FORCE_INLINE constexpr bool is_negative() const noexcept { return 0 != (high & sign_mask); }
1706 /**
1707 * @brief Returns true if the value is zero
1708 * @return Returns true if the value is zero
1709 */
1710 [[nodiscard]] FP128_FORCE_INLINE constexpr bool is_zero() const noexcept { return 0 == low && 0 == high; }
1711 /**
1712 * @brief get a specific bit within the 128 fixed point data
1713 * @param bit bit to get [0,127]
1714 * @return 0 or 1. Undefined when bit > 127
1715 */
1716 [[nodiscard]] FP128_FORCE_INLINE constexpr int32_t get_bit(uint32_t bit) const noexcept
1717 {
1718 if (bit < 64) {
1719 return FP128_GET_BIT(low, bit);
1720 }
1721 return FP128_GET_BIT(high, bit - 64);
1722 }
1723 /**
1724 * @brief Returns the exponent of the object - like the base 2 exponent of a floating point
1725 * A value of 2.1 would return 1, values in the range [0.5,1.0) would return -1.
1726 * Reads the magnitude, so the sign of the value makes no difference.
1727 * @return Exponent of the number
1728 */
1729 [[nodiscard]] FP128_FORCE_INLINE constexpr int32_t get_exponent() const noexcept
1730 {
1731 const int32_t s = static_cast<int32_t>(lzcnt128(*this));
1732 return I - s;
1733 }
1734 /**
1735 * @brief Returns an instance of fixed_point128 with the value of pi
1736 * Needs <B>I</B> to be 2 or more.
1737 * @return pi
1738 */
1739 [[nodiscard]] FP128_INLINE static const fixed_point128& pi() noexcept
1740 {
1741 static_assert(I >= 2, "pi() needs template parameter <I> to be at least 2: 3.14159... does not fit in one integer bit!");
1742 static const fixed_point128 pi = "3.14159265358979323846264338327950288419716939937510"; // 50 first digits of pi
1743 return pi;
1744 }
1745 /**
1746 * @brief Returns an instance of fixed_point128 with the value of pi * 2
1747 * Needs <B>I</B> to be 3 or more.
1748 * @return pi * 2
1749 */
1750 [[nodiscard]] FP128_INLINE static const fixed_point128& pi2() noexcept
1751 {
1752 static_assert(I >= 3, "pi2() needs template parameter <I> to be at least 3: 6.28318... does not fit in fewer integer bits!");
1753 static const fixed_point128 pi2 = "6.28318530717958647692528676655900576839433879875021"; // 50 first digits of pi * 2
1754 return pi2;
1755 }
1756 /**
1757 * @brief Returns an instance of fixed_point128 with the value of pi / 2
1758 * @return pi / 2
1759 */
1760 [[nodiscard]] FP128_INLINE static const fixed_point128& half_pi() noexcept
1761 {
1762 static const fixed_point128 half_pi = "1.57079632679489661923132169163975144209858469968755"; // 50 first digits of pi / 2
1763 return half_pi;
1764 }
1765 /**
1766 * @brief Returns an instance of fixed_point128 with the value of the golden ratio
1767 * @return golden ratio constant
1768 */
1769 [[nodiscard]] FP128_INLINE static const fixed_point128& golden_ratio() noexcept
1770 {
1771 static const fixed_point128 golden_ratio = "1.6180339887498948482045868343656381177203"; // 40 first digits of the golden ratio
1772 return golden_ratio;
1773 }
1774 /**
1775 * @brief Returns an instance of fixed_point128 with the value of e
1776 * Needs <B>I</B> to be 2 or more.
1777 * @return e
1778 */
1779 [[nodiscard]] FP128_INLINE static const fixed_point128& e() noexcept
1780 {
1781 static_assert(I >= 2, "e() needs template parameter <I> to be at least 2: 2.71828... does not fit in one integer bit!");
1782 static const fixed_point128 e = "2.71828182845904523536028747135266249775724709369"; // 50 first digits of e
1783 return e;
1784 }
1785 /**
1786 * @brief Returns an instance of fixed_point128 with the value of sqrt(2)
1787 * @return e
1788 */
1789 [[nodiscard]] FP128_INLINE static const fixed_point128& sqrt_2() noexcept
1790 {
1791 static const fixed_point128 sqrt_2 = "1.41421356237309504880168872420969807856967187537"; // 50 first digits of sqrt(2)
1792 return sqrt_2;
1793 }
1794 /**
1795 * @brief Return an instance of fixed_point128 with the value of 1
1796 * These three exact constants are returned by value rather than by reference like the
1797 * transcendental ones above: they are representable in every instantiation without a string
1798 * conversion, so a constexpr function can build them on the spot and callers get a compile
1799 * time constant instead of a lazily initialized static.
1800 * @return 1
1801 */
1802 [[nodiscard]] FP128_FORCE_INLINE static constexpr fixed_point128 one() noexcept { return fixed_point128(1); }
1803 /**
1804 * @brief Return an instance of fixed_point128 with the value of 0.5
1805 * Shifting one() right is exact for any <B>I</B>. Note that 0.5 lands in the low QWORD when
1806 * <B>I</B> is 63, which rules out spelling it as a constant of the upper QWORD alone.
1807 * @return 0.5
1808 */
1809 [[nodiscard]] FP128_FORCE_INLINE static constexpr fixed_point128 half() noexcept { return one() >> 1; }
1810 /**
1811 * @brief Return an instance of fixed_point128 with the smallest positive value possible
1812 * @return 1
1813 */
1814 [[nodiscard]] FP128_FORCE_INLINE static constexpr fixed_point128 epsilon() noexcept { return fixed_point128(1, 0); }
1815
1816private:
1817 /**
1818 * @brief Number of Mercator series terms log2_fraction() needs for this instantiation.
1819 *
1820 * The reduction leaves |z| <= 2^-6, so term n is bounded by 2^(-6n), and the series is cut off
1821 * once that is below the last bit of the result with eight bits to spare.
1822 */
1823 static constexpr int32_t LOG2_TERMS = (F + 8 + log2_reduction_bits - 1) / log2_reduction_bits;
1824
1825 /// @brief ln(2) as a 128 bit fraction, {high, low}: round(ln(2) * 2^128). The decimal string it
1826 /// replaces had wrong 35th and 36th digits.
1827 static constexpr uint64_t ln2_fraction[2] = {0xB17217F7D1CF79ABull, 0xC9E3B39803F2F6AFull};
1828 /// @brief log10(2) as a 128 bit fraction, {high, low}: round(log10(2) * 2^128). The decimal
1829 /// string it replaces had lost a digit, an error of 4e-35.
1830 static constexpr uint64_t log10_2_fraction[2] = {0x4D104D427DE7FBCCull, 0x47C4ACD605BE48BCull};
1831
1832 /**
1833 * @brief Multiplies this object by a constant in [0, 1) held as a 128 bit fraction.
1834 *
1835 * The full 256 bit product of the magnitude and the constant is formed and its upper half kept,
1836 * rounded to nearest with a tie going away from zero. The constant therefore contributes 2^-128
1837 * of relative error instead of the 2^-F a fixed_point128 of this instantiation would carry, which
1838 * matters once the other factor is large: log() multiplies a log2 of up to 63 by ln(2).
1839 *
1840 * @param c_low Low QWORD of the constant, scaled by 2^128.
1841 * @param c_high High QWORD of the constant.
1842 * @return This object times the constant.
1843 */
1844 [[nodiscard]] FP128_INLINE constexpr fixed_point128 MulByFraction128(uint64_t c_low, uint64_t c_high) const noexcept
1845 {
1846 uint64_t l = 0, h = 0;
1847 const uint64_t sign_bits = GetMagnitude(l, h);
1848
1849 uint64_t r1 = 0, r2 = 0, r3 = 0;
1850 (void)mulx_u64(l, c_low, &r1); // only its carry into r1 matters
1851 r2 = mulx_u64(h, c_high, &r3);
1852 uint64_t cross_high = 0;
1853 uint64_t cross_low = mulx_u64(l, c_high, &cross_high);
1854 uint8_t carry = addcarryx_u64(0, r1, cross_low, &r1);
1855 carry = addcarryx_u64(carry, r2, cross_high, &r2);
1856 addcarryx_u64(carry, r3, 0, &r3);
1857 cross_low = mulx_u64(h, c_low, &cross_high);
1858 carry = addcarryx_u64(0, r1, cross_low, &r1);
1859 carry = addcarryx_u64(carry, r2, cross_high, &r2);
1860 addcarryx_u64(carry, r3, 0, &r3);
1861
1862 // the product is scaled by 2^128 too much: keep r3:r2, rounded by the highest bit of r1
1863 fixed_point128 res(r2, r3);
1864 FP128_ADD_ROUND_BIT(res.low, res.high, (r1 >> 63) != 0);
1865 res.NegateIf(sign_bits);
1866 return res;
1867 }
1868
1869 /// @brief 1/sqrt(2) as a 128 bit fraction, {high, low}: round(2^-0.5 * 2^128).
1870 static constexpr uint64_t inv_sqrt2_fraction[2] = {0xB504F333F9DE6484ull, 0x597D89B3754ABE9Full};
1871
1872 /**
1873 * @brief sqrt((1 - x) / 2) for x in [1/2, 1], the argument asin() and acos() reduce to.
1874 * Formed as sqrt(1 - x) / sqrt(2): 1 - x is exact and the root correctly rounded, where halving
1875 * 1 - x first would drop its last bit and the root would magnify that near x = 1.
1876 * @param x Value in [1/2, 1].
1877 * @return sqrt((1 - x) / 2), in [0, 1/2].
1878 */
1879 [[nodiscard]] FP128_INLINE static fixed_point128 RootOfHalfComplement(const fixed_point128& x) noexcept
1880 {
1881 return sqrt(fixed_point128::one() - x).MulByFraction128(inv_sqrt2_fraction[1], inv_sqrt2_fraction[0]);
1882 }
1883
1884 /**
1885 * @brief asin(x) for x in [0, 1/2], by Newton's method on sin().
1886 *
1887 * sin(Xn) - a
1888 * Xn+1 = Xn - -------------
1889 * cos(Xn)
1890 * where 'a' is the argument, starting from the double precision asin(). The cosine stays above
1891 * 0.86 on this range, so the iteration converges quadratically. A step is only taken when it
1892 * moves sin(Xn) closer to the argument: a correction below the precision of sin() is noise, and
1893 * the guard keeps the iteration from wandering on it. The converged case leaves before evaluating
1894 * sin(candidate), so the guard costs close to nothing.
1895 *
1896 * @param x Value in [0, 1/2].
1897 * @return asin(x).
1898 */
1899 [[nodiscard]] static fixed_point128 AsinNewton(const fixed_point128& x) noexcept
1900 {
1901 constexpr fixed_point128 eps = fixed_point128::epsilon() << 1;
1902 constexpr int max_iterations = 6;
1903 fixed_point128 res = ::asin(static_cast<double>(x));
1904 fixed_point128 sin_res = sin(res);
1905 fixed_point128 residual = fabs(sin_res - x);
1906 for (int i = 0; i < max_iterations; ++i) {
1907 const fixed_point128 e = (sin_res - x) / cos(res);
1908 const fixed_point128 candidate = res - e;
1909 // a step of a couple of ulp has converged; taking it unchecked skips the sin() below
1910 if (fabs(e) <= eps) {
1911 res = candidate;
1912 break;
1913 }
1914
1915 const fixed_point128 sin_candidate = sin(candidate);
1916 const fixed_point128 candidate_residual = fabs(sin_candidate - x);
1917 // the step made the estimate worse, or no better: it is noise, so keep what we have
1918 if (candidate_residual >= residual)
1919 break;
1920
1921 res = candidate;
1922 sin_res = sin_candidate;
1923 residual = candidate_residual;
1924 }
1925 return res;
1926 }
1927
1928 /// @brief e^-1 as a 128 bit fraction, {high, low}: round(e^-1 * 2^128).
1929 static constexpr uint64_t inv_e_fraction[2] = {0x5E2D58D8B3BCDF1Aull, 0xBADEC7829054F90Eull};
1930
1931 /**
1932 * @brief Converts a constant in [0, 1) held as a 128 bit fraction to this instantiation.
1933 * @param high High QWORD of the fraction, scaled by 2^128.
1934 * @param low Low QWORD of the fraction.
1935 * @return The constant, rounded to nearest.
1936 */
1937 [[nodiscard]] FP128_INLINE static constexpr fixed_point128 FromFraction128(uint64_t high, uint64_t low) noexcept
1938 {
1939 // 128 fraction bits down to F is a right shift by I + 1, rounded
1940 shift_right128_inplace_safe(low, high, I + 1);
1941 return fixed_point128(low, high);
1942 }
1943
1944 /**
1945 * @brief sqrt(x^2 + 1), or sqrt(x^2 - 1) for |x| >= 1, rounded to nearest.
1946 *
1947 * The square is formed as an exact 256 bit integer and the root taken with RoundedSqrt256(), so
1948 * neither function forms x^2 in this type. That matters twice over: x^2 overflows once |x|
1949 * reaches 2^(I/2), and x^2 - 1 for an x just above one is a tiny value whose rounding error the
1950 * root magnifies - acosh() was out by 5e8 ulp at fixed_point128<1> and by 1e4 ulp at I = 63.
1951 *
1952 * @param x The value to square.
1953 * @param minus True for x^2 - 1, which needs |x| >= 1; false for x^2 + 1.
1954 * @return The root. A result of 2^I or more wraps like any overflow.
1955 */
1956 [[nodiscard]] FP128_INLINE static fixed_point128 RootOfSquareAndOne(const fixed_point128& x, bool minus) noexcept
1957 {
1958 uint64_t l = 0, h = 0;
1959 (void)x.GetMagnitude(l, h);
1960 uint64_t s[4] {};
1961 Square256(l, h, s);
1962
1963 // one is 2^F in raw units, so its square is the single bit 2F of the 256 bit square
1964 uint64_t one_square[4] {};
1965 one_square[(2 * F) / 64] = 1ull << ((2 * F) % 64);
1966 uint8_t carry = 0;
1967 for (int32_t i = 0; i < 4; ++i) {
1968 carry = (minus) ? subborrow_u64(carry, s[i], one_square[i], &s[i]) : addcarryx_u64(carry, s[i], one_square[i], &s[i]);
1969 }
1970
1971 fixed_point128 res;
1972 RoundedSqrt256(s, res.low, res.high);
1973 return res;
1974 }
1975
1976 /**
1977 * @brief log(x + r) for the magnitude x and the root r that asinh() and acosh() add to it.
1978 *
1979 * The sum reaches 2^I once x reaches 2^(I-1). It used to wrap there, into a negative value that
1980 * made log() throw out of the two noexcept functions and terminate the process. A sum beyond the
1981 * range is now formed in 129 bits, divided by four, and log(4) added back to its logarithm.
1982 *
1983 * @param x_low Low QWORD of the magnitude of x, read as unsigned: 2^127 for lowest().
1984 * @param x_high High QWORD of the magnitude of x.
1985 * @param r The root, read as an unsigned raw value too: for lowest() it is a little above 2^127.
1986 * @return log(x + r).
1987 */
1988 [[nodiscard]] FP128_INLINE static fixed_point128 LogOfSum(uint64_t x_low, uint64_t x_high, const fixed_point128& r)
1989 {
1990 uint64_t s_low = 0, s_high = 0;
1991 const uint8_t carry = addcarryx_u64(addcarryx_u64(0, x_low, r.low, &s_low), x_high, r.high, &s_high);
1992 if (carry == 0 && (s_high >> 63) == 0) {
1993 return log(fixed_point128(s_low, s_high));
1994 }
1995
1996 // a quarter of the 129 bit sum, rounded half up, is below 2^126 and fits every instantiation
1997 const uint64_t round_bit = (s_low >> 1) & 1;
1998 s_low = (s_low >> 2) | (s_high << 62);
1999 s_high = (s_high >> 2) | (static_cast<uint64_t>(carry) << 62);
2000 s_high += addcarryx_u64(0, s_low, round_bit, &s_low);
2001 const fixed_point128 ln2 = FromFraction128(ln2_fraction[0], ln2_fraction[1]);
2002 return log(fixed_point128(s_low, s_high)) + ln2 + ln2;
2003 }
2004
2005 /**
2006 * @brief Maclaurin series of the sine or the cosine of an argument in [0, pi/2].
2007 *
2008 * Each term is the previous one times x^2 / (n(n+1)), the ratio read from fp128_trig_series_table,
2009 * so no power of x and no factorial is ever formed on its own. The whole series runs in
2010 * fixed_point128<2>, which has 125 fraction bits whatever I is: x^2 reaches 2.47, beyond the range
2011 * of fixed_point128<1>, while every term and partial sum stays at or below one in magnitude for the
2012 * cosine and below pi/2 for the sine. The caller rounds the sum to its own grid once, at the end.
2013 *
2014 * The earlier evaluation raised x to the n-th power and multiplied by 1/n! in the caller's own
2015 * instantiation: x^25 is 8e4 for x = pi/2 and wrapped in fixed_point128<16>, and 1/n! held to F bits
2016 * lost most of its digits in a wide instantiation. cos(0) came out 7026 ulp short of one at I = 63
2017 * and every cosine was 8e-21 off at I = 16.
2018 *
2019 * The series stops once a term drops below an eighth of the caller's last place - the rest of it
2020 * adds up to less than that - so a narrow instantiation evaluates more terms than a wide one.
2021 *
2022 * @param x Argument in [0, pi/2].
2023 * @param cosine True for the cosine series, false for the sine series.
2024 * @return The sum of the series, in fixed_point128<2>.
2025 */
2026 [[nodiscard]] static FP128_INLINE fixed_point128<2> TrigSeries(const fixed_point128<2>& x, bool cosine) noexcept
2027 {
2028 using work_t = fixed_point128<2>;
2029 // this instantiation's last place is 2^(I-2) units of the 2^-125 grid; an eighth of it
2030 // (one unit at I = 4, where an eighth would be below the grid)
2031 constexpr uint64_t cutoff = 1ull << ((I >= 5) ? (I - 5) : 0);
2032
2033 const work_t xx = sqr(x);
2034 work_t term = (cosine) ? work_t::one() : x;
2035 work_t sum = term;
2036 bool subtract = true;
2037 // the cosine multiplies by 1/(1*2), 1/(3*4), ... and the sine by 1/(2*3), 1/(4*5), ...
2038 for (size_t n = (cosine) ? 0 : 1; n < array_length(fp128_trig_series_table); n += 2) {
2039 term *= xx;
2040 term *= work_t(fp128_trig_series_table[n][1], fp128_trig_series_table[n][0]);
2041 uint64_t term_low = 0, term_high = 0;
2042 term.get_components(term_low, term_high);
2043 if (term_high == 0 && term_low < cutoff) {
2044 break;
2045 }
2046 if (subtract) {
2047 sum -= term;
2048 } else {
2049 sum += term;
2050 }
2051 subtract = !subtract;
2052 }
2053 return sum;
2054 }
2055
2056 /**
2057 * @brief Reads entry n of log2_inv_n_table as a fixed_point128<1>.
2058 *
2059 * The table holds 1/(n*ln2) with 127 fraction bits, which is the form float128's log2 wants;
2060 * fixed_point128<1> carries 126, so each entry is shifted down by a bit as it is read.
2061 *
2062 * The shift cannot be hoisted out of the series loop by rescaling the whole recurrence. Doing
2063 * that is sound - the accumulator is linear in the table entries, so leaving them doubled just
2064 * doubles the answer - but the accumulator peaks around 1.47 and a doubled one would not fit
2065 * the range of fixed_point128<1>, which stops just under 2.
2066 *
2067 * @param n Index into the table.
2068 * @return The entry, scaled for the type the series runs in.
2069 */
2070 [[nodiscard]] FP128_FORCE_INLINE static fixed_point128<1> Log2InvN(size_t n) noexcept
2071 {
2072 const uint64_t high = log2_inv_n_table[n][0], low = log2_inv_n_table[n][1];
2073 return fixed_point128<1>(shift_right128<1>(low, high), high >> 1);
2074 }
2075
2076 /**
2077 * @brief Fraction part of log2(x) for x in [1,2), by argument reduction and a short series.
2078 *
2079 * Three steps:
2080 * -# Reduction. The leading six fraction bits of x select a tabulated reciprocal, and
2081 * multiplying by it brings the value to within 2^-6 of one. Because log2_value_table holds
2082 * the logarithm of the reciprocal that is actually stored rather than of the round number it
2083 * approximates, the identity log2(x) = log2(x * recip) - log2(recip) is exact and the
2084 * reduction introduces no error of its own. The multiply is done on the raw QWORDs as a pure
2085 * 128 bit fraction, so it neither knows nor cares what I is.
2086 * -# Series. log2(1+z) = (z - z^2/2 + z^3/3 - ...) / ln(2), evaluated by Horner. With
2087 * |z| <= 2^-6 each term buys six more bits, so LOG2_TERMS of them suffice.
2088 * -# Scaling. The result is converted to this instantiation's scaling exactly once, at the end.
2089 *
2090 * The series runs in fixed_point128<1>, which has 126 fraction bits whatever the caller's I is.
2091 * That is what keeps the accuracy: z is exact to 2^-127 coming out of the reduction, and
2092 * rounding it onto a grid of F bits before the series would cost 0.72 ulp of the result all on
2093 * its own. Holding it at 126 bits instead leaves the table entry and the final conversion as
2094 * the only meaningful error terms. The accumulator stays below 1.02 and 1/ln(2) is 1.443, so
2095 * both fit the range of fixed_point128<1>, which is just under 2.
2096 *
2097 * The caller passes the raw significand rather than a value already brought to [1,2). Dividing
2098 * down to that range is a right shift, and for an argument whose leading one sits above the
2099 * binary point it pushes up to I-1 of the significant bits off the bottom - worth about 1.4 ulp
2100 * of the answer, which was the largest single error term in the previous implementation.
2101 * Normalizing upwards here instead is a left shift, so the whole significand survives.
2102 *
2103 * @param low Low QWORD of the argument's raw significand.
2104 * @param high High QWORD of the argument's raw significand.
2105 * @param leading_zeros Count of leading zero bits in that significand.
2106 * @return The fraction part of log2, in [0,1).
2107 */
2108 [[nodiscard]] static FP128_INLINE fixed_point128 log2_fraction(uint64_t low, uint64_t high, int32_t leading_zeros) noexcept
2109 {
2110 using work_t = fixed_point128<1>;
2111 constexpr int32_t K = log2_reduction_bits;
2112
2113 // Bring the leading one to bit 127, turning the significand into a fraction in [0.5,1).
2114 uint64_t m_low = low, m_high = high;
2115 shift_left128_inplace_safe(m_low, m_high, leading_zeros);
2116
2117 // The leading one sits at bit 127; the six bits below it choose the reciprocal.
2118 const size_t j = static_cast<size_t>((m_high >> (63 - K)) & ((1ull << K) - 1));
2119
2120 uint64_t p_low = 0, p_high = 0;
2121 mul128_high(m_low, m_high, log2_recip_table[j][1], log2_recip_table[j][0], p_low, p_high);
2122
2123 // z = 2 * (x/2 * recip) - 1, which is the product with its leading bit removed. Subtracting
2124 // one half from the raw fraction wraps in the unsigned domain into exactly the two's
2125 // complement of a negative difference, which is what a reciprocal that rounded down
2126 // produces. The difference stands for z scaled by 2^127, one bit more than the 126 the raw
2127 // form of a fixed_point128<1> carries, so it is shifted down by one - arithmetically, z
2128 // having a sign now.
2129 constexpr uint64_t one_half = 1ull << 63;
2130 uint64_t z_low = p_low, z_high = p_high - one_half;
2131 shift_right128_inplace_safe_signed(z_low, z_high, 1);
2132 const work_t z(z_low, z_high);
2133
2134 // Horner over 1/(n*ln2), from the last term down, so the result is already base two.
2135 work_t acc = Log2InvN(LOG2_TERMS - 1);
2136 for (int32_t n = LOG2_TERMS - 1; n >= 1; --n) {
2137 acc = Log2InvN(n - 1) - z * acc;
2138 }
2139 const work_t series = z * acc;
2140
2141 // -log2(recip), the part of the answer the reduction removed, converted from a raw 128 bit
2142 // fraction to this scaling. The shift is by I + 1, which reaches 64 for the widest integer
2143 // part, so it goes through the variant that handles a shift of a whole QWORD.
2144 uint64_t table_low = log2_value_table[j][1], table_high = log2_value_table[j][0];
2145 shift_right128_inplace_safe(table_low, table_high, I + 1);
2146
2147 return fixed_point128(table_low, table_high) + fixed_point128(series);
2148 }
2149
2150 /**
2151 * @brief Fraction part of log2(x) for x in [1,2), one bit at a time.
2152 *
2153 * Squaring the argument repeatedly and recording whether each square left the [1,2) range
2154 * yields the bits of the answer from the top down: F squarings for F bits. log2_fraction() is
2155 * about five times faster and more accurate, so this survives only for constant evaluation,
2156 * where neither the tables nor the raw QWORD reduction of the fast path can be reached.
2157 *
2158 * The iteration runs on x/2 in [0.5,1) rather than on x itself, which keeps every square
2159 * inside [0.25,1). Squaring x directly reaches 4, and a magnitude of 4 needs three integer
2160 * bits, so the earlier form of this loop returned a completely wrong answer for
2161 * fixed_point128<1> - it compared against a constant 2 that instantiation cannot hold.
2162 * Halving costs the lowest bit of the argument, which is why this is the slow path's problem
2163 * to have and not the fast one's.
2164 *
2165 * @param x Value in [1,2).
2166 * @return log2(x), in [0,1).
2167 */
2168 [[nodiscard]] static constexpr fixed_point128 log2_fraction_bitwise(fixed_point128 x) noexcept
2169 {
2170 const fixed_point128 half = fixed_point128::one() >> 1; // 0.5
2171 fixed_point128 u = x >> 1; // in [0.5,1)
2172 fixed_point128 b = half;
2173 fixed_point128 fy; // fraction part of the result
2174 for (auto i = 0; i < fixed_point128::F; ++i) {
2175 u.square(); // in [0.25,1)
2176 // the square of x left [1,2) exactly when the square of x/2 reached 0.5
2177 if (u >= half) {
2178 fy |= b; // ORing is identical (in this case) but faster than addition.
2179 } else {
2180 shift_left128_inplace(u.low, u.high, 1);
2181 }
2182 // divide base by 2 using inplace shifts
2183 shift_right128_inplace(b.low, b.high, 1);
2184 }
2185
2186 return fy;
2187 }
2188
2189 /**
2190 * @brief Divides the magnitude this object holds by another magnitude, in place.
2191 *
2192 * The long division path of operator/=, which two of that function's branches reach. Both
2193 * operands are unsigned 128 bit magnitudes rather than values of this type, and that is what
2194 * lets this serve the one numerator the reciprocal path cannot: 2^127, which is the magnitude
2195 * of lowest() and reads as a negative value when held in a fixed_point128.
2196 *
2197 * The numerator is extended with 128 zero bits below it, so the quotient arrives with 128
2198 * fraction bits and is brought down to the F this type keeps.
2199 *
2200 * @param denom_low Low QWORD of the divisor's magnitude
2201 * @param denom_high High QWORD of the divisor's magnitude
2202 * @return True when the dropped part of the quotient reached half a bit, which the caller
2203 * rounds up for.
2204 */
2205 FP128_INLINE bool DivideMagnitude(uint64_t denom_low, uint64_t denom_high)
2206 {
2207 uint64_t q[4] {};
2208 const uint64_t nom[4] = {0, 0, low, high};
2209 const uint64_t denom[2] = {denom_low, denom_high};
2210
2211 // A divisor small enough to fit in one QWORD is div_64bit's job; div_128bit rejects it
2212 // rather than handle a case that has a cheaper route. Both fill the same first words of q.
2213 const bool ok = (denom_high != 0) ? Divide256By128(q, nullptr, nom, denom)
2214 : div_64bit(q, nullptr, nom, denom_low, array_length(nom));
2215 if (!ok) {
2217 }
2218
2219 // the quotient carries 128 fraction bits and this type keeps F of them, so it is shifted
2220 // right by 128 - F, which is I + 1
2221 constexpr uint64_t half = 1ull << I; // the highest bit dropped, used for rounding
2222 const bool need_rounding = (q[0] & half) != 0;
2223 if constexpr (I == 63) {
2224 // a shift of exactly one QWORD, which the intrinsic behind FP128_SHIFTRIGHT128 takes
2225 // modulo 64 and would leave unshifted
2226 low = q[1];
2227 high = q[2];
2228 } else {
2229 high = FP128_SHIFTRIGHT128(q[1], q[2], I + 1);
2230 low = FP128_SHIFTRIGHT128(q[0], q[1], I + 1);
2231 }
2232
2233 return need_rounding;
2234 }
2235
2236 /**
2237 * @brief Squares an unsigned 128 bit integer into its full 256 bit product.
2238 * @param l Low QWORD of the value
2239 * @param h High QWORD of the value
2240 * @param r Receives the product, r[0] lowest.
2241 */
2242 FP128_INLINE static constexpr void Square256(uint64_t l, uint64_t h, uint64_t (&r)[4]) noexcept
2243 {
2244 r[0] = mulx_u64(l, l, &r[1]);
2245 r[2] = mulx_u64(h, h, &r[3]);
2246
2247 // the cross product l * h appears twice: it is added doubled, a 129 bit value, at bit 64
2248 uint64_t cross_high = 0;
2249 const uint64_t cross_low = mulx_u64(l, h, &cross_high);
2250 const uint64_t doubled_low = cross_low << 1;
2251 const uint64_t doubled_high = (cross_high << 1) | (cross_low >> 63);
2252 const uint64_t doubled_top = cross_high >> 63;
2253 uint8_t carry = addcarryx_u64(0, r[1], doubled_low, &r[1]);
2254 carry = addcarryx_u64(carry, r[2], doubled_high, &r[2]);
2255 addcarryx_u64(carry, r[3], doubled_top, &r[3]);
2256 }
2257
2258 /**
2259 * @brief Compares two unsigned 256 bit integers.
2260 * @param a Left hand side, a[0] lowest
2261 * @param b Right hand side, b[0] lowest
2262 * @return Negative, zero or positive as a is below, equal to or above b.
2263 */
2264 [[nodiscard]] FP128_INLINE static constexpr int32_t Compare256(const uint64_t (&a)[4], const uint64_t (&b)[4]) noexcept
2265 {
2266 for (int32_t i = 3; i >= 0; --i) {
2267 if (a[i] != b[i]) {
2268 return (a[i] < b[i]) ? -1 : 1;
2269 }
2270 }
2271 return 0;
2272 }
2273
2274 /**
2275 * @brief Square root of an unsigned 256 bit integer, rounded to the nearest integer.
2276 *
2277 * A double precision estimate of the root, nudged above it, seeds the integer Newton iteration
2278 * r' = floor((r + floor(s / r)) / 2), which never drops below floor(sqrt(s)) once it starts above
2279 * it. The estimate is good to about 44 bits, so two steps leave r at floor(sqrt(s)) or one above
2280 * it. Comparing s with r^2 - r and r^2 + r then settles the rounded root exactly: it is r when
2281 * r^2 - r < s <= r^2 + r, the integer form of (r - 1/2)^2 <= s < (r + 1/2)^2. A root exactly
2282 * halfway between two integers is impossible, so there is no tie to break.
2283 *
2284 * Two 256 by 128 bit divisions do the work, the cost of the three Newton steps of the fixed point
2285 * iteration this replaced. The result no longer depends on how far the argument had to be
2286 * normalized: the old form shifted bits of a large argument away before taking the root and
2287 * shifted the root left afterwards, which lost up to half of the integer bits.
2288 *
2289 * @param s Radicand, s[0] lowest. At most 2^255, so the root fits in 128 bits.
2290 * @param res_low Receives the low QWORD of the rounded root.
2291 * @param res_high Receives the high QWORD of the rounded root.
2292 */
2293 FP128_INLINE static void RoundedSqrt256(const uint64_t (&s)[4], uint64_t& res_low, uint64_t& res_high) noexcept
2294 {
2295 res_low = res_high = 0;
2296 int32_t top = 3;
2297 while (top >= 0 && s[top] == 0) {
2298 --top;
2299 }
2300 if (top < 0) {
2301 return;
2302 }
2303
2304 // s is about lead * 2^k, lead holding its 64 leading bits
2305 const int32_t lz = static_cast<int32_t>(lzcnt64(s[top]));
2306 uint64_t lead = s[top] << lz;
2307 if (lz != 0 && top != 0) {
2308 lead |= s[top - 1] >> (64 - lz);
2309 }
2310 const int32_t k = 64 * top - lz;
2311 // k >> 1 rounds towards minus infinity and k & 1 is the matching remainder, so the split is
2312 // right for a negative k as well. The factor puts the estimate safely above the root.
2313 const double estimate = std::ldexp(std::sqrt(std::ldexp(static_cast<double>(lead), k & 1)), k >> 1) * (1.0 + 0x1p-45);
2314
2315 uint64_t r_low = 0, r_high = 0;
2316 if (estimate < 0x1p64) {
2317 r_low = static_cast<uint64_t>(estimate) + 2; // makes up for the truncation, and then some
2318 } else {
2319 int exponent = 0;
2320 const double mantissa = std::frexp(estimate, &exponent); // estimate = mantissa * 2^exponent
2321 r_low = static_cast<uint64_t>(std::ldexp(mantissa, 64)); // exact, it has 53 significant bits
2322 shift_left128_inplace_safe(r_low, r_high, exponent - 64);
2323 r_high += addcarryx_u64(0, r_low, 1, &r_low);
2324 }
2325
2326 // Two Newton steps from above. The quotient fits in 128 bits: r stays at or above
2327 // floor(sqrt(s)), so s / r is at most two above it.
2328 for (int32_t i = 0; i < 2; ++i) {
2329 uint64_t q[4] {};
2330 if (r_high != 0) {
2331 const uint64_t divisor[2] = {r_low, r_high};
2332 (void)Divide256By128(q, nullptr, s, divisor);
2333 } else {
2334 (void)div_64bit(q, nullptr, s, r_low, 4);
2335 }
2336 // (r + q) / 2, the carry out of the sum shifted back in at the top
2337 const uint8_t sum_carry = addcarryx_u64(addcarryx_u64(0, r_low, q[0], &r_low), r_high, q[1], &r_high);
2338 r_low = (r_low >> 1) | (r_high << 63);
2339 r_high = (r_high >> 1) | (static_cast<uint64_t>(sum_carry) << 63);
2340 }
2341
2342 // r is floor(sqrt(s)) or one more, so the rounded root is r - 1, r or r + 1
2343 uint64_t square[4] {};
2344 Square256(r_low, r_high, square);
2345 uint64_t below[4] {}, above[4] {}; // r^2 - r and r^2 + r
2346 uint8_t borrow = subborrow_u64(0, square[0], r_low, &below[0]);
2347 borrow = subborrow_u64(borrow, square[1], r_high, &below[1]);
2348 borrow = subborrow_u64(borrow, square[2], 0, &below[2]);
2349 (void)subborrow_u64(borrow, square[3], 0, &below[3]);
2350 uint8_t carry = addcarryx_u64(0, square[0], r_low, &above[0]);
2351 carry = addcarryx_u64(carry, square[1], r_high, &above[1]);
2352 carry = addcarryx_u64(carry, square[2], 0, &above[2]);
2353 (void)addcarryx_u64(carry, square[3], 0, &above[3]);
2354
2355 if (Compare256(s, below) <= 0) {
2356 r_high -= subborrow_u64(0, r_low, 1, &r_low);
2357 } else if (Compare256(s, above) > 0) {
2358 r_high += addcarryx_u64(0, r_low, 1, &r_low);
2359 }
2360
2361 res_low = r_low;
2362 res_high = r_high;
2363 }
2364
2365 /// @}
2366
2367 /// @name Binary Math Operators (Friend)
2368 /// @{
2369
2370 // Each of these applies the compound assignment to the by value left hand side and then returns
2371 // it on a line of its own, rather than the shorter `return lhs OP= rhs;`. The two are
2372 // equivalent, but the short form makes the return statement copy construct from an lvalue, which
2373 // MSVC compiles into a store forwarding stall. int128_base's binary operators carry the full
2374 // explanation and the measurement.
2375
2376 /**
2377 * @brief Adds 2 values and returns the result.
2378 * @param lhs left hand side operand
2379 * @param rhs Right hand side operand
2380 * @return Result of the operation
2381 */
2382 template <typename T>
2383 [[nodiscard]] friend FP128_FORCE_INLINE constexpr fixed_point128 operator+(fixed_point128 lhs, const T& rhs) noexcept
2384 {
2385 lhs += rhs;
2386 return lhs;
2387 }
2388 /**
2389 * @brief subtracts the right hand side operand to this object to and returns the result.
2390 * @param lhs left hand side operand
2391 * @param rhs Right hand side operand
2392 * @return The fixed_point128 result
2393 */
2394 template <typename T>
2395 [[nodiscard]] friend FP128_FORCE_INLINE constexpr fixed_point128 operator-(fixed_point128 lhs, const T& rhs) noexcept
2396 {
2397 lhs -= rhs;
2398 return lhs;
2399 }
2400 /**
2401 * @brief Multiplies the right hand side operand with this object to and returns the result.
2402 * @param lhs left hand side operand
2403 * @param rhs Right hand side operand
2404 * @return The fixed_point128 result
2405 */
2406 template <typename T>
2407 [[nodiscard]] friend FP128_FORCE_INLINE constexpr fixed_point128 operator*(fixed_point128 lhs, const T& rhs) noexcept
2408 {
2409 lhs *= rhs;
2410 return lhs;
2411 }
2412 /**
2413 * @brief Divides this object by the right hand side operand and returns the result.
2414 * @param lhs left hand side operand
2415 * @param rhs Right hand side operand
2416 * @return The fixed_point128 result
2417 */
2418 template <typename T> [[nodiscard]] friend FP128_FORCE_INLINE fixed_point128 operator/(fixed_point128 lhs, const T& rhs)
2419 {
2420 lhs /= rhs;
2421 return lhs;
2422 }
2423 /**
2424 * @brief Calculates modulo.
2425 * @param lhs left hand side operand
2426 * @param rhs Right hand side operand
2427 * @return The fixed_point128 result
2428 */
2429 template <typename T> [[nodiscard]] friend FP128_FORCE_INLINE fixed_point128 operator%(fixed_point128 lhs, const T& rhs)
2430 {
2431 lhs %= rhs;
2432 return lhs;
2433 }
2434
2435 /// @}
2436
2437 /// @name Binary Bitwise Operators (Friend)
2438 /// @{
2439
2440 /**
2441 * @brief Performs bitwise AND (&)
2442 * @param lhs left hand side operand
2443 * @param rhs Right hand side operand
2444 * @return The fixed_point128 result
2445 */
2446 template <typename T> [[nodiscard]] friend FP128_FORCE_INLINE constexpr fixed_point128 operator&(fixed_point128 lhs, const T& rhs)
2447 {
2448 lhs &= rhs;
2449 return lhs;
2450 }
2451 /**
2452 * @brief Performs bitwise OR (|)
2453 * @param lhs left hand side operand
2454 * @param rhs Right hand side operand
2455 * @return The fixed_point128 result
2456 */
2457 template <typename T> [[nodiscard]] friend FP128_FORCE_INLINE constexpr fixed_point128 operator|(fixed_point128 lhs, const T& rhs)
2458 {
2459 lhs |= rhs;
2460 return lhs;
2461 }
2462 /**
2463 * @brief Performs bitwise XOR (^)
2464 * @param lhs left hand side operand
2465 * @param rhs Right hand side operand
2466 * @return The fixed_point128 result
2467 */
2468 template <typename T> [[nodiscard]] friend FP128_FORCE_INLINE constexpr fixed_point128 operator^(fixed_point128 lhs, const T& rhs)
2469 {
2470 lhs ^= rhs;
2471 return lhs;
2472 }
2473
2474 /// @}
2475
2476 /// @name Binary Operators With The Scalar On The Left Hand Side (Friend)
2477 /// @brief Overloads that accept a builtin arithmetic type as the left operand.
2478 ///
2479 /// Without these, an expression like (1 + x) is ambiguous: converting the literal to
2480 /// fixed_point128 and converting x to a builtin type are both one user defined conversion, so
2481 /// neither overload wins. Restricting the left operand to the arithmetic types keeps these from
2482 /// competing with the fixed_point128 on the left versions above, which would otherwise be an
2483 /// equally good match. The comparison operators already carry the same pair of overloads.
2484 ///
2485 /// The scalar is widened to fixed_point128 rather than the object being narrowed to a builtin
2486 /// type, so (1 - x) keeps the fraction of x instead of truncating it away.
2487 /// @{
2488
2489 /// @brief Adds a scalar and a fixed_point128, in that order. @param lhs Left operand @param rhs Right operand @return The fixed_point128 result
2490 template <typename T>
2491 requires std::is_arithmetic_v<T>
2492 [[nodiscard]] friend FP128_FORCE_INLINE constexpr fixed_point128 operator+(const T& lhs, const fixed_point128& rhs) noexcept
2493 {
2494 return fixed_point128(lhs) += rhs;
2495 }
2496 /// @brief Subtracts a fixed_point128 from a scalar. @param lhs Left operand @param rhs Right operand @return The fixed_point128 result
2497 template <typename T>
2498 requires std::is_arithmetic_v<T>
2499 [[nodiscard]] friend FP128_FORCE_INLINE constexpr fixed_point128 operator-(const T& lhs, const fixed_point128& rhs) noexcept
2500 {
2501 return fixed_point128(lhs) -= rhs;
2502 }
2503 /// @brief Multiplies a scalar and a fixed_point128, in that order. @param lhs Left operand @param rhs Right operand @return The fixed_point128 result
2504 template <typename T>
2505 requires std::is_arithmetic_v<T>
2506 [[nodiscard]] friend FP128_FORCE_INLINE constexpr fixed_point128 operator*(const T& lhs, const fixed_point128& rhs) noexcept
2507 {
2508 return fixed_point128(lhs) *= rhs;
2509 }
2510 /// @brief Divides a scalar by a fixed_point128. @param lhs Left operand @param rhs Right operand @return The fixed_point128 result
2511 template <typename T>
2512 requires std::is_arithmetic_v<T>
2513 [[nodiscard]] friend FP128_FORCE_INLINE fixed_point128 operator/(const T& lhs, const fixed_point128& rhs)
2514 {
2515 return fixed_point128(lhs) /= rhs;
2516 }
2517 /// @brief Performs modulo of a scalar by a fixed_point128. @param lhs Left operand @param rhs Right operand @return The fixed_point128 result
2518 template <typename T>
2519 requires std::is_arithmetic_v<T>
2520 [[nodiscard]] friend FP128_FORCE_INLINE fixed_point128 operator%(const T& lhs, const fixed_point128& rhs)
2521 {
2522 return fixed_point128(lhs) %= rhs;
2523 }
2524 /// @brief Performs bitwise AND of a scalar and a fixed_point128. @param lhs Left operand @param rhs Right operand @return The fixed_point128 result
2525 template <typename T>
2526 requires std::is_arithmetic_v<T>
2527 [[nodiscard]] friend FP128_FORCE_INLINE constexpr fixed_point128 operator&(const T& lhs, const fixed_point128& rhs)
2528 {
2529 return fixed_point128(lhs) &= rhs;
2530 }
2531 /// @brief Performs bitwise OR of a scalar and a fixed_point128. @param lhs Left operand @param rhs Right operand @return The fixed_point128 result
2532 template <typename T>
2533 requires std::is_arithmetic_v<T>
2534 [[nodiscard]] friend FP128_FORCE_INLINE constexpr fixed_point128 operator|(const T& lhs, const fixed_point128& rhs)
2535 {
2536 return fixed_point128(lhs) |= rhs;
2537 }
2538 /// @brief Performs bitwise XOR of a scalar and a fixed_point128. @param lhs Left operand @param rhs Right operand @return The fixed_point128 result
2539 template <typename T>
2540 requires std::is_arithmetic_v<T>
2541 [[nodiscard]] friend FP128_FORCE_INLINE constexpr fixed_point128 operator^(const T& lhs, const fixed_point128& rhs)
2542 {
2543 return fixed_point128(lhs) ^= rhs;
2544 }
2545 /**
2546 * @brief Shifts a scalar left by a fixed_point128 shift count.
2547 *
2548 * The left operand is widened to fixed_point128 first, so the result is 128 bit rather than the
2549 * builtin type of lhs.
2550 *
2551 * The count is rhs converted to int32_t, the same conversion the fixed_point128 on the left
2552 * overload applies. That conversion is a shift, so the fraction of rhs is truncated toward zero
2553 * rather than rounded.
2554 *
2555 * @param lhs Left operand, the value being shifted
2556 * @param rhs Right operand, the shift count
2557 * @return The fixed_point128 result
2558 */
2559 template <typename T>
2560 requires std::is_arithmetic_v<T>
2561 [[nodiscard]] friend FP128_FORCE_INLINE constexpr fixed_point128 operator<<(const T& lhs, const fixed_point128& rhs) noexcept
2562 {
2563 return fixed_point128(lhs) <<= static_cast<int32_t>(rhs);
2564 }
2565 /**
2566 * @brief Shifts a scalar right by a fixed_point128 shift count.
2567 * The left operand is widened to fixed_point128 first, see operator<< above.
2568 * @param lhs Left operand, the value being shifted
2569 * @param rhs Right operand, the shift count
2570 * @return The fixed_point128 result
2571 */
2572 template <typename T>
2573 requires std::is_arithmetic_v<T>
2574 [[nodiscard]] friend FP128_FORCE_INLINE constexpr fixed_point128 operator>>(const T& lhs, const fixed_point128& rhs) noexcept
2575 {
2576 return fixed_point128(lhs) >>= static_cast<int32_t>(rhs);
2577 }
2578
2579 /// @}
2580
2581 /// @name Comparison Operators
2582 /// @{
2583
2584 /**
2585 * @brief Compare logical/bitwise equal.
2586 * @param lhs left hand side operand
2587 * @param rhs Right hand side operand
2588 * @return True if this and rhs are equal.
2589 */
2590 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator==(const fixed_point128& lhs, const fixed_point128& rhs) noexcept
2591 {
2592 return lhs.high == rhs.high && lhs.low == rhs.low;
2593 }
2594 /// @overload
2595 template <typename T> [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator==(const fixed_point128& lhs, const T& rhs) noexcept
2596 {
2597 return lhs == fixed_point128(rhs);
2598 }
2599 /// @overload
2600 template <typename T> [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator==(const T& lhs, const fixed_point128& rhs) noexcept
2601 {
2602 return rhs == fixed_point128(lhs);
2603 }
2604 /**
2605 * @brief Return true when objects are not equal. Can be used as logical XOR.
2606 * @param lhs left hand side operand
2607 * @param rhs Right hand side operand
2608 * @return True if not equal.
2609 */
2610 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator!=(const fixed_point128& lhs, const fixed_point128& rhs) noexcept
2611 {
2612 return lhs.high != rhs.high || lhs.low != rhs.low;
2613 }
2614 /// @overload
2615 template <typename T> [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator!=(const fixed_point128& lhs, const T& rhs) noexcept
2616 {
2617 return lhs != fixed_point128(rhs);
2618 }
2619 /// @overload
2620 template <typename T> [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator!=(const T& lhs, const fixed_point128& rhs) noexcept
2621 {
2622 return rhs != fixed_point128(lhs);
2623 }
2624 /**
2625 * @brief Return true if this object is small than the rhs
2626 * @param lhs left hand side operand
2627 * @param rhs Right hand side operand
2628 * @return True when this object is smaller.
2629 */
2630 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator<(const fixed_point128& lhs, const fixed_point128& rhs) noexcept
2631 {
2632 // the upper QWORDs are compared as signed values, which settles the sign and the magnitude
2633 // above bit 64 in one step; the lower ones are pure magnitude and compare unsigned
2634 if (lhs.high != rhs.high)
2635 return static_cast<int64_t>(lhs.high) < static_cast<int64_t>(rhs.high);
2636
2637 return lhs.low < rhs.low;
2638 }
2639 /// @overload
2640 template <typename T> [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator<(const fixed_point128& lhs, const T& rhs) noexcept
2641 {
2642 return lhs < fixed_point128(rhs);
2643 }
2644 /// @overload
2645 template <typename T> [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator<(const T& lhs, const fixed_point128& rhs) noexcept
2646 {
2647 return fixed_point128(lhs) < rhs;
2648 }
2649 /**
2650 * @brief Return true this object is small or equal than the rhs
2651 * @param lhs left hand side operand
2652 * @param rhs Right hand side operand
2653 * @return True when this object is smaller or equal.
2654 */
2655 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator<=(const fixed_point128& lhs, const fixed_point128& rhs) noexcept { return !(lhs > rhs); }
2656 /// @overload
2657 template <typename T> [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator<=(const fixed_point128& lhs, const T& rhs) noexcept
2658 {
2659 return !(lhs > fixed_point128(rhs));
2660 }
2661 /// @overload
2662 template <typename T> [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator<=(const T& lhs, const fixed_point128& rhs) noexcept
2663 {
2664 return !(fixed_point128(lhs) > rhs);
2665 }
2666 /**
2667 * @brief Return true this object is larger than the rhs
2668 * @param lhs left hand side operand
2669 * @param rhs Right hand side operand
2670 * @return True when this object is larger.
2671 */
2672 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator>(const fixed_point128& lhs, const fixed_point128& rhs) noexcept
2673 {
2674 // see operator< above
2675 if (lhs.high != rhs.high)
2676 return static_cast<int64_t>(lhs.high) > static_cast<int64_t>(rhs.high);
2677
2678 return lhs.low > rhs.low;
2679 }
2680 /// @overload
2681 template <typename T> [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator>(const fixed_point128& lhs, const T& rhs) noexcept
2682 {
2683 return lhs > fixed_point128(rhs);
2684 }
2685 /// @overload
2686 template <typename T> [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator>(const T& lhs, const fixed_point128& rhs) noexcept
2687 {
2688 return fixed_point128(lhs) > rhs;
2689 }
2690 /**
2691 * @brief Return true this object is larger or equal than the rhs
2692 * @param lhs left hand side operand
2693 * @param rhs Right hand side operand
2694 * @return True when this objext is larger or equal.
2695 */
2696 [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator>=(const fixed_point128& lhs, const fixed_point128& rhs) noexcept { return !(lhs < rhs); }
2697 /// @overload
2698 template <typename T> [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator>=(const fixed_point128& lhs, const T& rhs) noexcept
2699 {
2700 return !(lhs < fixed_point128(rhs));
2701 }
2702 /// @overload
2703 template <typename T> [[nodiscard]] friend FP128_FORCE_INLINE constexpr bool operator>=(const T& lhs, const fixed_point128& rhs) noexcept
2704 {
2705 return !(fixed_point128(lhs) < rhs);
2706 }
2707
2708 /// @}
2709
2710 /// @name Friend Math Functions
2711 /// @brief CRT-style math functions implemented as friend functions.
2712 /// @{
2713
2714 /**
2715 * @brief Returns the absolute value
2716 * @param x Input value
2717 * @return A copy of x with the sign removed. lowest() has no positive counterpart and comes
2718 * back unchanged, the same silent wrap the builtin integer types perform.
2719 */
2720 [[nodiscard]] friend FP128_FORCE_INLINE constexpr fixed_point128 fabs(const fixed_point128& x) noexcept
2721 {
2722 fixed_point128 temp = x;
2723 if (temp.is_negative())
2724 temp.Negate();
2725
2726 return temp;
2727 }
2728 /**
2729 * @brief Performs the floor() function, similar to libc's floor(), rounds down towards -infinity.
2730 * @param x Input value
2731 * @return A fixed_point128 holding the integer value. Overflow is not reported.
2732 */
2733 [[nodiscard]] friend FP128_FORCE_INLINE constexpr fixed_point128 floor(const fixed_point128& x) noexcept
2734 {
2735 // dropping the fraction bits of a two's complement value moves it towards minus infinity,
2736 // which is what floor does, so the mask is the whole of it
2737 return fixed_point128(0, x.high & int_mask);
2738 }
2739
2740 /**
2741 * @brief Performs the ceil() function, similar to libc's ceil(), rounds up towards infinity.
2742 * @param x Input value
2743 * @return A fixed_point128 holding the integer value. Overflow is not reported.
2744 */
2745 [[nodiscard]] friend FP128_FORCE_INLINE constexpr fixed_point128 ceil(const fixed_point128& x) noexcept
2746 {
2747 if (x.is_int())
2748 return x;
2749
2750 // the integer above the floor, which for a value with a fraction is the ceiling
2751 return fixed_point128(0, (x.high & int_mask) + unity);
2752 }
2753 /**
2754 * @brief Rounds towards zero
2755 * @param x Value to truncate
2756 * @return Integer value, rounded towards zero.
2757 */
2758 [[nodiscard]] friend FP128_FORCE_INLINE constexpr fixed_point128 trunc(const fixed_point128& x) noexcept
2759 {
2760 // towards zero is up for a negative value and down for a positive one
2761 return (x.is_negative()) ? ceil(x) : floor(x);
2762 }
2763 /**
2764 * @brief Rounds towards the nearest integer.
2765 * The halfway value (0.5) is rounded away from zero.
2766 * @param x Value to round
2767 * @return Integer value, rounded towards the nearest integer.
2768 */
2769 [[nodiscard]] friend FP128_FORCE_INLINE constexpr fixed_point128 round(const fixed_point128& x) noexcept
2770 {
2771 // the magnitude is rounded and the sign put back, which is what rounding away from zero on
2772 // a tie means
2773 const fixed_point128 res = floor(fabs(x) + fixed_point128::half());
2774 return (x.is_negative()) ? -res : res;
2775 }
2776 /**
2777 * @brief Retrieves an integer that represents the base-2 exponent of the specified value.
2778 * floor(log2(|x|)), as the C function: the sign of x makes no difference.
2779 * @param x The specified value.
2780 * @return The exponent. FP_ILOGB0 for zero, which is what the C function returns for it.
2781 */
2782 [[nodiscard]] friend FP128_FORCE_INLINE constexpr int32_t ilogb(const fixed_point128& x) noexcept
2783 {
2784 return (x.is_zero()) ? FP_ILOGB0 : x.get_exponent();
2785 }
2786 /**
2787 * @brief returns the value of x with the sign of y.
2788 * @param x The value that's returned as the magnitude of the result.
2789 * @param y The sign of the result.
2790 * @return The copysign functions return a floating-point value that combines the magnitude of x and the sign of y.
2791 */
2792 [[nodiscard]] friend FP128_FORCE_INLINE constexpr fixed_point128 copysign(const fixed_point128& x, const fixed_point128& y) noexcept
2793 {
2794 const fixed_point128 magnitude = fabs(x);
2795 return (y.is_negative()) ? -magnitude : magnitude;
2796 }
2797 /**
2798 * @brief Performs the fmod() function, similar to libc's fmod(): x - y * trunc(x / y).
2799 * Exact, and the result keeps the sign of x. See operator%=().
2800 * @param x Numerator
2801 * @param y Denominator
2802 * @return A fixed_point128 holding the modulo value.
2803 * @throws std::logic_error when y is zero. This type has no NaN to return instead.
2804 */
2805 [[nodiscard]] friend FP128_FORCE_INLINE fixed_point128 fmod(const fixed_point128& x, const fixed_point128& y) { return x % y; }
2806 /**
2807 * @brief Split into integer and fraction parts.
2808 * Both results carry the sign of the input variable.
2809 * @param x Input value
2810 * @param iptr Pointer to fixed_point128 holding the integer part of x.
2811 * @return The fraction part of x. Undefined when iptr is nullptr.
2812 */
2813 [[nodiscard]] friend FP128_FORCE_INLINE constexpr fixed_point128 modf(const fixed_point128& x, fixed_point128* iptr) noexcept
2814 {
2815 if (iptr == nullptr)
2816 return 0;
2817
2818 *iptr = trunc(x); // the integer part, carrying the sign of x
2819 // What is left is the fraction, which carries that sign as well. The subtraction is exact:
2820 // the two parts have no bits in common.
2821 return x - *iptr;
2822 }
2823 /**
2824 * @brief Determines the positive difference between the first and second values.
2825 * @param x First value
2826 * @param y Second value
2827 * @return If x > y returns x - y. Otherwise zero.
2828 */
2829 [[nodiscard]] friend FP128_FORCE_INLINE constexpr fixed_point128 fdim(const fixed_point128& x, const fixed_point128& y) noexcept
2830 {
2831 return (x > y) ? x - y : fixed_point128(0);
2832 }
2833 /**
2834 * @brief Returns the minimum between x and y.
2835 * @param x First value
2836 * @param y Second value
2837 * @return If x < y returns x. Otherwise y.
2838 */
2839 [[nodiscard]] friend FP128_FORCE_INLINE constexpr fixed_point128 fmin(const fixed_point128& x, const fixed_point128& y) noexcept { return (x < y) ? x : y; }
2840 /**
2841 * @brief Returns the maximum between x and y.
2842 * @param x First value
2843 * @param y Second value
2844 * @return If x > y returns x. Otherwise y.
2845 */
2846 [[nodiscard]] friend FP128_FORCE_INLINE constexpr fixed_point128 fmax(const fixed_point128& x, const fixed_point128& y) noexcept { return (x > y) ? x : y; }
2847 /**
2848 * @brief Calculates the hypotenuse. i.e. sqrt(x^2 + y^2)
2849 *
2850 * Correctly rounded, and free of intermediate overflow: hypot(x, y) * 2^F is the square root of
2851 * the sum of the squared raw values, which is formed as an exact 256 bit integer. Spelled as
2852 * sqrt(sqr(x) + sqr(y)) instead, it overflowed as soon as |x| or |y| reached 2^(I/2), long before
2853 * the result itself leaves the range.
2854 *
2855 * @param x First value
2856 * @param y Second value
2857 * @return sqrt(x^2 + y^2), rounded to nearest. A result of 2^I or more wraps, like any overflow.
2858 */
2859 [[nodiscard]] friend FP128_INLINE fixed_point128 hypot(const fixed_point128& x, const fixed_point128& y) noexcept
2860 {
2861 uint64_t x_low = 0, x_high = 0, y_low = 0, y_high = 0;
2862 (void)x.GetMagnitude(x_low, x_high);
2863 (void)y.GetMagnitude(y_low, y_high);
2864
2865 // each magnitude is at most 2^127, so the sum of the squares is at most 2^255
2866 uint64_t sum[4] {}, y_square[4] {};
2867 Square256(x_low, x_high, sum);
2868 Square256(y_low, y_high, y_square);
2869 uint8_t carry = 0;
2870 for (int32_t i = 0; i < 4; ++i) {
2871 carry = addcarryx_u64(carry, sum[i], y_square[i], &sum[i]);
2872 }
2873
2874 fixed_point128 res;
2875 RoundedSqrt256(sum, res.low, res.high);
2876 return res;
2877 }
2878 /**
2879 * @brief Calculates the square of a value. i.e. x^2
2880 *
2881 * Faster than x * x and bit identical to it. Prefer this function wherever a value is
2882 * multiplied by itself, see fixed_point128::square().
2883 *
2884 * @param x Value to square
2885 * @return x^2, which is never negative.
2886 */
2887 [[nodiscard]] friend FP128_FORCE_INLINE constexpr fixed_point128 sqr(fixed_point128 x) noexcept { return x.square(); }
2888 /**
2889 * @brief Calculates the left zero count of value x, ignoring the sign.
2890 * Counted on the magnitude, so a negative value gives the same answer as its opposite rather
2891 * than the zero its two's complement bits would produce.
2892 * @param x input value.
2893 * @return lzc (uint32_t) of th result.
2894 */
2895 [[nodiscard]] friend FP128_FORCE_INLINE constexpr uint64_t lzcnt128(const fixed_point128& x) noexcept
2896 {
2897 uint64_t l = 0, h = 0;
2898 (void)x.GetMagnitude(l, h);
2899 return (h != 0) ? lzcnt64(h) : 64 + lzcnt64(l);
2900 }
2901 /**
2902 * @brief Calculates the square root, correctly rounded.
2903 *
2904 * sqrt(x) * 2^F is the square root of the raw value scaled up by another F bits, which makes it
2905 * the integer square root of a 256 bit number: RoundedSqrt256() computes it rounded to nearest,
2906 * so the result is the representable value closest to the exact root at every I and every
2907 * magnitude. (A tie between two representable values cannot occur.)
2908 *
2909 * @param x Value to calculate the root of
2910 * @param iterations Ignored. It used to set the step count of an iterative refinement, which lost
2911 * up to half of the integer bits for a large argument; it is kept so that existing calls
2912 * still compile.
2913 * @return Square root of (x), zero when x <= 0.
2914 */
2915 [[nodiscard]] friend FP128_INLINE fixed_point128 sqrt(const fixed_point128& x, [[maybe_unused]] uint32_t iterations = 3) noexcept
2916 {
2917 if (x.is_negative() || !x)
2918 return 0;
2919
2920 // raw * 2^F: F is 64 + upper_frac_bits, so the raw value moves up one QWORD and that many bits
2921 uint64_t s[4] {};
2922 if constexpr (upper_frac_bits == 0) {
2923 s[1] = x.low;
2924 s[2] = x.high;
2925 } else {
2926 s[1] = x.low << upper_frac_bits;
2927 s[2] = (x.high << upper_frac_bits) | (x.low >> (64 - upper_frac_bits));
2928 s[3] = x.high >> (64 - upper_frac_bits);
2929 }
2930
2931 fixed_point128 root;
2932 RoundedSqrt256(s, root.low, root.high);
2933 return root;
2934 }
2935 /**
2936 * @brief Factorial reciprocal (inverse). Calculates 1 / x!
2937 * Maximum value of x that may produce non zero values is 34.
2938 * This value depends on the amount of fraction bits.
2939 * The table is parsed from decimal strings, so it carries the accuracy of the string constructor:
2940 * within 0.5 + 23 / 2^(I-1) ulp of the exact 1 / x!, measured 17.5 ulp at I = 1 and 0.5 from
2941 * I = 16 up.
2942 * @param x Input value
2943 * @param res Result of the function
2944 */
2945 friend FP128_INLINE void fact_reciprocal(int x, fixed_point128& res) noexcept
2946 {
2947 static const fixed_point128 c[] = {
2948 "1", // 1 / 0!
2949 "1", // 1 / 1!
2950 "0.5", // 1 / 2!
2951 "0.166666666666666666666666666666666666667", // 1 / 3!
2952 "0.041666666666666666666666666666666666667", // 1 / 4!
2953 "0.008333333333333333333333333333333333333", // 1 / 5!
2954 "0.001388888888888888888888888888888888889", // 1 / 6!
2955 "0.000198412698412698412698412698412698413", // 1 / 7!
2956 "0.000024801587301587301587301587301587302", // 1 / 8!
2957 "0.000002755731922398589065255731922398589", // 1 / 9!
2958 "0.000000275573192239858906525573192239859", // 1 / 10!
2959 "0.000000025052108385441718775052108385442", // 1 / 11!
2960 "0.000000002087675698786809897921009032120", // 1 / 12!
2961 "0.000000000160590438368216145993923771702", // 1 / 13!
2962 "0.000000000011470745597729724713851697979", // 1 / 14!
2963 "0.000000000000764716373181981647590113199", // 1 / 15!
2964 "0.000000000000047794773323873852974382075", // 1 / 16!
2965 "0.000000000000002811457254345520763198946", // 1 / 17!
2966 "0.000000000000000156192069685862264622164", // 1 / 18!
2967 "0.000000000000000008220635246624329716956", // 1 / 19!
2968 "0.000000000000000000411031762331216485848", // 1 / 20!
2969 "0.000000000000000000019572941063391261231", // 1 / 21!
2970 "0.000000000000000000000889679139245057329", // 1 / 22!
2971 "0.000000000000000000000038681701706306840", // 1 / 23!
2972 "0.000000000000000000000001611737571096118", // 1 / 24!
2973 "0.000000000000000000000000064469502843845", // 1 / 25!
2974 "0.000000000000000000000000002479596263225", // 1 / 26!
2975 "0.000000000000000000000000000091836898638", // 1 / 27!
2976 "0.000000000000000000000000000003279889237", // 1 / 28!
2977 "0.000000000000000000000000000000113099628", // 1 / 29!
2978 "0.000000000000000000000000000000003769988", // 1 / 30!
2979 "0.000000000000000000000000000000000121613", // 1 / 31!
2980 "0.000000000000000000000000000000000003800", // 1 / 32!
2981 "0.000000000000000000000000000000000000115", // 1 / 33!
2982 "0.000000000000000000000000000000000000003" // 1 / 34!
2983 };
2984 constexpr int series_len = array_length(c);
2985
2986 if (x >= 0 && x < series_len) {
2987 res = c[x];
2988 } else {
2989 res = 0;
2990 }
2991 }
2992 /**
2993 * @brief Calculates the reciprocal of a value. y = 1 / x
2994 *
2995 * Correctly rounded: the quotient comes from the same long division operator/=() uses, rounded to
2996 * nearest with a tie going away from zero. The division is the faster of the two since
2997 * div_128bit, and the Newton refinement of a double estimate this replaced lost accuracy as 1 / x
2998 * grew - tens of thousands of ulp at fixed_point128<16>. It is called directly rather than
2999 * through operator/=(), which divides by multiplying with this function when
3000 * FP128_USE_RECIPROCAL_FOR_DIVISION is set.
3001 *
3002 * @param x Input value
3003 * @return 1 / x. Zero when x is zero or when 1 / x does not fit the range [-2^I, 2^I), that is
3004 * for |x| < 2^-I and for x == 2^-I; x == -2^-I gives lowest().
3005 */
3006 [[nodiscard]] friend FP128_INLINE fixed_point128 reciprocal(const fixed_point128& x) noexcept
3007 {
3008 uint64_t l = 0, h = 0;
3009 const uint64_t sign_bits = x.GetMagnitude(l, h);
3010 if ((l | h) == 0) {
3011 return fixed_point128(0);
3012 }
3013
3014 // |x| = 2^(msb - F) and up, so 1 / |x| reaches 2^I exactly when msb is F - I or below.
3015 const int32_t msb = 127 - static_cast<int32_t>(lzcnt128(l, h));
3016 if (msb < F - I) {
3017 return fixed_point128(0);
3018 }
3019 if (msb == F - I && popcnt128(l, h) == 1) {
3020 // exactly 2^-I: the reciprocal is 2^I, which only the negative side of the range holds
3021 return (sign_bits != 0) ? fixed_point128(0, 1ull << 63) : fixed_point128(0);
3022 }
3023
3024 fixed_point128 res = one();
3025 const bool need_rounding = res.DivideMagnitude(l, h);
3026 FP128_ADD_ROUND_BIT(res.low, res.high, need_rounding);
3027 res.NegateIf(sign_bits);
3028 return res;
3029 }
3030 /**
3031 * @brief Calculate Sine and Cosine using CORDIC using a limited range of [-pi/2, pi/2]
3032 * 64 iterations, one per entry of the arctangent table, which give an absolute accuracy of about
3033 * 2^-63: measured within 1.1e-19 of mpmath for |x| < 1. The table used to skip arctan(2^-62),
3034 * which held the error near 1.8e-19. Not used by tan(), which divides sin() by cos().
3035 * @param x
3036 * @param sin_x Result of the Sine of x.
3037 * @param cos_x Result of the Cosine of x.
3038 * @param apply_scale_factor Apply a scale factor when 60 or more iterations are performed. This is required to get accurate results when the number of
3039 * iterations is high, but it can be disabled for performance reasons when the number of iterations is low.
3040 */
3041 friend FP128_INLINE void _sincos_cordic(fixed_point128 x, fixed_point128& sin_x, fixed_point128& cos_x, bool apply_scale_factor) noexcept
3042 {
3043 static const fixed_point128 angles[] = {
3044 "0.7853981633974483096156608458198757210492", // arctan(2^-0)
3045 "0.4636476090008061162142562314612144020285", // arctan(2^-1)
3046 "0.2449786631268641541720824812112758109141", // arctan(2^-2)
3047 "0.1243549945467614350313548491638710255731", // arctan(2^-3)
3048 "0.0624188099959573484739791129855051136062", // arctan(2^-4)
3049 "0.0312398334302682762537117448924909770324", // arctan(2^-5)
3050 "0.0156237286204768308028015212565703189111", // arctan(2^-6)
3051 "0.0078123410601011112964633918421992816212", // arctan(2^-7)
3052 "0.0039062301319669718276286653114243871403", // arctan(2^-8)
3053 "0.0019531225164788186851214826250767139316", // arctan(2^-9)
3054 "0.0009765621895593194304034301997172908516", // arctan(2^-10)
3055 "0.0004882812111948982754692396256448486661", // arctan(2^-11)
3056 "0.0002441406201493617640167229432596599862", // arctan(2^-12)
3057 "0.0001220703118936702042390586461179563009", // arctan(2^-13)
3058 "0.0000610351561742087750216625691738291537", // arctan(2^-14)
3059 "0.0000305175781155260968618259534385360197", // arctan(2^-15)
3060 "0.0000152587890613157621072319358126978851", // arctan(2^-16)
3061 "0.0000076293945311019702633884823401050905", // arctan(2^-17)
3062 "0.0000038146972656064962829230756163729937", // arctan(2^-18)
3063 "0.0000019073486328101870353653693059172441", // arctan(2^-19)
3064 "0.0000009536743164059608794206706899231123", // arctan(2^-20)
3065 "0.0000004768371582030888599275838214492470", // arctan(2^-21)
3066 "0.0000002384185791015579824909479772189326", // arctan(2^-22)
3067 "0.0000001192092895507806853113684971379221", // arctan(2^-23)
3068 "0.0000000596046447753905544139210621417888", // arctan(2^-24)
3069 "0.0000000298023223876953036767401327677095", // arctan(2^-25)
3070 "0.0000000149011611938476551470925165959632", // arctan(2^-26)
3071 "0.0000000074505805969238279871365645744953", // arctan(2^-27)
3072 "0.0000000037252902984619140452670705718119", // arctan(2^-28)
3073 "0.0000000018626451492309570290958838214764", // arctan(2^-29)
3074 "0.0000000009313225746154785153557354776845", // arctan(2^-30)
3075 "0.0000000004656612873077392577788419347105", // arctan(2^-31)
3076 "0.0000000002328306436538696289020427418388", // arctan(2^-32)
3077 "0.0000000001164153218269348144525990927298", // arctan(2^-33)
3078 "0.0000000000582076609134674072264967615912", // arctan(2^-34)
3079 "0.0000000000291038304567337036132730326989", // arctan(2^-35)
3080 "0.0000000000145519152283668518066395978373", // arctan(2^-36)
3081 "0.0000000000072759576141834259033201841046", // arctan(2^-37)
3082 "0.0000000000036379788070917129516601402005", // arctan(2^-38)
3083 "0.0000000000018189894035458564758300761188", // arctan(2^-39)
3084 "0.0000000000009094947017729282379150388117", // arctan(2^-40)
3085 "0.0000000000004547473508864641189575194999", // arctan(2^-41)
3086 "0.0000000000002273736754432320594787597617", // arctan(2^-42)
3087 "0.0000000000001136868377216160297393798823", // arctan(2^-43)
3088 "0.0000000000000568434188608080148696899413", // arctan(2^-44)
3089 "0.0000000000000284217094304040074348449706", // arctan(2^-45)
3090 "0.0000000000000142108547152020037174224853", // arctan(2^-46)
3091 "0.0000000000000071054273576010018587112426", // arctan(2^-47)
3092 "0.0000000000000035527136788005009293556213", // arctan(2^-48)
3093 "0.0000000000000017763568394002504646778106", // arctan(2^-49)
3094 "0.0000000000000008881784197001252323389053", // arctan(2^-50)
3095 "0.0000000000000004440892098500626161694526", // arctan(2^-51)
3096 "0.0000000000000002220446049250313080847263", // arctan(2^-52)
3097 "0.0000000000000001110223024625156540423631", // arctan(2^-53)
3098 "0.0000000000000000555111512312578270211815", // arctan(2^-54)
3099 "0.0000000000000000277555756156289135105907", // arctan(2^-55)
3100 "0.0000000000000000138777878078144567552953", // arctan(2^-56)
3101 "0.0000000000000000069388939039072283776476", // arctan(2^-57)
3102 "0.0000000000000000034694469519536141888238", // arctan(2^-58)
3103 "0.0000000000000000017347234759768070944119", // arctan(2^-59)
3104 "0.0000000000000000008673617379884035472059", // arctan(2^-60)
3105 "0.0000000000000000004336808689942017736029", // arctan(2^-61)
3106 "0.0000000000000000002168404344971008868015", // arctan(2^-62)
3107 "0.0000000000000000001084202172485504434007", // arctan(2^-63)
3108 //"0.0000000000000000000542101086242752217003", // arctan(2^-64)
3109 //"0.0000000000000000000271050543121376108501", // arctan(2^-65)
3110 //"0.0000000000000000000135525271560688054250", // arctan(2^-66)
3111 //"0.0000000000000000000067762635780344027125", // arctan(2^-67)
3112 //"0.0000000000000000000033881317890172013562", // arctan(2^-68)
3113 //"0.0000000000000000000016940658945086006781", // arctan(2^-69)
3114 //"0.0000000000000000000008470329472543003390", // arctan(2^-70)
3115 //"0.0000000000000000000004235164736271501695", // arctan(2^-71)
3116 //"0.0000000000000000000002117582368135750847", // arctan(2^-72)
3117 //"0.0000000000000000000001058791184067875423", // arctan(2^-73)
3118 //"0.0000000000000000000000529395592033937711", // arctan(2^-74)
3119 //"0.0000000000000000000000264697796016968855", // arctan(2^-75)
3120 //"0.0000000000000000000000132348898008484427", // arctan(2^-76)
3121 //"0.0000000000000000000000066174449004242213", // arctan(2^-77)
3122 //"0.0000000000000000000000033087224502121106", // arctan(2^-78)
3123 //"0.0000000000000000000000016543612251060553", // arctan(2^-79)
3124 //"0.0000000000000000000000008271806125530276", // arctan(2^-80)
3125 //"0.0000000000000000000000004135903062765138", // arctan(2^-81)
3126 //"0.0000000000000000000000002067951531382569", // arctan(2^-82)
3127 //"0.0000000000000000000000001033975765691284", // arctan(2^-83)
3128 };
3129 constexpr uint32_t angles_count = array_length(angles);
3130 static const fixed_point128 K = "0.607252935008881256169446752504928263"; // scaling factor for 60 or more iterations
3131
3132 sin_x = 0.0; // sin x result
3133 cos_x = 1.0; // cos x result
3134 int32_t base = 0;
3135 auto angle = angles[0];
3136
3137 for (uint32_t j = 1; j <= angles_count; ++j) {
3138 if (x.is_positive()) { // positive sigma
3139 fixed_point128 s2 = sin_x + (cos_x >> base);
3140 fixed_point128 c2 = cos_x - (sin_x >> base);
3141 cos_x = c2;
3142 sin_x = s2;
3143 //
3144 // Update the remaining angle.
3145 //
3146 x -= angle;
3147 } else { // negative sigma
3148 fixed_point128 s2 = sin_x - (cos_x >> base);
3149 fixed_point128 c2 = cos_x + (sin_x >> base);
3150 cos_x = c2;
3151 sin_x = s2;
3152 //
3153 // Update the remaining angle.
3154 //
3155 x += angle;
3156 }
3157
3158 ++base;
3159 //
3160 // Update the angle from table, or eventually by just dividing by two.
3161 //
3162 if (angles_count < j + 1) {
3163 angle >>= 1;
3164 } else {
3165 angle = angles[j];
3166 }
3167 }
3168
3169 // apply scaling factor for 60 iterations.
3170 if (apply_scale_factor) {
3171 sin_x *= K;
3172 cos_x *= K;
3173 }
3174 }
3175 /**
3176 * @brief Calculate the sine function over a limited range [-0.5pi, 0.5pi]
3177 * Using the Maclaurin series expansion, the formula is:
3178 * x^3 x^5 x^7
3179 * sin(x) = x - --- + --- - --- + ...
3180 * 3! 5! 7!
3181 * The series runs in a wider fraction than this instantiation has, see TrigSeries().
3182 * @param x value in Radians in the range [-0.5pi, 0.5pi]
3183 * @return Sine of x. See sin() for the accuracy.
3184 */
3185 [[nodiscard]] friend FP128_INLINE fixed_point128 sin1(fixed_point128 x) noexcept
3186 {
3187 static_assert(I >= 4, "sin1() needs template parameter <I> to be at least 4: its callers reduce the argument with pi, which needs more than one integer bit!");
3188 assert(fabs(x) <= fixed_point128::half_pi());
3189
3190 // sine is odd: the series runs on the magnitude, which keeps every term non negative
3191 const bool negative = x.is_negative();
3192 const fixed_point128 res(TrigSeries(fixed_point128<2>(fabs(x)), false));
3193 return (negative) ? -res : res;
3194 }
3195 /**
3196 * @brief Calculate the cosine function over a limited range [-0.5pi, 0.5pi]
3197 * Using the Maclaurin series expansion, the formula is:
3198 * x^2 x^4 x^6
3199 * cos(x) = 1 - --- + --- - --- + ...
3200 * 2! 4! 6!
3201 * Evaluated directly rather than as sin1(pi/2 - x), which carried the rounding error of pi/2 into
3202 * every result; cos1(0) is now exactly one. See TrigSeries().
3203 * @param x value in Radians in the range [-0.5pi, 0.5pi]
3204 * @return Cosine of x. See cos() for the accuracy.
3205 */
3206 [[nodiscard]] friend FP128_INLINE fixed_point128 cos1(const fixed_point128& x) noexcept
3207 {
3208 static_assert(I >= 4, "cos1() needs template parameter <I> to be at least 4: its callers reduce the argument with pi, which needs more than one integer bit!");
3209 assert(fabs(x) <= fixed_point128::half_pi());
3210 // cosine is even
3211 return fixed_point128(TrigSeries(fixed_point128<2>(fabs(x)), true));
3212 }
3213 /**
3214 * @brief Calculate the Sine function
3215 * Ultimately uses sin1() or cos1() with a reduced range of [-pi/4, pi/4].
3216 *
3217 * Accuracy, measured against mpmath at I = 1, 2, 4, 16, 32, 62 and 63 where the function exists: within 2.5 ulp
3218 * for |x| < 4 (1.4 ulp from I = 16 up). Beyond that the reduction x - n * pi/2 adds n times the
3219 * rounding error of pi/2 in this instantiation, at most |x| / 3 ulp more: 320 ulp for |x| near
3220 * 1000 at I = 32.
3221 * @param x value in Radians
3222 * @return Sine of x
3223 */
3224 [[nodiscard]] friend fixed_point128 sin(fixed_point128 x) noexcept
3225 {
3226 static_assert(I >= 4, "sin() needs template parameter <I> to be at least 4: it evaluates sin1() and cos1()!");
3227 static const fixed_point128& half_pi = fixed_point128::half_pi(); // pi / 2
3228 double round = (x.is_positive()) ? 0.5 : -0.5;
3229
3230 int64_t n = static_cast<int64_t>((x / half_pi) + round);
3231 x -= half_pi * n;
3232 n = n & 3ull; // n mod 4
3233 switch (n) {
3234 case 0: // [-45-45) degrees
3235 return sin1(x);
3236 case 1: // [45-135) degrees
3237 return cos1(x);
3238 case 2: // [135-225) degrees
3239 return -sin1(x);
3240 case 3: // [225-315) degrees
3241 default:
3242 return -cos1(x);
3243 }
3244 }
3245 /**
3246 * @brief Calculate the inverse sine function
3247 * Newton's method on sin() for |x| up to one half, see AsinNewton(). Beyond that the identity
3248 * asin(x) = pi/2 - 2 asin(sqrt((1 - x) / 2)) keeps the iteration away from pi/2, where the
3249 * derivative it divides by vanishes and the refinement stalled at double precision: asin(1) was
3250 * 4e16 ulp off at fixed_point128<16>. The square root is correctly rounded, so the identity costs
3251 * a few ulp at most.
3252 *
3253 * Accuracy, measured against mpmath at I = 4, 16, 32, 62 and 63: within 3.5 ulp.
3254 * @param x value in radians in the range [-1,1]
3255 * @return Inverse sine of x, zero outside [-1,1]
3256 */
3257 [[nodiscard]] friend fixed_point128 asin(fixed_point128 x) noexcept
3258 {
3259 static_assert(I >= 4, "asin() needs template parameter <I> to be at least 4: it evaluates sin() and cos()!");
3260 if (x < -1 || x > 1)
3261 return 0;
3262
3263 const bool negative = x.is_negative();
3264 x = fabs(x);
3265 fixed_point128 res;
3266 if (x <= fixed_point128::half()) {
3267 res = AsinNewton(x);
3268 } else {
3269 res = fixed_point128::half_pi() - (AsinNewton(RootOfHalfComplement(x)) << 1);
3270 }
3271 return (negative) ? -res : res;
3272 }
3273 /**
3274 * @brief Calculate the cosine function
3275 * Ultimately uses sin1() or cos1() with a reduced range of [-pi/4, pi/4]. cos(0) is exactly one.
3276 *
3277 * Accuracy, measured against mpmath at I = 1, 2, 4, 16, 32, 62 and 63 where the function exists: within 1.8 ulp
3278 * for |x| < 4 (1.3 ulp from I = 16 up), plus at most |x| / 3 ulp of argument reduction beyond, see
3279 * sin().
3280 * @param x value in Radians
3281 * @return Cosine of x
3282 */
3283 [[nodiscard]] friend fixed_point128 cos(fixed_point128 x) noexcept
3284 {
3285 static_assert(I >= 4, "cos() needs template parameter <I> to be at least 4: it evaluates sin1() and cos1()!");
3286 static const fixed_point128& half_pi = fixed_point128::half_pi(); // pi / 2
3287 double round = (x.is_positive()) ? 0.5 : -0.5;
3288
3289 int64_t n = static_cast<int64_t>((x / half_pi) + round);
3290 x -= half_pi * n;
3291 n = n & 3ull; // n mod 4
3292 switch (n) {
3293 case 0: // [-45-45) degrees
3294 return cos1(x);
3295 case 1: // [45-135) degrees
3296 return -sin1(x);
3297 case 2: // [135-225) degrees
3298 return -cos1(x);
3299 case 3: // [225-315) degrees
3300 default:
3301 return sin1(x);
3302 }
3303 }
3304 /**
3305 * @brief Calculate the inverse cosine function
3306 * pi/2 - asin(x) for |x| up to one half. Beyond that acos(x) = 2 asin(sqrt((1 - x) / 2)) for a
3307 * positive x and pi - 2 asin(sqrt((1 + x) / 2)) for a negative one, which keep Newton's method
3308 * away from the ends of the domain: acos(-1) was 8e16 ulp off at fixed_point128<16>.
3309 *
3310 * Accuracy, measured against mpmath at I = 4, 16, 32, 62 and 63: within 4 ulp.
3311 * @param x value in radians in the range [-1,1]
3312 * @return Inverse cosine of x, zero outside [-1,1]
3313 */
3314 [[nodiscard]] friend fixed_point128 acos(fixed_point128 x) noexcept
3315 {
3316 static_assert(I >= 4, "acos() needs template parameter <I> to be at least 4: it evaluates sin() and cos()!");
3317 if (x < -1 || x > 1)
3318 return 0;
3319
3320 const fixed_point128 magnitude = fabs(x);
3321 if (magnitude <= fixed_point128::half()) {
3322 const fixed_point128 res = AsinNewton(magnitude);
3323 return fixed_point128::half_pi() + ((x.is_negative()) ? res : -res);
3324 }
3325
3326 const fixed_point128 twice = AsinNewton(RootOfHalfComplement(magnitude)) << 1;
3327 return (x.is_negative()) ? fixed_point128::pi() - twice : twice;
3328 }
3329 /**
3330 * @brief Calculate the tangent function
3331 * tan(x) = sin(x)/cos(x)
3332 *
3333 * The error of the cosine is divided by the cosine itself, so it grows towards the poles. Measured
3334 * against mpmath for |x| < 4 at I = 4, 16, 32, 62 and 63: within 45 * max(1, |tan(x)|) ulp.
3335 * @param x value
3336 * @return Tangent of x. Zero at the poles (odd multiples of pi/2), where the true value is
3337 * unbounded and the cosine comes out exactly zero.
3338 */
3339 [[nodiscard]] friend FP128_INLINE fixed_point128 tan(fixed_point128 x) noexcept
3340 {
3341 static_assert(I >= 4, "tan() needs template parameter <I> to be at least 4: it evaluates sin() and cos()!");
3342 constexpr bool use_cordic = false; // CORDIC is currently slower and less accurate
3343 if constexpr (use_cordic) {
3344 fixed_point128 sin_x, cos_x;
3345 _sincos_cordic(x, sin_x, cos_x, false);
3346
3347 if (cos_x)
3348 return sin_x / cos_x;
3349 return 0;
3350 } else {
3351 const fixed_point128 cos_x = cos(x);
3352 // the range reduction lands exactly on zero at the poles. Dividing by it would throw
3353 // out of this noexcept function, so report zero like the CORDIC branch above does.
3354 if (!cos_x)
3355 return 0;
3356 return sin(x) / cos_x;
3357 }
3358 }
3359 /**
3360 * @brief Calculate the inverse tangent function
3361 * Accuracy, measured against mpmath at I = 1, 2, 4, 16, 32, 62 and 63 where the function exists: within 2.2 ulp.
3362 * @param x value
3363 * @return Arctangent of x
3364 */
3365 [[nodiscard]] friend fixed_point128 atan(fixed_point128 x) noexcept
3366 {
3367 static_assert(I >= 4, "atan() needs template parameter <I> to be at least 4: it evaluates sin() and cos()!");
3368 // constants for segmentation
3369 static const fixed_point128& half_pi = fixed_point128::half_pi(); // pi / 2
3370 static const fixed_point128 eps = fixed_point128::epsilon() << 1;
3371 bool comp = false;
3372 constexpr int max_iterations = 6;
3373
3374 // make argument positive, save the sign
3375 const bool negative = x.is_negative();
3376 x = fabs(x);
3377
3378 // limit argument to 0..1. x is greater than one here, so the division cannot be by zero.
3379 if (x > 1) {
3380 comp = true;
3381 x = one() / x;
3382 }
3383
3384 // initial step uses the CRT function.
3385 fixed_point128 res = ::atan(static_cast<double>(x));
3386 //
3387 // Xn+1 = Xn - cos(Xn) * ( sin(Xn) - a * cos(Xn))
3388 //
3389 // where 'a' is the argument, each iteration will converge on the result if the initial
3390 // estimate is close enough.
3391 for (int i = 0; i < max_iterations; ++i) {
3392 fixed_point128 cos_xn = cos(res);
3393 fixed_point128 sin_xn = sin(res);
3394 fixed_point128 e = cos_xn * (sin_xn - x * cos_xn); // this is the iteration estimated error
3395 res -= e;
3396 if (fabs(e) <= eps)
3397 break;
3398 }
3399
3400 // restore complement if needed
3401 if (comp)
3402 res = half_pi - res;
3403
3404 // restore sign if needed
3405 return (negative) ? -res : res;
3406 }
3407 /**
3408 * @brief Calculate the inverse tangent function of the ratio y / x
3409 * Accuracy, measured against mpmath at I = 1, 2, 4, 16, 32, 62 and 63 where the function exists: within 3.3 ulp.
3410 * @param y value
3411 * @param x value
3412 * @return Arctangent of y / x in the range [-pi, pi]
3413 */
3414 [[nodiscard]] friend fixed_point128 atan2(fixed_point128 y, fixed_point128 x) noexcept
3415 {
3416 static_assert(I >= 4, "atan2() needs template parameter <I> to be at least 4: it evaluates atan()!");
3417 // constants for segmentation
3418 static const fixed_point128& pi = fixed_point128::pi();
3419 static const fixed_point128& half_pi = fixed_point128::half_pi(); // pi / 2
3420
3421 // x == 0
3422 if (!x) {
3423 if (!y)
3424 return fixed_point128(0);
3425
3426 return (y.is_negative()) ? -half_pi : half_pi;
3427 }
3428 // y == 0
3429 if (!y)
3430 return (x.is_negative()) ? pi : fixed_point128(0);
3431
3432 // The ratio is kept at or below one in magnitude. Steeper than the diagonal, the angle is
3433 // +-pi/2 - atan(x / y) with the sign of y, in every quadrant. That used to take its sign
3434 // from atan(x / y) instead, which lost it whenever x / y rounded to zero: atan2(1000, -1e-30)
3435 // came out as 3pi/2 at fixed_point128<16>.
3436 if (fabs(y) > fabs(x)) {
3437 return ((y.is_negative()) ? -half_pi : half_pi) - atan(x / y);
3438 }
3439
3440 // flatter than the diagonal: atan(y / x), moved into the left half plane when x is negative
3441 const fixed_point128 res = atan(y / x);
3442 if (x.is_positive()) {
3443 return res;
3444 }
3445
3446 return (y.is_negative()) ? res - pi : res + pi;
3447 }
3448 /**
3449 * @brief Calculate the hyperbolic sine function
3450 * Use the exponent function which produces more accurate results than the power series.
3451 * e^x - e^(-x)
3452 * sinh(x) = ------------
3453 * 2
3454 * Accuracy, measured against mpmath at I = 1, 2, 4, 16, 32, 62 and 63 where the function exists: within
3455 * 10 * max(1, |sinh(x)|) ulp at I = 4 and 3 * max(1, |sinh(x)|) ulp from I = 16 up. e^x itself has
3456 * to fit the range, so a result between 2^(I-1) and 2^I overflows.
3457 * @param x value
3458 * @return Sine of x
3459 */
3460 [[nodiscard]] friend FP128_FORCE_INLINE fixed_point128 sinh(const fixed_point128& x) noexcept
3461 {
3462 static_assert(I >= 4, "sinh() needs template parameter <I> to be at least 4!");
3463 return (exp(x) - exp(-x)) >> 1;
3464 // the below code while faster, produces lower precision results
3465 // if (fabs(x) > 1) {
3466 // return (exp(x) - exp(-x)) >> 1;
3467 // }
3468 // else {
3469 // // Using the Maclaurin series expansion, the formula is :
3470 // // x^3 x^5 x^7
3471 // // sinh(x) = x + --- + --- + --- +...
3472 // // 2! 4! 6!
3473 //
3474 // // first part of the series is just 'x'
3475 // const fixed_point128 xx = x * x;
3476 // fixed_point128 elem_denom, elem_nom = x;
3477 // fixed_point128 res = x;
3478
3479 // // compute the rest of the series, starting with: -(x^3 / 2!)
3480 // for (int i = 3; ; i += 2) {
3481 // elem_nom *= xx;
3482 // fact_reciprocal(i - 1, elem_denom);
3483 // fixed_point128 elem = elem_nom * elem_denom; // next element in the series
3484 // // precision limit has been hit
3485 // if (!elem)
3486 // break;
3487 // res += elem;
3488 // }
3489 // return res;
3490 // }
3491 }
3492 /**
3493 * @brief Calculates the inverse hyperbolic sine
3494 * For positive x:
3495 * asinh(x) = log(x + sqrt(x^2 + 1))
3496 * For negative x, the function returns the result with the sign inverted.
3497 * The root is exact before it is rounded (RootOfSquareAndOne()) and the sum is kept from overflowing
3498 * (LogOfSum()), so every argument works, lowest() included. Accuracy, measured against mpmath at
3499 * I = 1, 2, 4, 16, 32, 62 and 63 over the whole range: within 2.8 ulp.
3500 * @param x value
3501 * @return Inverse hyperbolic sine of x
3502 */
3503 [[nodiscard]] friend FP128_INLINE fixed_point128 asinh(const fixed_point128& x) noexcept
3504 {
3505 uint64_t l = 0, h = 0;
3506 (void)x.GetMagnitude(l, h);
3507 const fixed_point128 res = LogOfSum(l, h, RootOfSquareAndOne(x, false));
3508 return (x.is_negative()) ? -res : res;
3509 }
3510 /**
3511 * @brief Calculate the hyperbolic cosine function
3512 * e^x + e^(-x)
3513 * cosh(x) = ------------
3514 * 2
3515 * Accuracy, measured against mpmath at I = 1, 2, 4, 16, 32, 62 and 63 where the function exists: within
3516 * 10 * max(1, cosh(x)) ulp at I = 4 and 3 * max(1, cosh(x)) ulp from I = 16 up. e^|x| itself has to
3517 * fit the range, see sinh().
3518 * @param x value
3519 * @return Hyperbolic cosine of x
3520 */
3521 [[nodiscard]] friend FP128_FORCE_INLINE fixed_point128 cosh(const fixed_point128& x) noexcept
3522 {
3523 static_assert(I >= 4, "cosh() needs template parameter <I> to be at least 4!");
3524 return (exp(x) + exp(-x)) >> 1;
3525
3526 // Using the Maclaurin series expansion, the formula is:
3527 // x^2 x^4 x^6
3528 // sinh(x) = 1 + --- + --- + --- + ...
3529 // 2! 4! 6!
3530
3531 // const fixed_point128 xx = x * x;
3532 // fixed_point128 elem_denom, elem_nom = fixed_point128::one();
3533 //// first part of the series is 1
3534 // fixed_point128 res = fixed_point128::one();
3535
3536 //// compute the rest of the series, starting with: -(x^2 / 2!)
3537 // for (int i = 2; ; i += 2) {
3538 // elem_nom *= xx;
3539 // fact_reciprocal(i, elem_denom);
3540 // fixed_point128 elem = elem_nom * elem_denom; // next element in the series
3541 // // precision limit has been hit
3542 // if (!elem)
3543 // break;
3544 // res += elem;
3545 // }
3546
3547 // return res;
3548 }
3549 /**
3550 * @brief Calculates the inverse hyperbolic cosine
3551 * For x >= 1:
3552 * acosh(x) = log(x + sqrt(x^2 - 1))
3553 * For x < 1, the function return zero
3554 * Accuracy, measured against mpmath at I = 1, 2, 4, 16, 32, 62 and 63 over the whole range: within
3555 * 2.9 ulp. It was out by up to 5e8 ulp just above one, where x^2 - 1 cancels.
3556 * @param x value in the range [1, inf]
3557 * @return Inverse hyperbolic cosine of x
3558 */
3559 [[nodiscard]] friend FP128_INLINE fixed_point128 acosh(const fixed_point128& x) noexcept
3560 {
3561 if (x < 1)
3562 return 0;
3563
3564 // The root of x^2 - 1 is exact before rounding, see RootOfSquareAndOne(): formed in this type
3565 // the difference cancels for an x near one and the root magnifies its rounding error. The sum
3566 // is kept from overflowing by LogOfSum().
3567 return LogOfSum(x.low, x.high, RootOfSquareAndOne(x, true));
3568 }
3569 /**
3570 * @brief Calculates the hyperbolic tangent
3571 * e^x - e^(-x) 1 - e^(-2|x|)
3572 * tanh(x) = ------------ = ---------------, with the sign of x
3573 * e^x + e^(-x) 1 + e^(-2|x|)
3574 * The second form is the one evaluated, for every argument. Accuracy, measured against mpmath at I = 1, 2, 4, 16, 32, 62 and 63 where the function exists:
3575 * within 4.2 ulp.
3576 * @param x value
3577 * @return hyperbolic tangent of x
3578 */
3579 [[nodiscard]] friend FP128_INLINE fixed_point128 tanh(const fixed_point128& x) noexcept
3580 {
3581 static_assert(I >= 2, "tanh() needs template parameter <I> to be at least 2: it evaluates exp()!");
3582 // (1 - e^(-2|x|)) / (1 + e^(-2|x|)) with the sign of x: only e^(-2|x|), which is at most one,
3583 // is ever formed. The quotient of e^x - e^-x and e^x + e^-x this replaced overflowed with e^x,
3584 // which happens once |x| reaches I ln(2) - tanh(12) was garbage at fixed_point128<16>.
3585 const fixed_point128 magnitude = fabs(x);
3586 fixed_point128 e2;
3587 if (magnitude.is_positive() && magnitude.get_exponent() < I - 1) {
3588 e2 = exp(-(magnitude << 1));
3589 } else {
3590 // 2|x| does not fit the range (lowest() included, whose fabs() wraps): square e^-|x| instead
3591 e2 = sqr(exp(-magnitude));
3592 }
3593 const fixed_point128 res = (fixed_point128::one() - e2) / (fixed_point128::one() + e2);
3594 return (x.is_negative()) ? -res : res;
3595 }
3596 /**
3597 * @brief Calculates the inverse hyperbolic tangent
3598 * 1 + x
3599 * atanh(x) = 0.5 * log( -----) = 0.5 * (log(1 + x) - log(1 - x))
3600 * 1 - x
3601 * The second form is the one evaluated. Both of its logarithms take an argument in (0, 2), inside
3602 * the range of every instantiation, while the quotient of the first form leaves the range as x
3603 * approaches one - beyond 0.88 at fixed_point128<4>, within 2^-15 of one at fixed_point128<16> -
3604 * and the wrapped value made log() throw out of this noexcept function, terminating the process.
3605 * Accuracy, measured against mpmath at I = 4, 16, 32, 62 and 63: within 1.4 ulp. Below I = 4 the
3606 * same holds where log(1 - x) fits the range, which log() needs for its log2 (see log()): for
3607 * |x| up to 0.75 at I = 1 and 0.9375 at I = 2.
3608 * @param x value in the range (-1, 1)
3609 * @return Inverse hyperbolic tangent of x, zero outside (-1, 1). A result beyond the range of the
3610 * instantiation, which only a narrow one can meet, wraps like any overflow.
3611 */
3612 [[nodiscard]] friend FP128_INLINE fixed_point128 atanh(const fixed_point128& x) noexcept
3613 {
3615 // compared without fabs(), which leaves lowest() negative
3616 if (x <= -one || x >= one)
3617 return 0;
3618
3619 return (log(one + x) - log(one - x)) >> 1;
3620 }
3621 /**
3622 * x
3623 * @brief Calculates the exponent of x: e
3624 * Using the Maclaurin series expansion, the formula is:
3625 * 1 2 3
3626 * x x x
3627 * exp(x) = 1 + --- + --- + --- + ...
3628 * 1! 2! 3!
3629 *
3630 * The Maclaurin series will quickly overflow as x's power increases rapidly.
3631 *
3632 * x ix fx
3633 * Using the equality e = e * e
3634 * Where ix is the integer part of x and fx is the fraction part.
3635 * ix is computed via multiplications which won't overflow if the result value can be held.
3636 * fx is computed via Maclaurin series expansion, but since fx < 1, it won't overflow.
3637 * A negative x works with 1/e and the alternating series of e^-fx, so it never forms e^|x|.
3638 *
3639 * Accuracy, measured against mpmath at I = 1, 2, 4, 16, 32, 62 and 63 where the function exists: within
3640 * 6.2 * max(1, e^x) ulp. The argument itself is only known to half an ulp, which alone moves a
3641 * large result by e^x / 2 ulp.
3642 * @param x A number specifying a power.
3643 * @return Exponent of x
3644 */
3645 [[nodiscard]] friend FP128_INLINE fixed_point128 exp(const fixed_point128& x) noexcept
3646 {
3647 static_assert(I >= 2, "exp() needs template parameter <I> to be at least 2: it multiplies by e(), which needs 2 integer bits!");
3648 static const fixed_point128 e = fixed_point128::e();
3649 // A negative exponent works with 1/e and an alternating series rather than inverting e^|x|:
3650 // e^|x| overflows long before e^-|x| leaves the grid - exp(-12) needs e^12 = 162755, beyond
3651 // the range of fixed_point128<16>, and came out as garbage.
3652 const bool negative = x.is_negative();
3653 fixed_point128 int_part;
3654 const fixed_point128 fx = modf(fabs(x), &int_part); // fraction part of |x|
3655 uint64_t ix = static_cast<uint64_t>(int_part); // 64 bit is an overkill to hold the exponent
3656
3657 // e^ix, or e^-ix, by binary powering
3659 fixed_point128 b = (negative) ? FromFraction128(inv_e_fraction[0], inv_e_fraction[1]) : e;
3660 while (ix > 0) {
3661 if (ix & 1) {
3662 exp_ix *= b;
3663 }
3664 ix >>= 1;
3665 if (ix > 0) {
3666 b.square();
3667 }
3668 }
3669
3670 // e^fx, or e^-fx, by the Maclaurin series: fx < 1, so the terms shrink and none overflows
3671 if (!fx)
3672 return exp_ix;
3673
3674 fixed_point128 exp_fx = (negative) ? fixed_point128::one() - fx : fixed_point128::one() + fx;
3675 fixed_point128 elem_denom, elem_nom = fx;
3676 for (int i = 2;; ++i) {
3677 elem_nom *= fx;
3678 fact_reciprocal(i, elem_denom);
3679 const fixed_point128 elem = elem_nom * elem_denom;
3680 if (!elem)
3681 break;
3682 if (negative && (i & 1)) {
3683 exp_fx -= elem;
3684 } else {
3685 exp_fx += elem;
3686 }
3687 }
3688
3689 return exp_ix * exp_fx;
3690 }
3691 /**
3692 * @brief Calculates the exponent of x and reduces 1 from the result: (e^x) - 1
3693 * Evaluated as exp(x) - 1, which in a fixed point type loses nothing to cancellation: the
3694 * absolute error is that of exp(), within 9.3 * max(1, |e^x - 1|) ulp measured at I = 4 and
3695 * 6.2 * max(1, e^x) ulp from I = 16 up.
3696 * @param x A number specifying a power.
3697 * @return Exponent of x
3698 */
3699 [[nodiscard]] friend FP128_FORCE_INLINE fixed_point128 expm1(const fixed_point128& x) noexcept
3700 {
3701 static_assert(I >= 2, "expm1() needs template parameter <I> to be at least 2: it evaluates exp()!");
3702 return exp(x) - fixed_point128::one();
3703 }
3704 /**
3705 * @brief Computes 2 to the power of x
3706 * exp(x * ln(2)), the constant applied with 128 fraction bits. Accuracy, measured against mpmath at I = 1, 2, 4, 16, 32, 62 and 63 where the function exists:
3707 * within 5.5 * max(1, 2^x) ulp.
3708 * @param x Exponent value
3709 * @return 2^x
3710 */
3711 [[nodiscard]] friend FP128_INLINE fixed_point128 exp2(const fixed_point128& x) noexcept
3712 {
3713 static_assert(I >= 2, "exp2() needs template parameter <I> to be at least 2: it evaluates exp()!");
3714 //
3715 // Based on exponent law: (x^n)^m = x^(m*n)
3716 // Convert the exponent x (function parameter) to produce an exponent that will work with exp()
3717 // y = log(2)
3718 // 2^x = e^(y*x) = exp(y*x)
3719 //
3720 return exp(x.MulByFraction128(ln2_fraction[1], ln2_fraction[0]));
3721 }
3722 /**
3723 * @brief Computes x to the power of y
3724 * exp(y * log(x)). Accuracy, measured against mpmath at I = 1, 2, 4, 16, 32, 62 and 63 where the function exists: within
3725 * 7.3 * max(1, x^y) ulp at I = 4 and 4.4 * max(1, x^y) ulp from I = 16 up. Exact powers are not
3726 * exact: pow(2, 3) is 8 - 15 ulp at I = 16. y * log(x) has to fit the range.
3727 * @param x Base value, must be positive
3728 * @param y Exponent value
3729 * @return x^y, one when x is one, zero when x is negative, and for x = 0 one when y = 0 and zero
3730 * otherwise
3731 */
3732 [[nodiscard]] friend FP128_INLINE fixed_point128 pow(const fixed_point128& x, const fixed_point128& y) noexcept
3733 {
3734 static_assert(I >= 2, "pow() needs template parameter <I> to be at least 2: it evaluates exp()!");
3735 //
3736 // Based on exponent law: (x^n)^m = x^(m * n)
3737 // Convert the exponent y (function parameter) to produce an exponent that will work with exp()
3738 // z = log(x)
3739 // pow(x, y) = x^y = e^(y * z) = exp(y * z)
3740 //
3741 if (x.is_negative())
3742 return 0;
3743
3744 // log() throws on a zero input and this function is noexcept, so zero has to be handled
3745 // here. Follows the CRT: pow(0, 0) is 1 and pow(0, y) is zero for any other y.
3746 if (x.is_zero())
3747 return (y.is_zero()) ? fixed_point128::one() : fixed_point128(0);
3748
3749 // log(1) is zero, and so is the log of a value within an ulp or two of one: x^y is one there
3750 // for every y. Returning the zero itself, as this used to, made pow(1, y) zero.
3751 const fixed_point128 lan_x = log(x);
3752 if (!lan_x)
3753 return fixed_point128::one();
3754
3755 return exp(y * lan_x);
3756 }
3757 /**
3758 * @brief Calculates the Log base 2 of x: y = log2(x)
3759 * Accuracy, measured against mpmath at I = 1, 2, 4, 16, 32, 62 and 63 where the function exists: within 2 ulp
3760 * at I = 1, 1.7 ulp at I = 2 and 1.1 ulp from I = 4 up. The compile time evaluation takes a
3761 * different, bitwise path that truncates instead: it can be one ulp below the runtime result.
3762 * A result outside the range wraps, which a narrow instantiation meets for small arguments:
3763 * log2(x) needs x >= 2^(-2^I).
3764 * @param x The number to perform log2 on.
3765 * @return log2(x)
3766 */
3767 [[nodiscard]] friend FP128_INLINE constexpr fixed_point128 log2(fixed_point128 x)
3768 {
3769 if (x.is_zero() || x.is_negative()) {
3770 throw std::domain_error("Math domain error! Function accepts positive, non-zero values only.");
3771 }
3772
3773 // Calculate the log in 2 steps:
3774 // - The integer part (iy) is the position of the leading one, which lzcnt gives directly.
3775 // - The fraction part is where the work is; see log2_fraction() below.
3776 // The result is the sum of the two. Based on the identity:
3777 // log(x + y) = log(x) + log(y)
3778 const int32_t leading_zeros = static_cast<int32_t>(lzcnt128(x.low, x.high));
3779 const int32_t expo = 127 - leading_zeros - F;
3780 const fixed_point128 iy = expo; // integer part of the result
3781
3782 // x is an exponent of 2: there is nothing below its leading one, so the fraction is zero.
3783 const uint64_t below_low = x.low - 1;
3784 const uint64_t below_high = x.high - ((x.low == 0) ? 1ull : 0ull);
3785 if (((x.low & below_low) | (x.high & below_high)) == 0) {
3786 return iy;
3787 }
3788
3789 if (std::is_constant_evaluated()) {
3790 // The bitwise path wants the value brought to [1,2) first.
3791 if (expo < 0) {
3792 x <<= -expo;
3793 } else if (expo > 0) {
3794 x >>= expo;
3795 }
3796 return iy + log2_fraction_bitwise(x);
3797 }
3798
3799 return iy + log2_fraction(x.low, x.high, leading_zeros);
3800 }
3801 /**
3802 * @brief Calculates the natural Log (base e) of x: log(x)
3803 * log2(x) * ln(2), the constant applied with 128 fraction bits by MulByFraction128() - a constant
3804 * held to this instantiation's F bits, multiplied by a log2 of up to 63, would cost tens of ulp.
3805 * Accuracy, measured against mpmath at I = 1, 2, 4, 16, 32, 62 and 63 where the function exists: within 1.9 ulp.
3806 * log2(x) has to fit the range as well, so a narrow instantiation cannot take the log of an
3807 * argument below 2^(-2^I) even when its log would fit: at I = 1 that is x below 0.25.
3808 * @param x The number to perform log on.
3809 * @return log(x)
3810 * @throws std::domain_error when x is zero or negative.
3811 */
3813 {
3814 if (x.is_zero() || x.is_negative()) {
3815 throw std::domain_error("Math domain error! Function accepts positive, non-zero values only.");
3816 }
3817 if (x == 1)
3818 return 0;
3819
3820 return log2(x).MulByFraction128(ln2_fraction[1], ln2_fraction[0]);
3821 }
3822 /**
3823 * @brief Calculates the natural Log (base e) of 1 + x: log(1 + x)
3824 * Not noexcept: it forwards to log(), which rejects a non positive argument. Marking it
3825 * noexcept would turn that domain_error into a call to std::terminate. 1 + x is exact in a fixed
3826 * point type, so the error is that of log(): within 1.2 ulp measured, with log()'s limit on small
3827 * arguments at I < 7.
3828 * @param x The number to perform log on.
3829 * @return log1p(x)
3830 * @throws std::domain_error when x is -1 or below.
3831 */
3833 /**
3834 * @brief Calculates Log base 10 of x: log10(x)
3835 * log2(x) * log10(2), the constant applied with 128 fraction bits, see log(). Accuracy, measured against mpmath at I = 1, 2, 4, 16, 32, 62 and 63 where the function exists:
3836 * within 1 ulp, with log()'s limit on small arguments at I < 7.
3837 * @param x The number to perform log on.
3838 * @return log10(x)
3839 */
3841 {
3842 if (x.is_zero() || x.is_negative()) {
3843 throw std::domain_error("Math domain error! Function accepts positive, non-zero values only.");
3844 }
3845
3846 if (x == 1)
3847 return 0;
3848
3849 // log2(x) * log10(2), the constant applied with 128 fraction bits, see log()
3850 return log2(x).MulByFraction128(log10_2_fraction[1], log10_2_fraction[0]);
3851 }
3852 /**
3853 * @brief Calculates Log base 2 of x as an integer ignoring the sign of x.
3854 * floor(log2(fabs(x))), as the C function: logb(-8) is 3. A narrow instantiation cannot hold the
3855 * exponent of its smallest values - logb(epsilon()) is -126 for fixed_point128<1> - and the result
3856 * then wraps like any other overflow.
3857 * @param x The number to perform log on.
3858 * @return logb(x)
3859 * @throws std::domain_error when x is zero. The C function returns minus infinity for it, which
3860 * this type cannot represent.
3861 */
3862 [[nodiscard]] friend FP128_FORCE_INLINE constexpr fixed_point128 logb(fixed_point128 x)
3863 {
3864 if (x.is_zero()) {
3865 throw std::domain_error("Math domain error! logb() of zero is minus infinity.");
3866 }
3867
3868 return x.get_exponent();
3869 }
3870
3871 /// @}
3872}; // class fixed_point128
3873
3874
3875/**
3876 * @brief Writes a fixed_point128 to a stream, honouring its width, fill and adjustment.
3877 * @tparam I Integer bit count of the type
3878 */
3879template <int32_t I> inline std::ostream& operator<<(std::ostream& os, const fixed_point128<I>& value)
3880{
3881 std::string text = static_cast<std::string>(value);
3882 if ((os.flags() & std::ios_base::showpos) && !text.empty() && text[0] != '-')
3883 text.insert(text.begin(), '+');
3884
3885 const std::streamsize width = os.width();
3886 os.width(0);
3887 if (static_cast<std::streamsize>(text.size()) < width) {
3888 const size_t padding = static_cast<size_t>(width) - text.size();
3889 const std::ios_base::fmtflags adjust = os.flags() & std::ios_base::adjustfield;
3890 if (adjust == std::ios_base::left)
3891 text.append(padding, os.fill());
3892 else if (adjust == std::ios_base::internal && !text.empty() && (text[0] == '-' || text[0] == '+'))
3893 text.insert(1, padding, os.fill());
3894 else
3895 text.insert(0, padding, os.fill());
3896 }
3897 return os << text;
3898}
3899
3900/**
3901 * @brief Reads a fixed_point128 from a stream, the way the builtin arithmetic extractors do.
3902 *
3903 * Reads what the constructor from a string reads - an optional sign, digits, an optional point and
3904 * more digits - correctly rounded to the grid, and stops at the first character that is not part
3905 * of it, leaving it in the stream: "2.5,3" gives 2.5 and leaves ",3".
3906 *
3907 * Failure sets failbit: no digits at all stores zero, and a value outside [lowest(), max()] stores
3908 * the nearer of the two. Leading white space is skipped unless skipws is off. This used to read a
3909 * whole white space delimited token through the string constructor, which never failed: "xyz" read
3910 * as zero and an overflow wrapped silently.
3911 * @tparam I Integer bit count of the type
3912 */
3913template <int32_t I> inline std::istream& operator>>(std::istream& is, fixed_point128<I>& value)
3914{
3915 const std::istream::sentry sentry(is);
3916 if (!sentry)
3917 return is;
3918
3919 using traits = std::char_traits<char>;
3920 std::streambuf* const buffer = is.rdbuf();
3921 std::string text;
3922 int c = buffer->sgetc();
3923 const auto take = [&]() {
3924 text += traits::to_char_type(c);
3925 buffer->sbumpc();
3926 c = buffer->sgetc();
3927 };
3928 if (c == '+' || c == '-') {
3929 take();
3930 }
3931 while (c != traits::eof() && c >= '0' && c <= '9') {
3932 take();
3933 }
3934 if (c == '.') {
3935 take();
3936 while (c != traits::eof() && c >= '0' && c <= '9') {
3937 take();
3938 }
3939 }
3940 if (c == traits::eof()) {
3941 is.setstate(std::ios_base::eofbit);
3942 }
3943
3944 uint64_t low = 0, high = 0;
3945 const char* end = nullptr;
3946 const int32_t status = fixed_point128<I>::ParseDecimal(text.data(), text.data() + text.size(), low, high, end);
3947 if (status == 0) {
3948 value = fixed_point128<I>();
3949 is.setstate(std::ios_base::failbit);
3950 } else if (status == 2) {
3951 value = (!text.empty() && text[0] == '-') ? std::numeric_limits<fixed_point128<I>>::lowest() : std::numeric_limits<fixed_point128<I>>::max();
3952 is.setstate(std::ios_base::failbit);
3953 } else {
3954 value = fixed_point128<I>(low, high);
3955 }
3956 return is;
3957}
3958
3959} // namespace fp128
3960
3961
3962namespace std
3963{
3964/**
3965 * @brief Numeric properties of `fixed_point128<I>`.
3966 *
3967 * A fixed point type is exact on its own grid rather than approximate like a floating point one,
3968 * so is_exact is true and epsilon is the spacing of that grid - the same everywhere, unlike a
3969 * float's, which is the spacing near one.
3970 *
3971 * The exponent members read the grid the way the floating point definitions read a significand:
3972 * the smallest positive value epsilon() = 2^(I-127) is 2^(min_exponent-1), and max() is just under
3973 * 2^max_exponent = 2^I. min() follows the floating point reading too and is the smallest positive
3974 * value; lowest() is the most negative one.
3975 *
3976 * Every member is usable in a constant expression, as the standard requires of a specialization.
3977 * The const, volatile and const volatile forms need no specialization of their own: <limits>
3978 * already defines numeric_limits<cv T> to have the members of numeric_limits<T>.
3979 */
3980template <int32_t I> class numeric_limits<fp128::fixed_point128<I>>
3981{
3982 using value_type = fp128::fixed_point128<I>;
3983
3984public:
3985 static constexpr bool is_specialized = true;
3986 static constexpr bool is_signed = true;
3987 static constexpr bool is_integer = false;
3988 /// @brief Every representable value is exactly the number it stands for.
3989 static constexpr bool is_exact = true;
3990 static constexpr bool has_infinity = false;
3991 static constexpr bool has_quiet_NaN = false;
3992 static constexpr bool has_signaling_NaN = false;
3993 // has_denorm and has_denorm_loss are deprecated since C++23 but remain part of the interface a
3994 // generic caller may read, so they are provided.
3996 static constexpr bool has_denorm_loss = false;
3997 static constexpr float_denorm_style has_denorm = denorm_absent;
3999 /// @brief Multiplication, division (by a fixed_point128 or an integer), the right shift and the
4000 /// narrowing conversions round to the nearest grid value, a tie going away from zero.
4001 static constexpr float_round_style round_style = round_to_nearest;
4002 static constexpr bool is_iec559 = false;
4003 static constexpr bool is_bounded = true;
4004 /**
4005 * @brief +, - and * wrap around: they keep the low 128 bits of the two's complement result,
4006 * which differs from the exact one by a multiple of 2^(I+1) = max() - lowest() + epsilon().
4007 *
4008 * As for int128_t, whose builtin counterparts report false only because their overflow is
4009 * undefined. Here it is defined: max() + epsilon() is lowest(). This used to say false.
4010 */
4011 static constexpr bool is_modulo = true;
4012 /// @brief Division by zero throws std::logic_error rather than producing a value.
4013 static constexpr bool traps = true;
4014 static constexpr bool tinyness_before = false;
4015
4016 /// @brief Value bits. One of the 128 is the sign, so 127 of them carry magnitude.
4017 static constexpr int digits = 127;
4018 /// @brief Decimal digits that survive a round trip: floor(127 * log10(2)).
4019 static constexpr int digits10 = 38;
4020 static constexpr int radix = 2;
4021 /// @brief 2^(min_exponent-1) = 2^(I-127) is the smallest positive value, epsilon().
4022 static constexpr int min_exponent = I - 126;
4023 /// @brief 2^(max_exponent-1) = 2^(I-1) is the largest power of two in range; max() is 2^I - epsilon().
4024 static constexpr int max_exponent = I;
4025 static constexpr int min_exponent10 = static_cast<int>((I - 127) * 0.30102999566398119521);
4026 static constexpr int max_exponent10 = static_cast<int>(I * 0.30102999566398119521);
4027 /**
4028 * @brief Significant decimal digits that tell every pair of neighbouring values apart.
4029 *
4030 * The top decade, from 10^max_exponent10 to max(), needs the most. Its values have
4031 * max_exponent10 + 1 integer digits, and the fraction needs floor((127 - I) * log10(2)) + 1
4032 * decimal places before their spacing falls below the grid spacing 2^(I-127). The total is 40
4033 * for the I where the two floors add up to 38 (4, 7, 10, 14, ..., 57, 60) and 39 for the rest.
4034 */
4035 static constexpr int max_digits10 = max_exponent10 + static_cast<int>((127 - I) * 0.30102999566398119521) + 2;
4036
4037 /// @brief Smallest positive value, which is one unit in the last place.
4038 [[nodiscard]] static constexpr value_type min() noexcept { return value_type::epsilon(); }
4039 /// @brief Largest value, every bit below the sign set: 2^I - epsilon().
4040 [[nodiscard]] static constexpr value_type max() noexcept { return value_type(UINT64_MAX, 0x7FFFFFFFFFFFFFFFull); }
4041 /// @brief Most negative value, exactly -2^I. Two's complement makes the range asymmetric, so
4042 /// this one has no positive counterpart and negating it wraps back to itself.
4043 [[nodiscard]] static constexpr value_type lowest() noexcept { return value_type(0, 1ull << 63); }
4044 /// @brief Spacing of the grid, the same at every magnitude.
4045 [[nodiscard]] static constexpr value_type epsilon() noexcept { return value_type::epsilon(); }
4046 /// @brief Largest rounding error of an operation in units in the last place, one half.
4047 [[nodiscard]] static constexpr value_type round_error() noexcept { return value_type::half(); }
4048 [[nodiscard]] static constexpr value_type infinity() noexcept { return value_type(); }
4049 [[nodiscard]] static constexpr value_type quiet_NaN() noexcept { return value_type(); }
4050 [[nodiscard]] static constexpr value_type signaling_NaN() noexcept { return value_type(); }
4051 /// @brief No value is subnormal, so this is the smallest positive one, the same as min().
4052 [[nodiscard]] static constexpr value_type denorm_min() noexcept { return value_type::epsilon(); }
4053};
4054
4055/// @brief Hash support, so a fixed_point128 can be a key in an unordered container.
4056template <int32_t I> struct hash<fp128::fixed_point128<I>>
4057{
4058 [[nodiscard]] size_t operator()(const fp128::fixed_point128<I>& value) const noexcept
4059 {
4060 // every value has exactly one representation, so the two QWORDs are all there is to mix
4061 uint64_t low = 0, high = 0;
4062 value.get_components(low, high);
4063
4064 uint64_t state = low + 0x9E3779B97F4A7C15ull;
4065 state = (state ^ (state >> 30)) * 0xBF58476D1CE4E5B9ull;
4066 state = (state ^ (state >> 27)) * 0x94D049BB133111EBull;
4067 state ^= high + 0x9E3779B97F4A7C15ull + (state << 6) + (state >> 2);
4068 state = (state ^ (state >> 30)) * 0xBF58476D1CE4E5B9ull;
4069 return static_cast<size_t>(state ^ (state >> 31));
4070 }
4071};
4072
4073/**
4074 * @brief std::format support for fixed_point128.
4075 *
4076 * Accepts fill and alignment, a sign, zero padding and a width. The type produces its own decimal
4077 * text, which carries every digit the grid distinguishes, so no precision or presentation type is
4078 * offered.
4079 */
4080template <int32_t I> struct formatter<fp128::fixed_point128<I>, char>
4081{
4082 constexpr auto parse(basic_format_parse_context<char>& context)
4083 {
4084 auto it = context.begin();
4085 const auto end = context.end();
4086 if (it == end || *it == '}')
4087 return it;
4088
4089 const auto is_align = [](char c) { return c == '<' || c == '>' || c == '^'; };
4090 if (it + 1 != end && is_align(*(it + 1))) {
4091 fill = *it;
4092 align = *(it + 1);
4093 it += 2;
4094 } else if (is_align(*it)) {
4095 align = *it++;
4096 }
4097
4098 if (it != end && (*it == '+' || *it == '-' || *it == ' '))
4099 sign = *it++;
4100
4101 if (it != end && *it == '0') {
4102 zero_pad = true;
4103 ++it;
4104 }
4105
4106 while (it != end && *it >= '0' && *it <= '9')
4107 width = width * 10 + (*it++ - '0');
4108
4109 if (it != end && *it != '}')
4110 throw format_error("invalid format specification for fixed_point128");
4111 return it;
4112 }
4113
4114 template <typename FormatContext> auto format(const fp128::fixed_point128<I>& value, FormatContext& context) const
4115 {
4116 string text = static_cast<string>(value);
4117 if (sign != '-' && !text.empty() && text[0] != '-')
4118 text.insert(text.begin(), sign);
4119
4120 if (static_cast<int>(text.size()) < width) {
4121 const size_t padding = static_cast<size_t>(width) - text.size();
4122 if (zero_pad && align == 0) {
4123 const size_t offset = (!text.empty() && (text[0] == '-' || text[0] == '+' || text[0] == ' ')) ? 1u : 0u;
4124 text.insert(offset, padding, '0');
4125 } else if (align == '<') {
4126 text.append(padding, fill);
4127 } else if (align == '^') {
4128 text.insert(0, padding / 2, fill);
4129 text.append(padding - padding / 2, fill);
4130 } else {
4131 text.insert(0, padding, fill);
4132 }
4133 }
4134 return std::copy(text.begin(), text.end(), context.out());
4135 }
4136
4137 char fill = ' '; ///< Character the padding is made of.
4138 char align = 0; ///< One of < > ^, or zero when none was given.
4139 char sign = '-'; ///< One of + - space.
4140 bool zero_pad = false; ///< The 0 flag: pad with zeros after the sign.
4141 int width = 0; ///< Minimum field width.
4142};
4143} // namespace std
4144
4145#endif // FP128_FIXED_POINT128_T_H
Google test class (friend).
friend fixed_point128 log(fixed_point128 x)
Calculates the natural Log (base e) of x: log(x) log2(x) * ln(2), the constant applied with 128 fract...
friend fixed_point128 operator%(const T &lhs, const fixed_point128 &rhs)
Performs modulo of a scalar by a fixed_point128.
constexpr fixed_point128 operator+() const noexcept
Unary +. Returns a copy of the object.
friend constexpr fixed_point128 operator^(fixed_point128 lhs, const T &rhs)
Performs bitwise XOR (^)
friend constexpr bool operator==(const fixed_point128 &lhs, const fixed_point128 &rhs) noexcept
Compare logical/bitwise equal.
friend constexpr bool operator==(const T &lhs, const fixed_point128 &rhs) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
static constexpr fixed_point128 half() noexcept
friend constexpr bool operator<(const T &lhs, const fixed_point128 &rhs) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
constexpr int32_t get_bit(uint32_t bit) const noexcept
get a specific bit within the 128 fixed point data
constexpr fixed_point128 & operator*=(const fixed_point128 &rhs) noexcept
Multiplies a value to this object.
friend constexpr fixed_point128 operator*(const T &lhs, const fixed_point128 &rhs) noexcept
Multiplies a scalar and a fixed_point128, in that order.
static const fixed_point128 & half_pi() noexcept
Returns an instance of fixed_point128 with the value of pi / 2.
friend fixed_point128 operator/(const T &lhs, const fixed_point128 &rhs)
Divides a scalar by a fixed_point128.
fixed_point128< I > type
Self type alias.
static constexpr int32_t F
constexpr fixed_point128 & operator|=(const fixed_point128 &rhs) noexcept
Bitwise OR=.
friend constexpr bool operator>=(const fixed_point128 &lhs, const T &rhs) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
constexpr fixed_point128(int32_t x) noexcept
Constructor from int32_t type.
constexpr fixed_point128 & operator=(fixed_point128 &&rhs) noexcept
Move assignment operator.
friend fixed_point128 fmod(const fixed_point128 &x, const fixed_point128 &y)
Performs the fmod() function, similar to libc's fmod(): x - y * trunc(x / y). Exact,...
friend constexpr fixed_point128 operator<<(const T &lhs, const fixed_point128 &rhs) noexcept
Shifts a scalar left by a fixed_point128 shift count.
friend fixed_point128 asin(fixed_point128 x) noexcept
Calculate the inverse sine function Newton's method on sin() for |x| up to one half,...
constexpr fixed_point128 & operator--() noexcept
Prefix – operation (–a)
friend void fact_reciprocal(int x, fixed_point128 &res) noexcept
Factorial reciprocal (inverse). Calculates 1 / x! Maximum value of x that may produce non zero values...
friend constexpr bool operator<(const fixed_point128 &lhs, const fixed_point128 &rhs) noexcept
Return true if this object is small than the rhs.
friend fixed_point128 atan2(fixed_point128 y, fixed_point128 x) noexcept
Calculate the inverse tangent function of the ratio y / x Accuracy, measured against mpmath at I = 1,...
friend constexpr fixed_point128 operator-(fixed_point128 lhs, const T &rhs) noexcept
subtracts the right hand side operand to this object to and returns the result.
friend constexpr bool operator>=(const fixed_point128 &lhs, const fixed_point128 &rhs) noexcept
Return true this object is larger or equal than the rhs.
friend fixed_point128 sqrt(const fixed_point128 &x, uint32_t iterations=3) noexcept
Calculates the square root, correctly rounded.
friend constexpr fixed_point128 fmax(const fixed_point128 &x, const fixed_point128 &y) noexcept
Returns the maximum between x and y.
constexpr fixed_point128 & operator^=(const T &rhs)
Bitwise XOR=.
friend constexpr fixed_point128 operator+(fixed_point128 lhs, const T &rhs) noexcept
Adds 2 values and returns the result.
friend constexpr bool operator>(const fixed_point128 &lhs, const fixed_point128 &rhs) noexcept
Return true this object is larger than the rhs.
fixed_point128 & operator%=(T rhs)
Performs modulo with a generic type by converting to fixed_point128.
constexpr fixed_point128(double x) noexcept
Constructor from the double type Underflow goes to zero. Overflow, NaN and +-INF saturate to the extr...
constexpr fixed_point128 & square() noexcept
Squares this object in place.
friend constexpr fixed_point128 log2(fixed_point128 x)
Calculates the Log base 2 of x: y = log2(x) Accuracy, measured against mpmath at I = 1,...
fixed_point128(const std::string &x) noexcept
Constructor from std::string. Accurate to 37 digits after the decimal point. Allows creating very hig...
friend constexpr fixed_point128 ceil(const fixed_point128 &x) noexcept
Performs the ceil() function, similar to libc's ceil(), rounds up towards infinity.
constexpr fixed_point128 operator<<(T shift) const noexcept
Performs left shift operation. Hinted rather than forced, see operator>> above.
friend fixed_point128 tan(fixed_point128 x) noexcept
Calculate the tangent function tan(x) = sin(x)/cos(x)
static const fixed_point128 & pi2() noexcept
Returns an instance of fixed_point128 with the value of pi * 2 Needs I to be 3 or more.
constexpr fixed_point128 operator-() const noexcept
Unary -. Returns the two's complement of the object. The most negative value has no positive counterp...
friend fixed_point128 operator%(fixed_point128 lhs, const T &rhs)
Calculates modulo.
friend fixed_point128 exp(const fixed_point128 &x) noexcept
Calculates the exponent of x: e Using the Maclaurin series expansion, the formula is: 1 2 3 x x x exp...
friend fixed_point128 sin(fixed_point128 x) noexcept
Calculate the Sine function Ultimately uses sin1() or cos1() with a reduced range of [-pi/4,...
constexpr ~fixed_point128() noexcept=default
Destructor.
static const fixed_point128 & golden_ratio() noexcept
Returns an instance of fixed_point128 with the value of the golden ratio.
friend fixed_point128 cos(fixed_point128 x) noexcept
Calculate the cosine function Ultimately uses sin1() or cos1() with a reduced range of [-pi/4,...
friend constexpr fixed_point128 operator|(const T &lhs, const fixed_point128 &rhs)
Performs bitwise OR of a scalar and a fixed_point128.
constexpr fixed_point128 & operator|=(const T &rhs)
Bitwise OR=.
constexpr bool is_int() const noexcept
Returns true if the value is an int (fraction is zero)
constexpr fixed_point128 & operator-=(const T &rhs) noexcept
Subtract a value to this object.
friend constexpr bool operator<(const fixed_point128 &lhs, const T &rhs) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
friend constexpr fixed_point128 operator+(const T &lhs, const fixed_point128 &rhs) noexcept
Adds a scalar and a fixed_point128, in that order.
constexpr fixed_point128 operator>>(T shift) const noexcept
Performs right shift operation.
constexpr fixed_point128 & operator*=(T x) noexcept
Multiplies a value to this object.
constexpr fixed_point128(fixed_point128 &&rhs) noexcept
Move constructor Doesn't modify the right hand side object. Acts like a copy constructor.
constexpr fixed_point128(const fixed_point128 &rhs) noexcept
Copy constructor.
constexpr fixed_point128 operator~() const noexcept
Bitwise not (~). Flips all 128 bits, the sign included, which makes it -x - epsilon().
friend fixed_point128 expm1(const fixed_point128 &x) noexcept
Calculates the exponent of x and reduces 1 from the result: (e^x) - 1 Evaluated as exp(x) - 1,...
friend constexpr uint64_t lzcnt128(const fixed_point128 &x) noexcept
Calculates the left zero count of value x, ignoring the sign. Counted on the magnitude,...
friend constexpr fixed_point128 floor(const fixed_point128 &x) noexcept
Performs the floor() function, similar to libc's floor(), rounds down towards -infinity.
friend constexpr bool operator!=(const fixed_point128 &lhs, const fixed_point128 &rhs) noexcept
Return true when objects are not equal. Can be used as logical XOR.
friend constexpr fixed_point128 sqr(fixed_point128 x) noexcept
Calculates the square of a value. i.e. x^2.
friend fixed_point128 hypot(const fixed_point128 &x, const fixed_point128 &y) noexcept
Calculates the hypotenuse. i.e. sqrt(x^2 + y^2)
constexpr fixed_point128 & operator+=(const T &rhs) noexcept
Add a value to this object.
friend constexpr fixed_point128 round(const fixed_point128 &x) noexcept
Rounds towards the nearest integer. The halfway value (0.5) is rounded away from zero.
friend fixed_point128 cosh(const fixed_point128 &x) noexcept
Calculate the hyperbolic cosine function e^x + e^(-x) cosh(x) = ---------— 2 Accuracy,...
friend constexpr int32_t ilogb(const fixed_point128 &x) noexcept
Retrieves an integer that represents the base-2 exponent of the specified value. floor(log2(|x|)),...
constexpr fixed_point128 & operator+=(const fixed_point128 &rhs) noexcept
Add a value to this object.
friend fixed_point128 sin1(fixed_point128 x) noexcept
Calculate the sine function over a limited range [-0.5pi, 0.5pi] Using the Maclaurin series expansion...
fixed_point128 & operator/=(const fixed_point128 &rhs)
Divide this object by x. The quotient is rounded to nearest, a tie going away from zero,...
friend std::istream & operator>>(std::istream &is, fixed_point128< J > &value)
constexpr fixed_point128(uint64_t x) noexcept
Constructor from uint64_t type A value of 2^I or above overflows into the sign and wraps silently.
friend class fixed_point128
constexpr fixed_point128 & operator-=(const fixed_point128 &rhs) noexcept
Subtract a value to this object.
friend constexpr bool operator<=(const fixed_point128 &lhs, const T &rhs) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
friend constexpr bool operator!=(const fixed_point128 &lhs, const T &rhs) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
friend constexpr fixed_point128 fabs(const fixed_point128 &x) noexcept
Returns the absolute value.
constexpr fixed_point128(int64_t x) noexcept
Constructor from int64_t type The shift is done in the unsigned domain, where it wraps rather than ov...
constexpr fixed_point128< I > & operator=(const fixed_point128< I2 > &rhs) noexcept
cross-template assignment operator, can be used between two different fixed_point128 templates Behave...
fixed_point128 & operator%=(const fixed_point128 &rhs)
%= operator, the remainder of a truncating division: x - y * trunc(x / y).
constexpr fixed_point128 & operator&=(const fixed_point128 &rhs) noexcept
Bitwise AND= The operators below work on all 128 bits, the sign bit included.
static const fixed_point128 & e() noexcept
friend constexpr bool operator>(const fixed_point128 &lhs, const T &rhs) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
friend fixed_point128 exp2(const fixed_point128 &x) noexcept
Computes 2 to the power of x exp(x * ln(2)), the constant applied with 128 fraction bits....
friend constexpr fixed_point128 fdim(const fixed_point128 &x, const fixed_point128 &y) noexcept
Determines the positive difference between the first and second values.
friend constexpr fixed_point128 operator&(const T &lhs, const fixed_point128 &rhs)
Performs bitwise AND of a scalar and a fixed_point128.
friend constexpr fixed_point128 copysign(const fixed_point128 &x, const fixed_point128 &y) noexcept
returns the value of x with the sign of y.
friend constexpr bool operator!=(const T &lhs, const fixed_point128 &rhs) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
friend constexpr fixed_point128 logb(fixed_point128 x)
Calculates Log base 2 of x as an integer ignoring the sign of x. floor(log2(fabs(x))),...
static const fixed_point128 & sqrt_2() noexcept
Returns an instance of fixed_point128 with the value of sqrt(2)
constexpr bool is_zero() const noexcept
Returns true if the value is zero.
friend fixed_point128 log1p(fixed_point128 x)
Calculates the natural Log (base e) of 1 + x: log(1 + x) Not noexcept: it forwards to log(),...
friend constexpr fixed_point128 operator|(fixed_point128 lhs, const T &rhs)
Performs bitwise OR (|)
static const fixed_point128 & pi() noexcept
Returns an instance of fixed_point128 with the value of pi Needs I to be 2 or more.
friend fixed_point128 tanh(const fixed_point128 &x) noexcept
Calculates the hyperbolic tangent e^x - e^(-x) 1 - e^(-2|x|) tanh(x) = ---------— = ------------—,...
fixed_point128 & operator/=(T x)
Divide this object by x.
friend constexpr fixed_point128 modf(const fixed_point128 &x, fixed_point128 *iptr) noexcept
Split into integer and fraction parts. Both results carry the sign of the input variable.
friend fixed_point128 operator/(fixed_point128 lhs, const T &rhs)
Divides this object by the right hand side operand and returns the result.
friend constexpr fixed_point128 operator*(fixed_point128 lhs, const T &rhs) noexcept
Multiplies the right hand side operand with this object to and returns the result.
constexpr fixed_point128(uint64_t l, uint64_t h) noexcept
Constructor from the two QWORDs of the raw value, useful for creating very small constants....
constexpr fixed_point128(uint32_t x) noexcept
Constructor from uint32_t type.
friend fixed_point128 asinh(const fixed_point128 &x) noexcept
Calculates the inverse hyperbolic sine For positive x: asinh(x) = log(x + sqrt(x^2 + 1)) For negative...
static constexpr fixed_point128 epsilon() noexcept
Return an instance of fixed_point128 with the smallest positive value possible.
friend fixed_point128 reciprocal(const fixed_point128 &x) noexcept
Calculates the reciprocal of a value. y = 1 / x.
friend constexpr bool operator>=(const T &lhs, const fixed_point128 &rhs) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
friend fixed_point128 atan(fixed_point128 x) noexcept
Calculate the inverse tangent function Accuracy, measured against mpmath at I = 1,...
constexpr bool is_positive() const noexcept
Returns true if the value is positive (including zero)
fixed_point128(const char *x) noexcept
Constructor from const char* (C string).
friend fixed_point128 atanh(const fixed_point128 &x) noexcept
Calculates the inverse hyperbolic tangent 1 + x atanh(x) = 0.5 * log( --—) = 0.5 * (log(1 + x) - log(...
constexpr fixed_point128 operator--(int32_t) noexcept
Postfix – operation (a–)
constexpr fixed_point128 & operator^=(const fixed_point128 &rhs) noexcept
Bitwise XOR=.
friend fixed_point128 acosh(const fixed_point128 &x) noexcept
Calculates the inverse hyperbolic cosine For x >= 1: acosh(x) = log(x + sqrt(x^2 - 1)) For x < 1,...
fixed_point128< I > & ref_type
friend constexpr fixed_point128 operator^(const T &lhs, const fixed_point128 &rhs)
Performs bitwise XOR of a scalar and a fixed_point128.
friend fixed_point128 pow(const fixed_point128 &x, const fixed_point128 &y) noexcept
Computes x to the power of y exp(y * log(x)). Accuracy, measured against mpmath at I = 1,...
friend constexpr fixed_point128 operator-(const T &lhs, const fixed_point128 &rhs) noexcept
Subtracts a fixed_point128 from a scalar.
friend constexpr bool operator<=(const T &lhs, const fixed_point128 &rhs) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
static constexpr fixed_point128 one() noexcept
Return an instance of fixed_point128 with the value of 1 These three exact constants are returned by ...
constexpr void get_components(uint64_t &l, uint64_t &h) const noexcept
Reads the raw representation: the two QWORDs of the 128 bit two's complement value.
static constexpr uint64_t max_int_value
fixed_point128< I > * ptr_type
Pointer type alias.
constexpr fixed_point128 & operator<<=(int32_t shift) noexcept
Shift left this object. A value shifted past the range of the type wraps silently,...
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....
constexpr fixed_point128 operator++(int32_t) noexcept
Postfix ++ operation (a++)
friend fixed_point128 log10(fixed_point128 x)
Calculates Log base 10 of x: log10(x) log2(x) * log10(2), the constant applied with 128 fraction bits...
constexpr fixed_point128 & operator>>=(int32_t shift) noexcept
Shift right this object. The shift is arithmetic: the sign bit is replicated, so the result is the va...
friend fixed_point128 acos(fixed_point128 x) noexcept
Calculate the inverse cosine function pi/2 - asin(x) for |x| up to one half. Beyond that acos(x) = 2 ...
friend constexpr fixed_point128 operator>>(const T &lhs, const fixed_point128 &rhs) noexcept
Shifts a scalar right by a fixed_point128 shift count. The left operand is widened to fixed_point128 ...
friend constexpr fixed_point128 fmin(const fixed_point128 &x, const fixed_point128 &y) noexcept
Returns the minimum between x and y.
constexpr fixed_point128 & operator++() noexcept
Prefix ++ operation (++a)
friend constexpr bool operator==(const fixed_point128 &lhs, const T &rhs) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
constexpr fixed_point128 & operator&=(const T &rhs)
Bitwise AND=.
constexpr bool is_negative() const noexcept
Returns true if the value negative (smaller than zero)
constexpr fixed_point128(const fixed_point128< I2 > &rhs) noexcept
cross-template Copy constructor, can be used between two different fixed_point128 templates A value t...
friend constexpr bool operator>(const T &lhs, const fixed_point128 &rhs) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
constexpr bool operator!() const noexcept
Logical not (!). Opposite of operator bool.
friend constexpr fixed_point128 trunc(const fixed_point128 &x) noexcept
Rounds towards zero.
friend constexpr fixed_point128 operator&(fixed_point128 lhs, const T &rhs)
Performs bitwise AND (&)
friend fixed_point128 sinh(const fixed_point128 &x) noexcept
Calculate the hyperbolic sine function Use the exponent function which produces more accurate results...
friend fixed_point128 cos1(const fixed_point128 &x) noexcept
Calculate the cosine function over a limited range [-0.5pi, 0.5pi] Using the Maclaurin series expansi...
constexpr fixed_point128() noexcept
Default constructor, creates an instance with a value of zero.
friend void _sincos_cordic(fixed_point128 x, fixed_point128 &sin_x, fixed_point128 &cos_x, bool apply_scale_factor) noexcept
Calculate Sine and Cosine using CORDIC using a limited range of [-pi/2, pi/2] 64 iterations,...
friend constexpr bool operator<=(const fixed_point128 &lhs, const fixed_point128 &rhs) noexcept
Return true this object is small or equal than the rhs.
static constexpr float_denorm_style has_denorm
static constexpr value_type min() noexcept
Smallest positive value, which is one unit in the last place.
static constexpr value_type denorm_min() noexcept
No value is subnormal, so this is the smallest positive one, the same as min().
static constexpr int min_exponent
2^(min_exponent-1) = 2^(I-127) is the smallest positive value, epsilon().
static FP128_SUPPRESS_DEPRECATED_END constexpr float_round_style round_style
Multiplication, division (by a fixed_point128 or an integer), the right shift and the narrowing conve...
static constexpr value_type signaling_NaN() noexcept
static constexpr value_type epsilon() noexcept
Spacing of the grid, the same at every magnitude.
static constexpr int max_exponent
2^(max_exponent-1) = 2^(I-1) is the largest power of two in range; max() is 2^I - epsilon().
static constexpr bool traps
Division by zero throws std::logic_error rather than producing a value.
static constexpr value_type round_error() noexcept
Largest rounding error of an operation in units in the last place, one half.
static constexpr int max_digits10
Significant decimal digits that tell every pair of neighbouring values apart.
static constexpr bool is_exact
Every representable value is exactly the number it stands for.
static constexpr bool is_modulo
+, - and * wrap around: they keep the low 128 bits of the two's complement result,...
static constexpr value_type quiet_NaN() noexcept
static constexpr value_type infinity() noexcept
static constexpr int digits10
Decimal digits that survive a round trip: floor(127 * log10(2)).
static constexpr int digits
Value bits. One of the 128 is the sign, so 127 of them carry magnitude.
static constexpr value_type lowest() noexcept
Most negative value, exactly -2^I. Two's complement makes the range asymmetric, so this one has no po...
static FP128_SUPPRESS_DEPRECATED_BEGIN constexpr bool has_denorm_loss
static constexpr value_type max() noexcept
Largest value, every bit below the sign set: 2^I - epsilon().
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_ADD_ROUND_BIT(l, h, round_up)
Adds a rounding bit into a 128 bit value held as two QWORDs, as l and h are named there.
#define FP128_FLOAT_DIVIDE_BY_ZERO_EXCEPTION
#define FP128_GET_BIT(x, n)
#define FP128_INLINE
#define FP128_GET_BITS(x, b, count)
#define FP128_MAX_VALUE_64(x)
#define FP128_FORCE_INLINE
Marks a function the compiler must inline rather than merely may.
#define FP128_USE_RECIPROCAL_FOR_DIVISION
Selects how fixed_point128 divides by a value that is neither a power of two nor an integer.
basic_big_uint< 560 > big_uint
The big integer every conversion uses, 560 limbs or 17920 bits.
Everything the library provides.
constexpr void shift_right128_inplace_safe(uint64_t &l, uint64_t &h, int shift) noexcept
Right shift of an unsigned 128 bit integer (inplace), rounded to nearest with a tie going up.
void fact_reciprocal(int x, fixed_point128< I > &res) noexcept
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 void shift_right128_inplace(uint64_t &l, uint64_t &h, int shift) noexcept
Right shift a 128 bit unsigned integer (inplace). Limited range, inplace and no parameter checks (che...
static bool div_64bit(uint64_t *q, uint64_t *r, const uint64_t *u, uint64_t v, int64_t m) noexcept
64 bit words unsigned divide function. Variation of the code from the book Hacker's Delight.
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 void twos_complement128(uint64_t &l, uint64_t &h) noexcept
converts a 128 integer to negative via 2's complement.
uint64_t lzcnt128(const fixed_point128< I > &x) noexcept
constexpr uint64_t shift_left128(uint64_t l, uint64_t h) noexcept
Left shift a 128 bit integer. When shift is a compile time constant, this function generates optimal ...
int32_t ilogb(const fixed_point128< I > &x) noexcept
constexpr void shift_left128_inplace(uint64_t &l, uint64_t &h, int shift) noexcept
Left shift a 128 bit integer (inplace). Limited range, inplace and no parameter checks (checked via a...
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,...
static constexpr int32_t flt_frac_bits
Mantissa bit count of an IEEE 754 float.
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.
bool Divide256By128(uint64_t *q, uint64_t *r, const uint64_t *u, const uint64_t *v) noexcept
Divides a 256 bit numerator by a 128 bit divisor: the one call of div_128bit() in this header.
fixed_point128< I > fmax(const fixed_point128< I > &x, const fixed_point128< I > &y) noexcept
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
fixed_point128< I > modf(const fixed_point128< I > &x, fixed_point128< I > *iptr) noexcept
fixed_point128< I > tan(fixed_point128< I > x) noexcept
constexpr uint64_t fp128_trig_series_table[][2]
1 / (n(n+1)) for n = 1..40, with 125 fraction bits rounded to nearest, {high, low}...
fixed_point128< I > logb(fixed_point128< I > x) noexcept
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
fixed_point128< I > fdim(const fixed_point128< I > &x, const fixed_point128< I > &y) noexcept
constexpr void shift_right128_inplace_safe_signed(uint64_t &l, uint64_t &h, int shift) noexcept
Arithmetic right shift of a 128 bit two's complement value (inplace), rounded to nearest with a tie g...
fixed_point128< I > round(const fixed_point128< I > &x) noexcept
fixed_point128< I > log1p(fixed_point128< I > x) noexcept
fixed_point128< I > sin(fixed_point128< I > x) noexcept
fixed_point128< I > copysign(const fixed_point128< I > &x, const fixed_point128< I > &y) noexcept
fixed_point128< I > log10(fixed_point128< I > x) noexcept
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
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.
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
fixed_point128< I > tanh(const fixed_point128< I > &x) noexcept
fixed_point128< I > fabs(const fixed_point128< I > &x) noexcept
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...
constexpr uint64_t log2_value_table[][2]
-log2 of the matching log2_recip_table entry, as a 128 bit fraction.
fixed_point128< I > acosh(const fixed_point128< I > &x) noexcept
fixed_point128< I > trunc(const fixed_point128< I > &x) noexcept
fixed_point128< I > reciprocal(const fixed_point128< I > &x) noexcept
constexpr uint64_t popcnt128(uint64_t l, uint64_t h) noexcept
Counts the number of 1 bits (population count) in a 128-bit unsigned integer.
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
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).
static constexpr double make(uint64_t s, uint64_t e, uint64_t f) noexcept
Assembles a double out of its three fields.
constexpr uint64_t e() const noexcept
Biased exponent bits.
static constexpr float make(uint32_t s, uint32_t e, uint32_t f) noexcept
Assembles a float out of its three fields, see Double::make().
constexpr auto parse(basic_format_parse_context< char > &context)
char align
One of < > ^, or zero when none was given.
bool zero_pad
The 0 flag: pad with zeros after the sign.
char fill
Character the padding is made of.
auto format(const fp128::fixed_point128< I > &value, FormatContext &context) const
size_t operator()(const fp128::fixed_point128< I > &value) const noexcept