fixed_point128 1.0.1.0
128 bit integer, fixed point and floating point arithmetic for C++20
Loading...
Searching...
No Matches
fp128 Namespace Reference

Everything the library provides. More...

Namespaces

namespace  detail

Classes

struct  Double
 Bit level view of an IEEE 754 double-precision value. More...
class  fixed_point128
 Google test class (friend). More...
struct  Float
 Bit level view of an IEEE 754 single-precision value. More...
class  float128
 128 bit floating point class. More...
class  int128_base
 128 bit integer class, signed or unsigned depending on the template parameter. More...

Typedefs

using int128_t = int128_base<true>
 128 bit signed integer type.
using uint128_t = int128_base<false>
 128 bit unsigned integer type.

Functions

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.
template<int32_t I>
std::ostream & operator<< (std::ostream &os, const fixed_point128< I > &value)
 Writes a fixed_point128 to a stream, honouring its width, fill and adjustment.
template<int32_t I>
std::istream & operator>> (std::istream &is, fixed_point128< I > &value)
 Reads a fixed_point128 from a stream, the way the builtin arithmetic extractors do.
std::from_chars_result from_chars (const char *first, const char *last, float128 &value)
 Reads a decimal string into a float128. Defined below, declared here because the constructor from a string delegates to it.
std::from_chars_result from_chars (const char *first, const char *last, float128 &value, std::chars_format fmt)
 Reads a decimal or hexadecimal string into a float128. Defined below.
float128 operator""_f128 (const char *literal)
 User-defined literal for constructing float128 from a string.
std::string to_string (const float128 &value)
 The shortest decimal string that reads back as this exact value.
std::to_chars_result to_chars (char *first, char *last, const float128 &value, std::chars_format fmt, int precision)
 Converts a float128 to text, in the shape of std::to_chars.
std::to_chars_result to_chars (char *first, char *last, const float128 &value, std::chars_format fmt)
 Converts a float128 to text with the default precision for the layout.
std::to_chars_result to_chars (char *first, char *last, const float128 &value)
 Converts a float128 to the shortest text that reads back as the same value.
std::ostream & operator<< (std::ostream &os, const float128 &value)
 Writes a float128 to a stream, honouring its formatting state.
std::istream & operator>> (std::istream &is, float128 &value)
 Reads a float128 from a stream.
static errno_t strnlwr (char *dest, const char *src, size_t n) noexcept
 Copy a string to lowercase, up to n characters.
template<typename T>
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 = array_length(a); // returns 5 at build time.
constexpr uint64_t shift_right64_round (uint64_t x, int shift) noexcept
 Right-shift a 64-bit value with rounding.
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 (checked via assert in debug builds)
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 assert in debug builds)
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.
constexpr uint64_t shift_right128_wide_signed_low (uint64_t l, uint64_t h, int shift) noexcept
 The shifts by 64 bits or more of shift_right128_inplace_safe_signed().
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 going away from zero.
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.
template<int shift>
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 code for all shift values.
template<int shift>
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 code for all shift values.
constexpr uint64_t shift_right128 (uint64_t l, uint64_t h, int shift) noexcept
 Right shift a 128 bit integer.
constexpr uint64_t shift_right128_round (uint64_t l, uint64_t h, int shift) noexcept
 Right shift a 128 bit integer with rounding.
constexpr uint64_t shift_left128 (uint64_t l, uint64_t h, int shift) noexcept
 Left shift a 128 bit integer.
constexpr void twos_complement128 (uint64_t &l, uint64_t &h) noexcept
 converts a 128 integer to negative via 2's complement.
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.
template<int64_t m>
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, 64 bit limbs.
static bool div_128bit (uint64_t *q, uint64_t *r, const uint64_t *u, const uint64_t *v, int64_t m) noexcept
 div_128bit() with the word count of the numerator chosen at run time.
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.
constexpr uint64_t lzcnt128 (uint64_t l, uint64_t h) noexcept
 Left zero count 128 bit.
constexpr uint64_t log2 (uint64_t l, uint64_t h) noexcept
 Calculates the Log base 2 of x: log2(x) Rounding is always towards zero so the maximum error is close to 1.
constexpr uint64_t log2 (uint64_t x) noexcept
 Calculates the Log base 2 of x: log2(x) Rounding is always towards zero so the maximum error is close to 1.
constexpr uint32_t log2 (uint32_t x) noexcept
 Calculates the Log base 2 of x: log2(x) Rounding is always towards zero so the maximum error is close to 1.
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.
template<bool IsSigned>
std::ostream & operator<< (std::ostream &os, const int128_base< IsSigned > &value)
 Writes a 128 bit integer to a stream, honouring its width, fill and adjustment.
template<bool IsSigned>
std::istream & operator>> (std::istream &is, int128_base< IsSigned > &value)
 Reads a 128 bit integer from a stream, the way the builtin integer extractors do.
int128_t operator""_int128 (const char *literal)
 User-defined literal for constructing int128_t from a string.
uint128_t operator""_uint128 (const char *literal)
 User-defined literal for constructing uint128_t from a string.
CRT-Style Math Functions (Forward Declarations)

Free functions providing standard math library equivalents for float128.

template<int32_t I>
fixed_point128< I > fabs (const fixed_point128< I > &x)
template<int32_t I>
fixed_point128< I > floor (const fixed_point128< I > &x)
template<int32_t I>
fixed_point128< I > ceil (const fixed_point128< I > &x)
template<int32_t I>
fixed_point128< I > trunc (const fixed_point128< I > &x)
template<int32_t I>
fixed_point128< I > round (const fixed_point128< I > &x)
template<int32_t I>
int32_t ilogb (const fixed_point128< I > &x)
template<int32_t I>
fixed_point128< I > copysign (const fixed_point128< I > &x, const fixed_point128< I > &y)
template<int32_t I>
fixed_point128< I > fmod (const fixed_point128< I > &x, const fixed_point128< I > &y)
template<int32_t I>
fixed_point128< I > modf (const fixed_point128< I > &x, fixed_point128< I > *iptr)
template<int32_t I>
fixed_point128< I > fdim (const fixed_point128< I > &x, const fixed_point128< I > &y)
template<int32_t I>
fixed_point128< I > fmin (const fixed_point128< I > &x, const fixed_point128< I > &y)
template<int32_t I>
fixed_point128< I > fmax (const fixed_point128< I > &x, const fixed_point128< I > &y)
template<int32_t I>
fixed_point128< I > hypot (const fixed_point128< I > &x, const fixed_point128< I > &y)
template<int32_t I>
fixed_point128< I > sqrt (const fixed_point128< I > &x, uint32_t iterations=3)
template<int32_t I>
fixed_point128< I > sin (fixed_point128< I > x)
template<int32_t I>
fixed_point128< I > asin (fixed_point128< I > x)
template<int32_t I>
fixed_point128< I > cos (fixed_point128< I > x)
template<int32_t I>
fixed_point128< I > acos (fixed_point128< I > x)
template<int32_t I>
fixed_point128< I > tan (fixed_point128< I > x)
template<int32_t I>
fixed_point128< I > atan (fixed_point128< I > x)
template<int32_t I>
fixed_point128< I > atan2 (fixed_point128< I > y, fixed_point128< I > x)
template<int32_t I>
fixed_point128< I > sinh (const fixed_point128< I > &x)
template<int32_t I>
fixed_point128< I > asinh (const fixed_point128< I > &x)
template<int32_t I>
fixed_point128< I > cosh (const fixed_point128< I > &x)
template<int32_t I>
fixed_point128< I > acosh (const fixed_point128< I > &x)
template<int32_t I>
fixed_point128< I > tanh (const fixed_point128< I > &x)
template<int32_t I>
fixed_point128< I > atanh (const fixed_point128< I > &x)
template<int32_t I>
fixed_point128< I > exp (const fixed_point128< I > &x)
template<int32_t I>
fixed_point128< I > exp2 (const fixed_point128< I > &x)
template<int32_t I>
fixed_point128< I > expm1 (const fixed_point128< I > &x)
template<int32_t I>
fixed_point128< I > pow (const fixed_point128< I > &x, const fixed_point128< I > &y)
template<int32_t I>
fixed_point128< I > log (fixed_point128< I > x)
template<int32_t I>
fixed_point128< I > log2 (fixed_point128< I > x)
template<int32_t I>
fixed_point128< I > log10 (fixed_point128< I > x)
template<int32_t I>
fixed_point128< I > logb (fixed_point128< I > x)
template<int32_t I>
fixed_point128< I > log1p (fixed_point128< I > x)
constexpr float128 fabs (const float128 &x)
constexpr float128 floor (const float128 &x)
constexpr float128 ceil (const float128 &x)
constexpr float128 trunc (const float128 &x)
constexpr float128 round (const float128 &x)
constexpr int64_t llrint (const float128 &x)
constexpr int64_t llround (const float128 &x)
constexpr int32_t lrint (const float128 &x)
constexpr int32_t lround (const float128 &x)
constexpr int32_t ilogb (const float128 &x)
constexpr float128 copysign (const float128 &x, const float128 &y)
float128 fmod (const float128 &x, const float128 &y)
constexpr float128 modf (const float128 &x, float128 *iptr)
constexpr float128 fdim (const float128 &x, const float128 &y)
constexpr float128 fmin (const float128 &x, const float128 &y)
constexpr float128 fmax (const float128 &x, const float128 &y)
constexpr float128 fma (float128 x, float128 y, float128 z)
float128 hypot (const float128 &x, const float128 &y)
float128 cbrt (const float128 x, uint32_t iterations=2)
float128 sqrt (const float128 &x, uint32_t iterations=3)
float128 erf (float128 x)
float128 erfc (float128 x)
float128 sin (float128 x)
float128 asin (float128 x)
float128 cos (float128 x)
float128 acos (float128 x)
float128 tan (float128 x)
float128 atan (float128 x)
float128 atan2 (float128 y, float128 x)
float128 sinh (float128 x)
float128 asinh (float128 x)
float128 cosh (float128 x)
float128 acosh (float128 x)
float128 tanh (float128 x)
float128 atanh (float128 x)
float128 exp (const float128 &x)
float128 exp2 (const float128 &x)
float128 expm1 (const float128 &x)
float128 pow (const float128 &x, const float128 &y)
float128 pow (const float128 &x, int32_t y)
float128 log (float128 x)
float128 log2 (float128 x)
float128 log10 (float128 x)
float128 logb (float128 x)
float128 log1p (float128 x)
constexpr float128 frexp (float128 x, int *expptr)
constexpr float128 ldexp (float128 x, int exp)
constexpr bool isfinite (const float128 &x)
constexpr bool signbit (const float128 &x)
constexpr bool isnormal (const float128 &x)
constexpr int fpclassify (const float128 &x)
constexpr bool isunordered (const float128 &x, const float128 &y)
constexpr bool isgreater (const float128 &x, const float128 &y)
constexpr bool isgreaterequal (const float128 &x, const float128 &y)
constexpr bool isless (const float128 &x, const float128 &y)
constexpr bool islessequal (const float128 &x, const float128 &y)
constexpr bool islessgreater (const float128 &x, const float128 &y)
constexpr float128 rint (const float128 &x)
constexpr float128 nearbyint (const float128 &x)
constexpr float128 scalbn (const float128 &x, int n)
constexpr float128 scalbln (const float128 &x, long n)
constexpr float128 nextafter (const float128 &x, const float128 &y)
constexpr float128 nexttoward (const float128 &x, const float128 &y)
float128 remainder (const float128 &x, const float128 &y)
float128 remquo (const float128 &x, const float128 &y, int *quo)
float128 hypot (const float128 &x, const float128 &y, const float128 &z)
float128 lgamma (float128 x)
float128 tgamma (float128 x)
constexpr float128 abs (const float128 &x)
constexpr bool totalorder (const float128 &x, const float128 &y)
constexpr bool totalordermag (const float128 &x, const float128 &y)
constexpr float128 fmaxmag (const float128 &x, const float128 &y)
constexpr float128 fminmag (const float128 &x, const float128 &y)
constexpr bool iscanonical (const float128 &x)
constexpr bool issignaling (const float128 &x)
constexpr bool issubnormal (const float128 &x)
constexpr bool iszero (const float128 &x)
float128 nan (const char *payload)
Non-CRT Utility Functions (Forward Declarations)
template<int32_t I>
uint64_t lzcnt128 (const fixed_point128< I > &x)
template<int32_t I>
fixed_point128< I > reciprocal (const fixed_point128< I > &x)
template<int32_t I>
void fact_reciprocal (int x, fixed_point128< I > &res)
float128 reciprocal (const float128 &x)
void fact_reciprocal (int x, float128 &res)
float128 double_factorial (int x)
Floating point environment

IEEE 754-2008 asks two things of a binary format beyond its arithmetic. Clause 4 requires four rounding-direction attributes the program can choose between: to nearest with ties to even, the default, and towards zero, towards positive infinity and towards negative infinity. Clause 7 requires five exceptions - invalid operation, division by zero, overflow, underflow and inexact - each reported by a status flag that stays raised until the program lowers it.

float128 provides both, as a per thread environment of its own that is entirely separate from the hardware one <cfenv> controls: setting the rounding direction here does not change how double rounds, and an exception raised by a float128 operation shows up here and not in fetestexcept().

The environment is opt in. It exists only when every translation unit that includes this header is compiled with FP128_IEEE_ENV defined. Without it, which is the default, every operation rounds to nearest with ties to even, no flag is ever raised, and the code that would maintain the environment compiles away, leaving the arithmetic exactly as fast as it was before the environment existed. The functions below are still declared, so the same source builds either way: they report the fixed default and refuse to change it.

The macro changes the definition of inline functions, so it must have the same value in every translation unit of a program. Mixing the two violates the one definition rule.

The rounding directions and exception flags are named with the FE_ constants of <cfenv>, so the calls read the way their hardware counterparts do:

fp128::fesetround(FE_UPWARD);
float128 bound = a / b; // rounded towards +inf
if (fp128::fetestexcept(FE_INEXACT)) { ... } // the quotient was not exact
128 bit floating point class.
Definition float128.h:672
int fetestexcept(int excepts) noexcept
Tests float128 exception flags (IEEE 754 testFlags).
Definition float128.h:452
int fesetround(int round) noexcept
Selects the rounding direction float128 arithmetic uses on the calling thread.
Definition float128.h:427

The calls have to be qualified: their arguments are plain integers, so argument dependent lookup cannot tell them from the <cfenv> functions of the same name.

int fegetround () noexcept
 The rounding direction float128 arithmetic uses on the calling thread.
int fesetround (int round) noexcept
 Selects the rounding direction float128 arithmetic uses on the calling thread.
int fetestexcept (int excepts) noexcept
 Tests float128 exception flags (IEEE 754 testFlags).
int feclearexcept (int excepts) noexcept
 Lowers float128 exception flags (IEEE 754 lowerFlags).
int feraiseexcept (int excepts) noexcept
 Raises float128 exception flags (IEEE 754 raiseFlags).
int fegetexceptflag (std::fexcept_t *flagp, int excepts) noexcept
 Saves the state of float128 exception flags (IEEE 754 saveAllFlags).
int fesetexceptflag (const std::fexcept_t *flagp, int excepts) noexcept
 Restores float128 exception flags saved by fegetexceptflag (IEEE 754 restoreFlags).

Variables

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}.
constexpr uint64_t log2_recip_table [][2]
 1/(1 + j/64) as a 128 bit fraction, the reciprocals fixed_point128::log2() reduces with.
constexpr uint64_t log2_value_table [][2]
 -log2 of the matching log2_recip_table entry, as a 128 bit fraction.
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)*ln2).
constexpr int32_t log2_reduction_bits = 6
 Bits of argument reduction fixed_point128::log2() applies; log2_recip_table has 2^this entries.
Library Version

The FP128_VERSION_* macros as constants, for code that reports the version rather than branching on it at preprocessing time.

static constexpr int32_t version_major = FP128_VERSION_MAJOR
 Breaking changes to the public interface.
static constexpr int32_t version_minor = FP128_VERSION_MINOR
 Backwards compatible additions.
static constexpr int32_t version_patch = FP128_VERSION_PATCH
 Fixes that change neither.
static constexpr int32_t version_build = FP128_VERSION_BUILD
 Rebuild of an unchanged source tree.
static constexpr int32_t version = FP128_VERSION
 All four packed into one comparable integer.
static constexpr const char * version_string = FP128_VERSION_STRING
 Dotted form, e.g. "0.9.0.0".
IEEE 754 Layout Constants
static constexpr int32_t flt_frac_bits = 23
 Mantissa bit count of an IEEE 754 float.
static constexpr int32_t flt_exp_bits = 8
 Exponent bit count of an IEEE 754 float.
static constexpr int32_t dbl_frac_bits = 52
 Mantissa bit count of an IEEE 754 double.
static constexpr int32_t dbl_exp_bits = 11
 Exponent bit count of an IEEE 754 double.

Detailed Description

Everything the library provides.

The namespace holds four value types and the free functions that operate on them:

Each of them supports the operators, the <cmath> functions, the std::numeric_limits, std::hash and std::formatter specializations, and the stream insertion and extraction that the corresponding builtin type does, so they can stand in for one in generic code.

The rest of the namespace is the machinery those types are built from - 128 bit shifts, multiply, divide and bit counting over pairs of QWORDs - which is public because the types are header only and inline everything, not because a user is expected to call it.

Typedef Documentation

◆ int128_t

128 bit signed integer type.

An alias of the signed instantiation of fp128::int128_base, which holds the entire implementation. This type implements the standard operators a signed integer type has.
All of int128_t's methods are inline for maximum performance.

Implementation notes:

  • Values are stored in two's complement, so the bit patterns of the shared operations match the unsigned type exactly.
  • Overflow is handled silently, similar to builtin integer operations.
  • An int128_t object is not thread safe. Accessing a const object from multiple threads is safe.
  • int128_t is conditionally safe, 2 different non const objects can be accessed concurrently.
  • Only 64 bit builds are supported.
  • Being an alias rather than a distinct class, int128_t cannot be forward declared. Include this header instead.

Definition at line 76 of file int128_t.h.

◆ uint128_t

using fp128::uint128_t = int128_base<false>

128 bit unsigned integer type.

An alias of the unsigned instantiation of fp128::int128_base, which holds the entire implementation. This type implements the standard operators an unsigned integer type has.
All of uint128_t's methods are inline for maximum performance.

Implementation notes:

  • Overflow is handled silently, similar to builtin integer operations.
  • A uint128_t object is not thread safe. Accessing a const object from multiple threads is safe.
  • uint128_t is conditionally safe, 2 different non const objects can be accessed concurrently.
  • Only 64 bit builds are supported.
  • Being an alias rather than a distinct class, uint128_t cannot be forward declared. Include this header instead.

Definition at line 73 of file uint128_t.h.

Function Documentation

◆ fabs() [1/2]

template<int32_t I>
fixed_point128< I > fp128::fabs ( const fixed_point128< I > & x)
nodiscardnoexcept
Parameters
xInput value
Returns
A copy of x with the sign removed. lowest() has no positive counterpart and comes back unchanged, the same silent wrap the builtin integer types perform.

Definition at line 2720 of file fixed_point128.h.

◆ floor() [1/2]

template<int32_t I>
fixed_point128< I > fp128::floor ( const fixed_point128< I > & x)
nodiscardnoexcept
Parameters
xInput value
Returns
A fixed_point128 holding the integer value. Overflow is not reported.

Definition at line 2733 of file fixed_point128.h.

◆ ceil() [1/2]

template<int32_t I>
fixed_point128< I > fp128::ceil ( const fixed_point128< I > & x)
nodiscardnoexcept
Parameters
xInput value
Returns
A fixed_point128 holding the integer value. Overflow is not reported.

Definition at line 2745 of file fixed_point128.h.

◆ trunc() [1/2]

template<int32_t I>
fixed_point128< I > fp128::trunc ( const fixed_point128< I > & x)
nodiscardnoexcept
Parameters
xValue to truncate
Returns
Integer value, rounded towards zero.

Definition at line 2758 of file fixed_point128.h.

◆ round() [1/2]

template<int32_t I>
fixed_point128< I > fp128::round ( const fixed_point128< I > & x)
nodiscardnoexcept
Parameters
xValue to round
Returns
Integer value, rounded towards the nearest integer.

Definition at line 2769 of file fixed_point128.h.

◆ ilogb() [1/2]

template<int32_t I>
int32_t fp128::ilogb ( const fixed_point128< I > & x)
nodiscardnoexcept
Parameters
xThe specified value.
Returns
The exponent. FP_ILOGB0 for zero, which is what the C function returns for it.

Definition at line 2782 of file fixed_point128.h.

◆ copysign() [1/2]

template<int32_t I>
fixed_point128< I > fp128::copysign ( const fixed_point128< I > & x,
const fixed_point128< I > & y )
nodiscardnoexcept
Parameters
xThe value that's returned as the magnitude of the result.
yThe sign of the result.
Returns
The copysign functions return a floating-point value that combines the magnitude of x and the sign of y.

Definition at line 2792 of file fixed_point128.h.

◆ fmod() [1/2]

template<int32_t I>
fixed_point128< I > fp128::fmod ( const fixed_point128< I > & x,
const fixed_point128< I > & y )
nodiscard
Parameters
xNumerator
yDenominator
Returns
A fixed_point128 holding the modulo value.
Exceptions
std::logic_errorwhen y is zero. This type has no NaN to return instead.

Definition at line 2805 of file fixed_point128.h.

◆ modf() [1/2]

template<int32_t I>
fixed_point128< I > fp128::modf ( const fixed_point128< I > & x,
fixed_point128< I > * iptr )
nodiscardnoexcept
Parameters
xInput value
iptrPointer to fixed_point128 holding the integer part of x.
Returns
The fraction part of x. Undefined when iptr is nullptr.

Definition at line 2813 of file fixed_point128.h.

◆ fdim() [1/2]

template<int32_t I>
fixed_point128< I > fp128::fdim ( const fixed_point128< I > & x,
const fixed_point128< I > & y )
nodiscardnoexcept
Parameters
xFirst value
ySecond value
Returns
If x > y returns x - y. Otherwise zero.

Definition at line 2829 of file fixed_point128.h.

◆ fmin() [1/2]

template<int32_t I>
fixed_point128< I > fp128::fmin ( const fixed_point128< I > & x,
const fixed_point128< I > & y )
nodiscardnoexcept
Parameters
xFirst value
ySecond value
Returns
If x < y returns x. Otherwise y.

Definition at line 2839 of file fixed_point128.h.

◆ fmax() [1/2]

template<int32_t I>
fixed_point128< I > fp128::fmax ( const fixed_point128< I > & x,
const fixed_point128< I > & y )
nodiscardnoexcept
Parameters
xFirst value
ySecond value
Returns
If x > y returns x. Otherwise y.

Definition at line 2846 of file fixed_point128.h.

◆ hypot() [1/3]

template<int32_t I>
fixed_point128< I > fp128::hypot ( const fixed_point128< I > & x,
const fixed_point128< I > & y )
nodiscardnoexcept

Correctly rounded, and free of intermediate overflow: hypot(x, y) * 2^F is the square root of the sum of the squared raw values, which is formed as an exact 256 bit integer. Spelled as sqrt(sqr(x) + sqr(y)) instead, it overflowed as soon as |x| or |y| reached 2^(I/2), long before the result itself leaves the range.

Parameters
xFirst value
ySecond value
Returns
sqrt(x^2 + y^2), rounded to nearest. A result of 2^I or more wraps, like any overflow.

Definition at line 2859 of file fixed_point128.h.

◆ sqrt() [1/2]

template<int32_t I>
fixed_point128< I > fp128::sqrt ( const fixed_point128< I > & x,
uint32_t iterations = 3 )
nodiscardnoexcept

sqrt(x) * 2^F is the square root of the raw value scaled up by another F bits, which makes it the integer square root of a 256 bit number: RoundedSqrt256() computes it rounded to nearest, so the result is the representable value closest to the exact root at every I and every magnitude. (A tie between two representable values cannot occur.)

Parameters
xValue to calculate the root of
iterationsIgnored. It used to set the step count of an iterative refinement, which lost up to half of the integer bits for a large argument; it is kept so that existing calls still compile.
Returns
Square root of (x), zero when x <= 0.

Definition at line 2915 of file fixed_point128.h.

◆ sin() [1/2]

template<int32_t I>
fixed_point128< I > fp128::sin ( fixed_point128< I > x)
nodiscardnoexcept

Accuracy, measured against mpmath at I = 1, 2, 4, 16, 32, 62 and 63 where the function exists: within 2.5 ulp for |x| < 4 (1.4 ulp from I = 16 up). Beyond that the reduction x - n * pi/2 adds n times the rounding error of pi/2 in this instantiation, at most |x| / 3 ulp more: 320 ulp for |x| near 1000 at I = 32.

Parameters
xvalue in Radians
Returns
Sine of x

Definition at line 3224 of file fixed_point128.h.

◆ asin() [1/2]

template<int32_t I>
fixed_point128< I > fp128::asin ( fixed_point128< I > x)
nodiscardnoexcept

Accuracy, measured against mpmath at I = 4, 16, 32, 62 and 63: within 3.5 ulp.

Parameters
xvalue in radians in the range [-1,1]
Returns
Inverse sine of x, zero outside [-1,1]

Definition at line 3257 of file fixed_point128.h.

◆ cos() [1/2]

template<int32_t I>
fixed_point128< I > fp128::cos ( fixed_point128< I > x)
nodiscardnoexcept

Accuracy, measured against mpmath at I = 1, 2, 4, 16, 32, 62 and 63 where the function exists: within 1.8 ulp for |x| < 4 (1.3 ulp from I = 16 up), plus at most |x| / 3 ulp of argument reduction beyond, see sin().

Parameters
xvalue in Radians
Returns
Cosine of x

Definition at line 3283 of file fixed_point128.h.

◆ acos() [1/2]

template<int32_t I>
fixed_point128< I > fp128::acos ( fixed_point128< I > x)
nodiscardnoexcept

Accuracy, measured against mpmath at I = 4, 16, 32, 62 and 63: within 4 ulp.

Parameters
xvalue in radians in the range [-1,1]
Returns
Inverse cosine of x, zero outside [-1,1]

Definition at line 3314 of file fixed_point128.h.

◆ tan() [1/2]

template<int32_t I>
fixed_point128< I > fp128::tan ( fixed_point128< I > x)
nodiscardnoexcept

The error of the cosine is divided by the cosine itself, so it grows towards the poles. Measured against mpmath for |x| < 4 at I = 4, 16, 32, 62 and 63: within 45 * max(1, |tan(x)|) ulp.

Parameters
xvalue
Returns
Tangent of x. Zero at the poles (odd multiples of pi/2), where the true value is unbounded and the cosine comes out exactly zero.

Definition at line 3339 of file fixed_point128.h.

◆ atan() [1/2]

template<int32_t I>
fixed_point128< I > fp128::atan ( fixed_point128< I > x)
nodiscardnoexcept
Parameters
xvalue
Returns
Arctangent of x

Definition at line 3365 of file fixed_point128.h.

◆ atan2() [1/2]

template<int32_t I>
fixed_point128< I > fp128::atan2 ( fixed_point128< I > y,
fixed_point128< I > x )
nodiscardnoexcept
Parameters
yvalue
xvalue
Returns
Arctangent of y / x in the range [-pi, pi]

Definition at line 3414 of file fixed_point128.h.

◆ sinh() [1/2]

template<int32_t I>
fixed_point128< I > fp128::sinh ( const fixed_point128< I > & x)
nodiscardnoexcept
Parameters
xvalue
Returns
Sine of x

Definition at line 3460 of file fixed_point128.h.

◆ asinh() [1/2]

template<int32_t I>
fixed_point128< I > fp128::asinh ( const fixed_point128< I > & x)
nodiscardnoexcept
Parameters
xvalue
Returns
Inverse hyperbolic sine of x

Definition at line 3503 of file fixed_point128.h.

◆ cosh() [1/2]

template<int32_t I>
fixed_point128< I > fp128::cosh ( const fixed_point128< I > & x)
nodiscardnoexcept
Parameters
xvalue
Returns
Hyperbolic cosine of x

Definition at line 3521 of file fixed_point128.h.

◆ acosh() [1/2]

template<int32_t I>
fixed_point128< I > fp128::acosh ( const fixed_point128< I > & x)
nodiscardnoexcept
Parameters
xvalue in the range [1, inf]
Returns
Inverse hyperbolic cosine of x

Definition at line 3559 of file fixed_point128.h.

◆ tanh() [1/2]

template<int32_t I>
fixed_point128< I > fp128::tanh ( const fixed_point128< I > & x)
nodiscardnoexcept
Parameters
xvalue
Returns
hyperbolic tangent of x

Definition at line 3579 of file fixed_point128.h.

◆ atanh() [1/2]

template<int32_t I>
fixed_point128< I > fp128::atanh ( const fixed_point128< I > & x)
nodiscardnoexcept
Parameters
xvalue in the range (-1, 1)
Returns
Inverse hyperbolic tangent of x, zero outside (-1, 1). A result beyond the range of the instantiation, which only a narrow one can meet, wraps like any overflow.

Definition at line 3612 of file fixed_point128.h.

◆ exp() [1/2]

template<int32_t I>
fixed_point128< I > fp128::exp ( const fixed_point128< I > & x)
nodiscardnoexcept
                                  x

The Maclaurin series will quickly overflow as x's power increases rapidly.

                x   ix   fx

Using the equality e = e * e Where ix is the integer part of x and fx is the fraction part. ix is computed via multiplications which won't overflow if the result value can be held. fx is computed via Maclaurin series expansion, but since fx < 1, it won't overflow. A negative x works with 1/e and the alternating series of e^-fx, so it never forms e^|x|.

Accuracy, measured against mpmath at I = 1, 2, 4, 16, 32, 62 and 63 where the function exists: within 6.2 * max(1, e^x) ulp. The argument itself is only known to half an ulp, which alone moves a large result by e^x / 2 ulp.

Parameters
xA number specifying a power.
Returns
Exponent of x

Definition at line 3645 of file fixed_point128.h.

◆ exp2() [1/2]

template<int32_t I>
fixed_point128< I > fp128::exp2 ( const fixed_point128< I > & x)
nodiscardnoexcept
Parameters
xExponent value
Returns
2^x

Definition at line 3711 of file fixed_point128.h.

◆ expm1() [1/2]

template<int32_t I>
fixed_point128< I > fp128::expm1 ( const fixed_point128< I > & x)
nodiscardnoexcept
Parameters
xA number specifying a power.
Returns
Exponent of x

Definition at line 3699 of file fixed_point128.h.

◆ pow() [1/3]

template<int32_t I>
fixed_point128< I > fp128::pow ( const fixed_point128< I > & x,
const fixed_point128< I > & y )
nodiscardnoexcept
Parameters
xBase value, must be positive
yExponent value
Returns
x^y, one when x is one, zero when x is negative, and for x = 0 one when y = 0 and zero otherwise

Definition at line 3732 of file fixed_point128.h.

◆ log() [1/2]

template<int32_t I>
fixed_point128< I > fp128::log ( fixed_point128< I > x)
nodiscardnoexcept
Parameters
xThe number to perform log on.
Returns
log(x)
Exceptions
std::domain_errorwhen x is zero or negative.

Definition at line 3812 of file fixed_point128.h.

◆ log2() [1/5]

template<int32_t I>
fixed_point128< I > fp128::log2 ( fixed_point128< I > x)
nodiscardnoexcept
Parameters
xThe number to perform log2 on.
Returns
log2(x)

Definition at line 3767 of file fixed_point128.h.

◆ log10() [1/2]

template<int32_t I>
fixed_point128< I > fp128::log10 ( fixed_point128< I > x)
nodiscardnoexcept
Parameters
xThe number to perform log on.
Returns
log10(x)

Definition at line 3840 of file fixed_point128.h.

◆ logb() [1/2]

template<int32_t I>
fixed_point128< I > fp128::logb ( fixed_point128< I > x)
nodiscardnoexcept
Parameters
xThe number to perform log on.
Returns
logb(x)
Exceptions
std::domain_errorwhen x is zero. The C function returns minus infinity for it, which this type cannot represent.

Definition at line 3862 of file fixed_point128.h.

◆ log1p() [1/2]

template<int32_t I>
fixed_point128< I > fp128::log1p ( fixed_point128< I > x)
nodiscardnoexcept
Parameters
xThe number to perform log on.
Returns
log1p(x)
Exceptions
std::domain_errorwhen x is -1 or below.

Definition at line 3832 of file fixed_point128.h.

◆ lzcnt128() [1/2]

template<int32_t I>
uint64_t fp128::lzcnt128 ( const fixed_point128< I > & x)
nodiscardnoexcept
Parameters
xinput value.
Returns
lzc (uint32_t) of th result.

Definition at line 2895 of file fixed_point128.h.

◆ reciprocal() [1/2]

template<int32_t I>
fixed_point128< I > fp128::reciprocal ( const fixed_point128< I > & x)
nodiscardnoexcept

Correctly rounded: the quotient comes from the same long division operator/=() uses, rounded to nearest with a tie going away from zero. The division is the faster of the two since div_128bit, and the Newton refinement of a double estimate this replaced lost accuracy as 1 / x grew - tens of thousands of ulp at fixed_point128<16>. It is called directly rather than through operator/=(), which divides by multiplying with this function when FP128_USE_RECIPROCAL_FOR_DIVISION is set.

Parameters
xInput value
Returns
1 / x. Zero when x is zero or when 1 / x does not fit the range [-2^I, 2^I), that is for |x| < 2^-I and for x == 2^-I; x == -2^-I gives lowest().

Definition at line 3006 of file fixed_point128.h.

◆ fact_reciprocal() [1/2]

template<int32_t I>
void fp128::fact_reciprocal ( int x,
fixed_point128< I > & res )
noexcept
Parameters
xInput value
resResult of the function

Definition at line 2945 of file fixed_point128.h.

◆ Divide256By128()

bool fp128::Divide256By128 ( uint64_t * q,
uint64_t * r,
const uint64_t * u,
const uint64_t * v )
inlinenodiscardnoexcept

Divides a 256 bit numerator by a 128 bit divisor: the one call of div_128bit() in this header.

The long division, the remainder and the integer square root of fixed_point128 all divide by a divisor that needs both QWORDs, and all of them come through here. The word count is fixed at four by the template argument of div_128bit<4>(), so its loops are unrolled for this shape whether the compiler inlines it or not. That used to depend on inlining: with the count an ordinary argument and callers in int128_shared.h and float128.h sharing one out of line copy, clang++ compiled a generic division and the long division here lost 15%.

Parameters
q(output) Quotient, three words, q[0] lowest.
r(output, optional) Remainder, two words. Can be nullptr.
uNumerator, four words, u[0] lowest.
vDivisor, two words; v[1] must not be zero.
Returns
true on success, false when v[1] is zero or a pointer is null.

Definition at line 160 of file fixed_point128.h.

◆ operator<<() [1/3]

template<int32_t I>
std::ostream & fp128::operator<< ( std::ostream & os,
const fixed_point128< I > & value )
inline

Writes a fixed_point128 to a stream, honouring its width, fill and adjustment.

Template Parameters
IInteger bit count of the type

Definition at line 3879 of file fixed_point128.h.

◆ operator>>() [1/3]

template<int32_t I>
std::istream & fp128::operator>> ( std::istream & is,
fixed_point128< I > & value )
inline

Reads a fixed_point128 from a stream, the way the builtin arithmetic extractors do.

Reads what the constructor from a string reads - an optional sign, digits, an optional point and more digits - correctly rounded to the grid, and stops at the first character that is not part of it, leaving it in the stream: "2.5,3" gives 2.5 and leaves ",3".

Failure sets failbit: no digits at all stores zero, and a value outside [lowest(), max()] stores the nearer of the two. Leading white space is skipped unless skipws is off. This used to read a whole white space delimited token through the string constructor, which never failed: "xyz" read as zero and an overflow wrapped silently.

Template Parameters
IInteger bit count of the type

Definition at line 3913 of file fixed_point128.h.

◆ from_chars() [1/2]

std::from_chars_result fp128::from_chars ( const char * first,
const char * last,
float128 & value )
inline

Reads a decimal string into a float128. Defined below, declared here because the constructor from a string delegates to it.

Converts text to a float128, in the shape of std::from_chars.

Reads the longest prefix of [first, last) that forms a number: an optional sign, decimal digits with an optional point and an optional exponent, or one of inf, infinity, nan, nan(payload) and snan. The result is the representable value nearest the one the text names, rounded once in the current rounding direction - including when it is subnormal, where fewer than 113 bits are kept.

That holds for any number of digits. The first 40 significant ones settle the rounding unless the value lies within one unit of the fortieth digit of a point halfway between two binary128 values; only then are all of them read, up to the 11700 that decide any case, which costs a few milliseconds for an input that long. Digits past the fortieth used to be dropped, so 10384593717069655257060992658440193.000001, just above the tie between 2^113 and 2^113 + 2, read as the tie and rounded down to 2^113.

Parameters
firstStart of the text
lastOne past the end of the text
valueReceives the parsed value, untouched when nothing was parsed
Returns
ptr points past what was consumed; ec is invalid_argument when no number was found and result_out_of_range when the value is beyond the format's range, in which case value is set to the infinity or zero it rounded to.

Definition at line 7376 of file float128.h.

◆ from_chars() [2/2]

std::from_chars_result fp128::from_chars ( const char * first,
const char * last,
float128 & value,
std::chars_format fmt )
inline

Reads a decimal or hexadecimal string into a float128. Defined below.

Converts text to a float128 in a given format, in the shape of std::from_chars.

chars_format::hex reads a hexadecimal significand and a binary exponent without the 0x prefix, as std::from_chars does; every other format reads the decimal forms from_chars() above accepts.

Parameters
firstStart of the text
lastOne past the end of the text
valueReceives the parsed value, untouched when nothing was parsed
fmtThe format to read
Returns
As from_chars() above.

Definition at line 7568 of file float128.h.

◆ operator""_f128()

float128 fp128::operator""_f128 ( const char * literal)

User-defined literal for constructing float128 from a string.

User-defined literal implementation for constructing float128 from a string.

Definition at line 6693 of file float128.h.

◆ fabs() [2/2]

float128 fp128::fabs ( const float128 & x)
constexprnoexcept
Parameters
xInput value
Returns
|x|

Definition at line 3422 of file float128.h.

◆ floor() [2/2]

float128 fp128::floor ( const float128 & x)
constexprnoexcept
Parameters
xInput value
Returns
A float128 holding the integer value.

Definition at line 3536 of file float128.h.

◆ ceil() [2/2]

float128 fp128::ceil ( const float128 & x)
constexprnoexcept
Parameters
xInput value
Returns
A float128 holding the integer value. A negative value above -1 gives -0.

Definition at line 3545 of file float128.h.

◆ trunc() [2/2]

float128 fp128::trunc ( const float128 & x)
constexprnoexcept
Parameters
xValue to truncate
Returns
Integer value, rounded towards zero. A negative value above -1 gives -0.

Definition at line 3554 of file float128.h.

◆ round() [2/2]

float128 fp128::round ( const float128 & x)
constexprnoexcept
Parameters
xValue to round
Returns
Integer value, rounded towards the nearest integer.

Definition at line 3564 of file float128.h.

◆ llrint()

int64_t fp128::llrint ( const float128 & x)
constexprnoexcept
Parameters
xInput value
Returns
Nearest integer as int64_t. Returns 0 on overflow or for a NaN, raising invalid.

Definition at line 3575 of file float128.h.

◆ llround()

int64_t fp128::llround ( const float128 & x)
constexprnoexcept
Parameters
xValue to round
Returns
Integer value, rounded towards the nearest integer. Returns 0 on overflow or for a NaN, raising invalid.

Definition at line 3583 of file float128.h.

◆ lrint()

int32_t fp128::lrint ( const float128 & x)
constexprnoexcept
Parameters
xInput value
Returns
Nearest integer as int32_t. Returns 0 on overflow or for a NaN, raising invalid.

Definition at line 3589 of file float128.h.

◆ lround()

int32_t fp128::lround ( const float128 & x)
constexprnoexcept
Parameters
xValue to round
Returns
Integer value, rounded towards the nearest integer. Returns 0 on overflow or for a NaN, raising invalid.

Definition at line 3597 of file float128.h.

◆ ilogb() [2/2]

int32_t fp128::ilogb ( const float128 & x)
constexprnoexcept

IEEE 754-2008 logB (5.3.3) with an integer result format: a zero, an infinity and a NaN have no exponent the result can express, so each is the invalid operation.

Parameters
xThe specified value.
Returns
The unbiased exponent of x - that of its leading bit for a subnormal. FP_ILOGB0 for a zero, INT_MAX for an infinity and FP_ILOGBNAN for a NaN, each raising invalid.

Definition at line 3609 of file float128.h.

◆ copysign() [2/2]

float128 fp128::copysign ( const float128 & x,
const float128 & y )
constexprnoexcept
Parameters
xThe value that's returned as the magnitude of the result.
yThe sign of the result.
Returns
The copysign functions return a floating-point value that combines the magnitude of x and the sign of y.

Definition at line 3633 of file float128.h.

◆ fmod() [2/2]

float128 fp128::fmod ( const float128 & x,
const float128 & y )
noexcept
Parameters
xNumerator
yDenominator
Returns
The modulo value.

Definition at line 3645 of file float128.h.

◆ modf() [2/2]

float128 fp128::modf ( const float128 & x,
float128 * iptr )
constexprnoexcept
Parameters
xInput value
iptrPointer to float128 holding the integer part of x.
Returns
The fraction part of x. Undefined when iptr is nullptr.

Definition at line 3720 of file float128.h.

◆ fdim() [2/2]

float128 fp128::fdim ( const float128 & x,
const float128 & y )
constexprnoexcept
Parameters
xFirst value
ySecond value
Returns
If x > y returns x - y. Otherwise zero.

Definition at line 3745 of file float128.h.

◆ fmin() [2/2]

float128 fp128::fmin ( const float128 & x,
const float128 & y )
constexprnoexcept
Parameters
xFirst value
ySecond value
Returns
If x < y returns x. Otherwise y.

Definition at line 3757 of file float128.h.

◆ fmax() [2/2]

float128 fp128::fmax ( const float128 & x,
const float128 & y )
constexprnoexcept
Parameters
xFirst value
ySecond value
Returns
If x > y returns x. Otherwise y.

Definition at line 3781 of file float128.h.

◆ fma()

float128 fp128::fma ( float128 x,
float128 y,
float128 z )
constexprnoexcept

The whole point of a fused multiply add is that the product is not rounded before the addend reaches it, which is what makes the result correct to the last bit and what lets a caller recover the error of a multiplication as fma(x, y, -x*y). Writing it as x * y + z rounds twice and loses everything the addend cancels against.

The exact product of the two 113 bit mantissas is 226 bits, and the addend is another 113. Both are placed in a wide accumulator with their leading bits aligned, added or subtracted there, and the single rounding is applied when the result is read back out. An operand too far below the other one to reach the accumulator cannot change any bit of the result except through the tie break, so it is folded into the sticky bit.

Parameters
xThe first value to multiply.
yThe second value to multiply.
zThe value to add to the product.
Returns
(x * y) + z, correctly rounded.

Definition at line 5785 of file float128.h.

◆ hypot() [2/3]

float128 fp128::hypot ( const float128 & x,
const float128 & y )
noexcept
Parameters
xFirst value
ySecond value
Returns
sqrt(x^2 + y^2).

Definition at line 3799 of file float128.h.

◆ cbrt()

float128 fp128::cbrt ( const float128 x,
uint32_t iterations = 2 )
noexcept
Parameters
xFloating point value
iterationshow many Halley to perform, usually 1 is enough
Returns
cube root of x

Definition at line 3958 of file float128.h.

◆ sqrt() [2/2]

float128 fp128::sqrt ( const float128 & x,
uint32_t iterations = 3 )
noexcept

IEEE 754 requires the square root to be correctly rounded, the same as the four arithmetic operations, and Newton's method alone cannot promise that: every step rounds, and the last one can land a unit either side of the answer. It used to, for a quarter of all arguments.

So Newton's method only gets close, and the last bit is then settled exactly. The mantissa m (doubled when the exponent is odd, so that what is left of it halves exactly) is in [2^112, 2^114), which puts the square root of N = m * 2^112 in [2^112, 2^113) - exactly the 113 bit significand the result needs. Squaring a candidate r in integer arithmetic and comparing with N moves it onto floor(sqrt(N)), and the remainder N - r*r then says which way to round: the root is past the halfway point r + 1/2 exactly when the remainder exceeds r, and it can never sit on it, because (r + 1/2)^2 is not an integer.

Based on the book "Math toolkit for real time programming" by Jack W. Crenshaw.

Parameters
xValue to calculate the root of
iterationsIgnored. The result is correctly rounded whatever its value; the parameter is kept so that existing calls still compile.
Returns
Square root of x. sqrt(-0) is -0, and any other negative argument is the invalid operation and returns a NaN.

Definition at line 3872 of file float128.h.

◆ erf()

float128 fp128::erf ( float128 x)
noexcept
Parameters
xA floating-point value.
Returns
The erf functions return the Gauss error function of x.

Definition at line 5626 of file float128.h.

◆ erfc()

float128 fp128::erfc ( float128 x)
noexcept

Above one the answer is a small difference of two values close to one, so it cannot be reached through erf() - at x = 6 the subtraction would leave 55 of the 113 bits, and past 13 nothing at all. It is computed directly instead, from Laplace's continued fraction

                  2
                -x
               e                 1
 erfc(x) = ---------- * ------------------------
            sqrt(pi)     x + (1/2)/(x + 1/(x + ...))

evaluated with the modified Lentz algorithm. The fraction converges for every x above one, and fastest where the series form is weakest.

Accuracy, measured against mpmath and pinned by tests/float128_accuracy_gtest.cpp: within 56 ulp. The worst is just above one, 43 ulp at 1.32, where the fraction converges slowest and rounds once per step; from 2 on the error was measured below 28 ulp, and below one, where the answer is 1 - erf(x), below 8.

Parameters
xInput value
Returns
1 - erf(x)

Definition at line 5708 of file float128.h.

◆ sin() [2/2]

float128 fp128::sin ( float128 x)
noexcept

Definition at line 5140 of file float128.h.

◆ asin() [2/2]

float128 fp128::asin ( float128 x)
noexcept

asin(x) = atan(x / sqrt((1-x)(1+x))). The Newton iteration on sin() this replaced divided by cos(), the derivative, which vanishes at the ends of the domain: it converged slowly there, to about 58 correct bits at asin(1). Near the ends 1-x is exact, so the argument of atan() keeps its accuracy however close to one x gets.

Parameters
xvalue in the range [-1,1]
Returns
Inverse sine of x. Outside the domain the result is a NaN, the invalid operation.

Definition at line 5177 of file float128.h.

◆ cos() [2/2]

float128 fp128::cos ( float128 x)
noexcept
Parameters
xvalue in Radians
Returns
Cosine of x

Definition at line 5210 of file float128.h.

◆ acos() [2/2]

float128 fp128::acos ( float128 x)
noexcept

acos(x) = 2 * atan(sqrt((1-x)/(1+x))). The Newton iteration this replaced divided by sin(), which is zero at acos(1): that returned a NaN, and so did acos(1 - 2^-100). Near x = 1 the difference 1-x is exact, and near x = -1 the sum 1+x is, so the quotient keeps its accuracy at both ends.

Parameters
xvalue in the range [-1,1]
Returns
Inverse cosine of x. Outside the domain the result is a NaN, the invalid operation.

Definition at line 5245 of file float128.h.

◆ tan() [2/2]

float128 fp128::tan ( float128 x)
noexcept
Parameters
xvalue
Returns
Tangent of x

Definition at line 5267 of file float128.h.

◆ atan() [2/2]

float128 fp128::atan ( float128 x)
noexcept
Parameters
xvalue
Returns
Arctangent of x

Definition at line 5273 of file float128.h.

◆ atan2() [2/2]

float128 fp128::atan2 ( float128 y,
float128 x )
noexcept
Parameters
yvalue
xvalue
Returns
Arctangent of y / x in the range [-pi, pi]. The zeros and infinities follow IEEE 754-2008 9.2.1: the sign of a zero y is kept, a negative x (-0 included) puts the result at +-pi, and two infinities give +-pi/4 or +-3pi/4.

Definition at line 5339 of file float128.h.

◆ sinh() [2/2]

float128 fp128::sinh ( float128 x)
noexcept
Parameters
xvalue
Returns
Sine of x

Definition at line 5393 of file float128.h.

◆ asinh() [2/2]

float128 fp128::asinh ( float128 x)
noexcept
Parameters
xvalue
Returns
Inverse hyperbolic sine of x

Definition at line 5429 of file float128.h.

◆ cosh() [2/2]

float128 fp128::cosh ( float128 x)
noexcept
Parameters
xvalue in Radians in the range [-0.5pi, 0.5pi]
Returns
Sine of x

Definition at line 5474 of file float128.h.

◆ acosh() [2/2]

float128 fp128::acosh ( float128 x)
noexcept
Parameters
xvalue in the range [1, inf]
Returns
Inverse hyperbolic cosine of x

Definition at line 5498 of file float128.h.

◆ tanh() [2/2]

float128 fp128::tanh ( float128 x)
noexcept
Parameters
xvalue
Returns
hyperbolic tangent of x

Definition at line 5533 of file float128.h.

◆ atanh() [2/2]

float128 fp128::atanh ( float128 x)
noexcept
Parameters
xvalue in the range (-1, 1)
Returns
Inverse hyperbolic tangent of x

Definition at line 5569 of file float128.h.

◆ exp() [2/2]

float128 fp128::exp ( const float128 & x)
noexcept

x is written as k*ln2 + r with k an integer and |r| <= ln2/2, which turns the answer into 2^k * exp(r): the power of two is an exact scaling and only the reduced argument goes through a series.

The reduction is where the accuracy of the whole function is decided. ln2 is irrational, so k*ln2 cannot be represented and subtracting a rounded one leaves an error of k ulp - at the top of the range k reaches 16000 and fourteen bits of the answer are gone before the series even starts. Splitting ln2 into a high part whose low 14 bits are zero, so that k times it is exact, and a low part carrying the rest, keeps r accurate to far below its last bit.

The previous implementation raised e to the integer part by repeated squaring, which doubles its own error at every step, and reached the negative half of the range through reciprocal().

Parameters
xA number specifying a power.
Returns
e^x

Definition at line 4190 of file float128.h.

◆ exp2() [2/2]

float128 fp128::exp2 ( const float128 & x)
noexcept
Parameters
xExponent value
Returns
2^x

Definition at line 4232 of file float128.h.

◆ expm1() [2/2]

float128 fp128::expm1 ( const float128 & x)
noexcept
Parameters
xA number specifying a power.
Returns
Exponent of x

Definition at line 4269 of file float128.h.

◆ pow() [2/3]

float128 fp128::pow ( const float128 & x,
const float128 & y )
noexcept

The special values follow IEEE 754-2008 9.2.1 throughout. Among those the previous version got wrong: pow(0.5, inf) and pow(2, -inf) were infinite rather than zero, pow(2, NaN) was infinite, pow(-0, 0.5) a NaN, and every integer exponent beyond 11355 in magnitude overflowed whatever the base, so pow(1 + 2^-40, 12000), which is about 1.00000001, came out infinite.

Accuracy, measured against mpmath and pinned by tests/float128_accuracy_gtest.cpp: within 4 + 2.5 |y log2(x)| ulp, which is about 41000 ulp next to the overflow and underflow thresholds, where |y log2(x)| reaches 16383. Both methods below lose about two ulp per unit of that product - the relative error of log(x), or of every squaring, becomes an absolute error of the exponent, and the exponential makes it relative again - and holding it to a few ulp would take an intermediate wider than 113 bits. A y of 1/2 is the square root, correctly rounded.

Parameters
xBase value
yExponent value
Returns
x^y

Definition at line 4359 of file float128.h.

◆ pow() [3/3]

float128 fp128::pow ( const float128 & x,
int32_t y )
noexcept
Parameters
xBase value
yExponent value (integer)
Returns
x^y

Definition at line 4333 of file float128.h.

◆ log() [2/2]

float128 fp128::log ( float128 x)
noexcept
Parameters
xThe number to perform log on.
Returns
log(x)

Definition at line 4513 of file float128.h.

◆ log2() [2/5]

float128 fp128::log2 ( float128 x)
noexcept

Accurate relative to its own result, which matters most for an argument close to one: the answer is then proportional to x - 1, and that difference is carried through exactly rather than being rounded onto a grid it would barely register on. That holds on both sides of one; below it the exponent is -1, and the answer is formed without the -1 that would cancel. The earlier implementation built the answer as a fixed point fraction of 112 bits before returning it as a float, which left log2(1 + 2^-112) with no correct significant bits at all.

Parameters
xThe number to perform log2 on.
Returns
log2(x)

Definition at line 4542 of file float128.h.

◆ log10() [2/2]

float128 fp128::log10 ( float128 x)
noexcept
Parameters
xThe number to perform log on.
Returns
log10(x)

Definition at line 4700 of file float128.h.

◆ logb() [2/2]

float128 fp128::logb ( float128 x)
noexcept
Parameters
xThe number to perform log on.
Returns
logb(x)

Definition at line 4720 of file float128.h.

◆ log1p() [2/2]

float128 fp128::log1p ( float128 x)
noexcept
Parameters
xThe number to perform log on.
Returns
log1p(x)

Definition at line 4744 of file float128.h.

◆ frexp()

float128 fp128::frexp ( float128 x,
int * expptr )
constexprnoexcept
Parameters
xFloating-point value.
expptrReceives the exponent: zero for a zero, an infinity or a NaN.
Returns
Mantissa in the [0.5,1) range with the sign of x. A zero or an infinity comes back unchanged, a NaN quieted (a signaling one raising invalid, as for every operation).

Definition at line 5923 of file float128.h.

◆ ldexp()

float128 fp128::ldexp ( float128 x,
int exp )
constexprnoexcept
Parameters
xFloating-point value.
expInteger exponent.
Returns
The ldexp functions return the value of x * 2^exp if successful. On overflow, and depending on the sign of x, ldexp returns +/- inf

Definition at line 5948 of file float128.h.

◆ isfinite()

bool fp128::isfinite ( const float128 & x)
constexprnoexcept
Parameters
xInput value
Returns
Non-zero if finite, zero otherwise.

Definition at line 5765 of file float128.h.

◆ signbit()

bool fp128::signbit ( const float128 & x)
constexprnoexcept

Definition at line 5971 of file float128.h.

◆ isnormal()

bool fp128::isnormal ( const float128 & x)
constexprnoexcept

Definition at line 5973 of file float128.h.

◆ fpclassify()

int fp128::fpclassify ( const float128 & x)
constexprnoexcept

Definition at line 5975 of file float128.h.

◆ isunordered()

bool fp128::isunordered ( const float128 & x,
const float128 & y )
constexprnoexcept

This and the five predicates below are IEEE 754-2008's quiet comparisons (5.11): a quiet NaN operand is an ordinary unordered answer, a signaling one is the invalid operation. The relational operators are the signaling comparisons instead, which raise invalid for any NaN. The five below decide unorderedness through this function, which is where the signal comes from.

Definition at line 5993 of file float128.h.

◆ isgreater()

bool fp128::isgreater ( const float128 & x,
const float128 & y )
constexprnoexcept

Definition at line 6000 of file float128.h.

◆ isgreaterequal()

bool fp128::isgreaterequal ( const float128 & x,
const float128 & y )
constexprnoexcept

Definition at line 6005 of file float128.h.

◆ isless()

bool fp128::isless ( const float128 & x,
const float128 & y )
constexprnoexcept

Definition at line 6010 of file float128.h.

◆ islessequal()

bool fp128::islessequal ( const float128 & x,
const float128 & y )
constexprnoexcept

Definition at line 6015 of file float128.h.

◆ islessgreater()

bool fp128::islessgreater ( const float128 & x,
const float128 & y )
constexprnoexcept

Definition at line 6020 of file float128.h.

◆ rint()

float128 fp128::rint ( const float128 & x)
constexprnoexcept

Definition at line 6165 of file float128.h.

◆ nearbyint()

float128 fp128::nearbyint ( const float128 & x)
constexprnoexcept

Definition at line 6170 of file float128.h.

◆ scalbn()

float128 fp128::scalbn ( const float128 & x,
int n )
constexprnoexcept

Definition at line 6181 of file float128.h.

◆ scalbln()

float128 fp128::scalbln ( const float128 & x,
long n )
constexprnoexcept

Definition at line 6183 of file float128.h.

◆ nextafter()

float128 fp128::nextafter ( const float128 & x,
const float128 & y )
constexprnoexcept

A quiet operation, like IEEE 754-2008's nextUp and nextDown that it is built on: stepping from the largest finite value to infinity, or into the subnormal range or onto zero, raises neither overflow nor underflow (C's Annex F would raise them). Only a signaling NaN operand raises an exception, invalid, and is quieted.

Parameters
xStarting value
yValue giving the direction
Returns
The neighbour of x towards y, or y itself when the two are equal.

Definition at line 6205 of file float128.h.

◆ nexttoward()

float128 fp128::nexttoward ( const float128 & x,
const float128 & y )
constexprnoexcept

Definition at line 6214 of file float128.h.

◆ remainder()

float128 fp128::remainder ( const float128 & x,
const float128 & y )
noexcept

Unlike fmod, whose result keeps the sign of x, this one lands in [-|y|/2, |y|/2].

Parameters
xDividend
yDivisor
Returns
The remainder.

Definition at line 6305 of file float128.h.

◆ remquo()

float128 fp128::remquo ( const float128 & x,
const float128 & y,
int * quo )
noexcept
Parameters
xDividend
yDivisor
quoReceives at least the low three bits of the quotient, with the sign of x/y
Returns
The remainder.

Definition at line 6318 of file float128.h.

◆ hypot() [3/3]

float128 fp128::hypot ( const float128 & x,
const float128 & y,
const float128 & z )
noexcept
Parameters
xFirst side
ySecond side
zThird side
Returns
sqrt(x*x + y*y + z*z)

Definition at line 6365 of file float128.h.

◆ lgamma()

float128 fp128::lgamma ( float128 x)
noexcept

Three regimes:

  • |x| < 32: x = n + z with n = round(x), and the recurrence gamma(x + 1) = x * gamma(x) moves the argument to 2 + z, where lgamma_near_two() is accurate relative to its result. Every factor the recurrence takes is x moved by an integer towards zero, which is exact, so the answer is lgamma(2 + z) plus or minus the logarithm of their product: rounded a few times rather than cancelled. Next to a pole the factor z is the small one, and its logarithm is the answer.
  • x >= 32: Stirling's asymptotic series.
  • x <= -32: the reflection formula, as |gamma(x)| = pi / (|sin(pi x)| |x| gamma(-x)), with the sine reduced exactly by abs_sin_pi().

The result is the logarithm of the absolute value: the gamma function alternates sign between the poles at the non positive integers.

Accuracy, measured against mpmath and pinned by tests/float128_accuracy_gtest.cpp: within 6 ulp for x > 0. For x < 0 within the larger of 6 ulp and an absolute error of 2^-110. The absolute term matters next to the zeros lgamma has on the negative axis - two between each pair of poles from (-3, -2) to (-32, -31), about 1/n! from the poles - where the answer is a difference of terms of order log(n!): relative to a result that vanishes there it is unbounded.

Parameters
xInput value
Returns
log(|gamma(x)|)

Definition at line 6534 of file float128.h.

◆ tgamma()

float128 fp128::tgamma ( float128 x)
noexcept
  • The integers up to 38: the factorial, exactly. 37! is the largest factorial a binary128 holds without rounding - its odd part has 110 bits - so no partial product of the integers below x rounds either.
  • |x| < 32: exp(lgamma(2 + z)) multiplied or divided by the exact factors the recurrence takes, see lgamma(). The exponential is of a value below 0.3 and the product rounds once per factor, so the result is within a few ulp - also next to a pole, where it used to be 2^39 ulp off at -1 + 2^-40, and at a tiny argument, where gamma(x) is about 1/x.
  • Elsewhere exp(lgamma(x)), with the sign of the interval between the poles. The exponential is what limits the accuracy there: a logarithm as large as 11000 carries its own last bit into the fourteenth bit from the bottom of the result.

Accuracy, measured against mpmath and pinned by tests/float128_accuracy_gtest.cpp: exact for the integers up to 38, within 8 ulp for |x| < 32, and within 8 + 4.5 |lgamma(x)| ulp beyond that, which reaches about 51000 ulp at either end of the range.

Parameters
xInput value
Returns
gamma(x)

Definition at line 6626 of file float128.h.

◆ abs()

float128 fp128::abs ( const float128 & x)
constexprnoexcept

Definition at line 6690 of file float128.h.

◆ totalorder()

bool fp128::totalorder ( const float128 & x,
const float128 & y )
constexprnoexcept

The order every value takes part in, NaNs included: -NaN < -inf < negative values < -0 < +0 < positive values < +inf < +NaN, a signaling NaN before a quiet one of the same sign, and NaNs of the same kind ordered by payload. It never signals, even for a signaling NaN.

Parameters
xFirst value
ySecond value
Returns
True when x is ordered before or the same as y.

Definition at line 6059 of file float128.h.

◆ totalordermag()

bool fp128::totalordermag ( const float128 & x,
const float128 & y )
constexprnoexcept

Definition at line 6067 of file float128.h.

◆ fmaxmag()

float128 fp128::fmaxmag ( const float128 & x,
const float128 & y )
constexprnoexcept
Parameters
xFirst value
ySecond value
Returns
The larger magnitude. A quiet NaN is treated as missing; a signaling one is the invalid operation and gives a quiet NaN.

Definition at line 6079 of file float128.h.

◆ fminmag()

float128 fp128::fminmag ( const float128 & x,
const float128 & y )
constexprnoexcept
Parameters
xFirst value
ySecond value
Returns
The larger magnitude. A quiet NaN is treated as missing; a signaling one is the invalid operation and gives a quiet NaN.

Definition at line 6092 of file float128.h.

◆ iscanonical()

bool fp128::iscanonical ( const float128 & x)
constexprnoexcept

Definition at line 6105 of file float128.h.

◆ issignaling()

bool fp128::issignaling ( const float128 & x)
constexprnoexcept

Definition at line 6107 of file float128.h.

◆ issubnormal()

bool fp128::issubnormal ( const float128 & x)
constexprnoexcept

Definition at line 6109 of file float128.h.

◆ iszero()

bool fp128::iszero ( const float128 & x)
constexprnoexcept

Definition at line 6111 of file float128.h.

◆ nan()

float128 fp128::nan ( const char * payload)
noexcept

The only one of these that a call cannot reach through argument dependent lookup: its argument is a plain character pointer, so the name has to be visible at namespace scope - and a call has to be qualified as fp128::nan(...) wherever <cmath> puts its own nan(const char*) in scope too.

Definition at line 6124 of file float128.h.

◆ reciprocal() [2/2]

float128 fp128::reciprocal ( const float128 & x)
noexcept

The division itself, which rounds once in the current direction. This used to refine a double seed with Newton iterations, which was a third of the speed of the division (11 M/s against 35 M/s on MSVC, 10.5 against 37 on Clang, P-core, 2026-10-10) and up to an ulp off: a subnormal result was rounded twice, and in a directed rounding mode the result could land on the wrong side.

Parameters
xInput value
Returns
1 / x. +-0 gives +-inf and raises division by zero, +-inf gives +-0, a NaN is propagated.

Definition at line 4017 of file float128.h.

◆ fact_reciprocal() [2/2]

void fp128::fact_reciprocal ( int x,
float128 & res )
noexcept
Parameters
xInput value
resResult of the function

Definition at line 4029 of file float128.h.

◆ double_factorial()

float128 fp128::double_factorial ( int x)
noexcept

The values below 100 come from a table built during compilation, every product rounded to nearest. Filling a function local table on first use, as this used to, was a data race when two threads made the first call together, and under FP128_IEEE_ENV the products took the rounding direction of whichever caller came first.

Parameters
xThe number to compute the double factorial of.
Returns
x!!: exact for every odd x up to 51 and every even x up to 74, and within 1 ulp of the correctly rounded value up to 99 (each product of the table rounds once, so the error can accumulate). (-1)!! is 1, the empty product (2n - 1)!! takes for n = 0. Any other negative x is the invalid operation and returns a NaN; x of 100 or more returns infinity.

< c[i] is i!!

Definition at line 4109 of file float128.h.

◆ fegetround()

int fp128::fegetround ( )
inlinenodiscardnoexcept

The rounding direction float128 arithmetic uses on the calling thread.

Returns
One of FE_TONEAREST, FE_TOWARDZERO, FE_UPWARD or FE_DOWNWARD.

Definition at line 411 of file float128.h.

◆ fesetround()

int fp128::fesetround ( int round)
inlinenoexcept

Selects the rounding direction float128 arithmetic uses on the calling thread.

Parameters
roundOne of FE_TONEAREST, FE_TOWARDZERO, FE_UPWARD or FE_DOWNWARD
Returns
Zero on success. Non zero for an unknown direction, and for anything but FE_TONEAREST when the program was built without FP128_IEEE_ENV.

Definition at line 427 of file float128.h.

◆ fetestexcept()

int fp128::fetestexcept ( int excepts)
inlinenodiscardnoexcept

Tests float128 exception flags (IEEE 754 testFlags).

Parameters
exceptsFE_ bits to test
Returns
The subset of excepts that is raised. Always zero without FP128_IEEE_ENV.

Definition at line 452 of file float128.h.

◆ feclearexcept()

int fp128::feclearexcept ( int excepts)
inlinenoexcept

Lowers float128 exception flags (IEEE 754 lowerFlags).

Parameters
exceptsFE_ bits to clear
Returns
Zero.

Definition at line 466 of file float128.h.

◆ feraiseexcept()

int fp128::feraiseexcept ( int excepts)
inlinenoexcept

Raises float128 exception flags (IEEE 754 raiseFlags).

Parameters
exceptsFE_ bits to raise
Returns
Zero on success; non zero without FP128_IEEE_ENV, when there is nowhere to raise them.

Definition at line 479 of file float128.h.

◆ fegetexceptflag()

int fp128::fegetexceptflag ( std::fexcept_t * flagp,
int excepts )
inlinenoexcept

Saves the state of float128 exception flags (IEEE 754 saveAllFlags).

Parameters
flagpReceives the saved state
exceptsFE_ bits to save
Returns
Zero.

Definition at line 495 of file float128.h.

◆ fesetexceptflag()

int fp128::fesetexceptflag ( const std::fexcept_t * flagp,
int excepts )
inlinenoexcept

Restores float128 exception flags saved by fegetexceptflag (IEEE 754 restoreFlags).

Only the flags named in excepts are written, each set to the state it had when saved.

Parameters
flagpState saved by fegetexceptflag()
exceptsFE_ bits to restore
Returns
Zero.

Definition at line 511 of file float128.h.

◆ to_string()

std::string fp128::to_string ( const float128 & value)
inlinenodiscard

The shortest decimal string that reads back as this exact value.

Parameters
valueValue to convert
Returns
Decimal text, in scientific notation when the exponent is far from zero.

Definition at line 7132 of file float128.h.

◆ to_chars() [1/3]

std::to_chars_result fp128::to_chars ( char * first,
char * last,
const float128 & value,
std::chars_format fmt,
int precision )
inline

Converts a float128 to text, in the shape of std::to_chars.

Parameters
firstStart of the output range
lastOne past the end of the output range
valueValue to convert
fmtLayout to use. chars_format::hex writes what std::to_chars writes for a double - no 0x prefix and as few exponent digits as needed, 1.8p+1 - which from_chars() with chars_format::hex reads back to the same value. A subnormal is written normalized, 1p-16494 for the smallest one.
precisionDigits after the point, or significant digits for general
Returns
ptr points past the last character written; ec is value_too_large when the range was too small, in which case nothing was written.

Definition at line 7588 of file float128.h.

◆ to_chars() [2/3]

std::to_chars_result fp128::to_chars ( char * first,
char * last,
const float128 & value,
std::chars_format fmt )
inline

Converts a float128 to text with the default precision for the layout.

Definition at line 7609 of file float128.h.

◆ to_chars() [3/3]

std::to_chars_result fp128::to_chars ( char * first,
char * last,
const float128 & value )
inline

Converts a float128 to the shortest text that reads back as the same value.

Definition at line 7615 of file float128.h.

◆ operator<<() [2/3]

std::ostream & fp128::operator<< ( std::ostream & os,
const float128 & value )
inline

Writes a float128 to a stream, honouring its formatting state.

The stream's precision, its fixed, scientific and hexfloat flags, showpos, showpoint, uppercase, width, fill and adjustfield are all applied, so a float128 behaves in a stream the way a double does.

Definition at line 7633 of file float128.h.

◆ operator>>() [2/3]

std::istream & fp128::operator>> ( std::istream & is,
float128 & value )
inline

Reads a float128 from a stream.

Accepts what the constructor from a string does: a decimal number with an optional exponent, a hexadecimal one after a 0x prefix with an optional binary exponent (0x1.8p1), and inf, infinity, nan, nan(payload) and snan in any case, each with an optional sign. Leading white space is skipped unless skipws is off.

Like the builtin extractors it reads only as far as the number goes and leaves the character that ends it in the stream, so "1.5,2.5" gives 1.5 and leaves ",2.5" to be read next. It used to read up to the next white space and fail the whole token. A value beyond the range is read as the infinity or zero it rounds to, as the constructor reads it.

Failure - no number at all, or one that stops halfway, such as "1e" or "0x" - leaves the value untouched and sets failbit.

Definition at line 7691 of file float128.h.

◆ strnlwr()

errno_t fp128::strnlwr ( char * dest,
const char * src,
size_t n )
inlinestaticnoexcept

Copy a string to lowercase, up to n characters.

Parameters
destDestination buffer.
srcSource string.
nMaximum number of characters to copy.
Returns
0 on success, EINVAL if dest or src is nullptr.

Definition at line 968 of file fp128_shared.h.

◆ array_length()

template<typename T>
uint32_t fp128::array_length ( const T & a)
nodiscardconstexpr

Calculates the element count of a C style array at build time Example: int a[5]; constexpr int len = array_length(a); // returns 5 at build time.

Template Parameters
Tarray type
Parameters
aarray instance
Returns
Element count in array

Definition at line 990 of file fp128_shared.h.

◆ shift_right64_round()

uint64_t fp128::shift_right64_round ( uint64_t x,
int shift )
inlinenodiscardconstexprnoexcept

Right-shift a 64-bit value with rounding.

Undefined behavior when shift is outside the range [1, 63].

Parameters
xValue to shift.
shiftNumber of bits to shift.
Returns
The rounded result of x >> shift.

Definition at line 1004 of file fp128_shared.h.

◆ shift_right128_inplace()

void fp128::shift_right128_inplace ( uint64_t & l,
uint64_t & h,
int shift )
inlineconstexprnoexcept

Right shift a 128 bit unsigned integer (inplace). Limited range, inplace and no parameter checks (checked via assert in debug builds)

Parameters
lLow QWORD
hHigh QWORD
shiftBits to shift, between 1-63

Definition at line 1018 of file fp128_shared.h.

◆ shift_left128_inplace()

void fp128::shift_left128_inplace ( uint64_t & l,
uint64_t & h,
int shift )
inlineconstexprnoexcept

Left shift a 128 bit integer (inplace). Limited range, inplace and no parameter checks (checked via assert in debug builds)

Parameters
lLow QWORD
hHigh QWORD
shiftBits to shift, between 1-63

Definition at line 1031 of file fp128_shared.h.

◆ shift_right128_inplace_safe()

void fp128::shift_right128_inplace_safe ( uint64_t & l,
uint64_t & h,
int shift )
inlineconstexprnoexcept

Right shift of an unsigned 128 bit integer (inplace), rounded to nearest with a tie going up.

The magnitude is divided by 2^shift and rounded to the nearest integer; an exact tie rounds up, which for a magnitude is away from zero. That is the rule fixed_point128 applies to every rounded result - the multiply, the divisions and the signed shift below - so a value gets the same answer whichever of them produced it.

Rounding half up needs no sticky bit: the result moves up exactly when the highest dropped bit is set, whatever lies below it, which keeps this free of branches beyond the choice of QWORD.

Parameters
lLow QWORD
hHigh QWORD
shiftBits to shift, any non negative count. 128 rounds 2^127 and above up to one, more than 128 always leaves zero.

Definition at line 1103 of file fp128_shared.h.

◆ shift_right128_wide_signed_low()

uint64_t fp128::shift_right128_wide_signed_low ( uint64_t l,
uint64_t h,
int shift )
nodiscardconstexprnoexcept

The shifts by 64 bits or more of shift_right128_inplace_safe_signed().

Kept apart so that the common case stays small: the callers of that function, the shift operators of fixed_point128 among them, are inlined only while it is, and a shift by a constant count then folds down to a handful of instructions. The QWORDs travel by value: a reference would take their address and push the caller's value through memory on the common path as well.

Only the low QWORD of the result is returned. The high one is the sign of the input, or zero when the low QWORD is zero: the quotient fits in 64 bits, and a negative one is never zero there unless rounding carried it all the way up from minus one half.

Parameters
lLow QWORD
hHigh QWORD, holding the sign in its MSB
shiftBits to shift, 64 or more
Returns
The low QWORD of the rounded quotient.

Definition at line 1147 of file fp128_shared.h.

◆ shift_right128_inplace_safe_signed()

void fp128::shift_right128_inplace_safe_signed ( uint64_t & l,
uint64_t & h,
int shift )
inlineconstexprnoexcept

Arithmetic right shift of a 128 bit two's complement value (inplace), rounded to nearest with a tie going away from zero.

The signed counterpart of shift_right128_inplace_safe: the vacated top bits are filled with copies of the sign bit instead of zeros, so the shift divides by a power of two for negative values as well as positive ones. The result is the quotient rounded to the nearest integer, and an exact tie goes away from zero - the same answer as rounding the magnitude half up and putting the sign back, which is what the multiply and the divisions of fixed_point128 do.

The arithmetic shift itself rounds towards minus infinity. One is added back when the dropped part is above one half, or is exactly one half of a non negative value; the sticky bit, which tells those two apart, is every dropped bit below the highest one.

A shift of 128 or more leaves zero, except that lowest() shifted by exactly 128 is a tie at minus one half and so rounds away from zero, to minus one.

Parameters
lLow QWORD
hHigh QWORD, holding the sign in its MSB
shiftBits to shift, any non negative count

Definition at line 1188 of file fp128_shared.h.

◆ shift_left128_inplace_safe()

void fp128::shift_left128_inplace_safe ( uint64_t & l,
uint64_t & h,
int shift )
inlineconstexprnoexcept

Left shift a 128 bit integer (inplace). Handles any positive shift value.

Parameters
lLow QWORD
hHigh QWORD
shiftBits to shift, between 1-inf

Definition at line 1221 of file fp128_shared.h.

◆ shift_right128() [1/2]

template<int shift>
uint64_t fp128::shift_right128 ( uint64_t l,
uint64_t h )
inlinenodiscardconstexprnoexcept

Right shift a 128 bit integer. When shift is a compile time constant, this function generates optimal code for all shift values.

Parameters
lLow QWORD
hHigh QWORD @
Returns
Lower 64 bit of the result

Definition at line 1247 of file fp128_shared.h.

◆ shift_left128() [1/2]

template<int shift>
uint64_t fp128::shift_left128 ( uint64_t l,
uint64_t h )
inlinenodiscardconstexprnoexcept

Left shift a 128 bit integer. When shift is a compile time constant, this function generates optimal code for all shift values.

Parameters
lLow QWORD
hHigh QWORD @
Returns
Upper 64 bit of the result

Definition at line 1273 of file fp128_shared.h.

◆ shift_right128() [2/2]

uint64_t fp128::shift_right128 ( uint64_t l,
uint64_t h,
int shift )
inlinenodiscardconstexprnoexcept

Right shift a 128 bit integer.

Parameters
lLow QWORD
hHigh QWORD
shiftBits to shift, between 0-127
Returns
Lower 64 bit of the result

Definition at line 1293 of file fp128_shared.h.

◆ shift_right128_round()

uint64_t fp128::shift_right128_round ( uint64_t l,
uint64_t h,
int shift )
inlinenodiscardconstexprnoexcept

Right shift a 128 bit integer with rounding.

Parameters
lLow QWORD
hHigh QWORD
shiftBits to shift, between 0-127
Returns
Lower 64 bit of the result

Definition at line 1315 of file fp128_shared.h.

◆ shift_left128() [2/2]

uint64_t fp128::shift_left128 ( uint64_t l,
uint64_t h,
int shift )
inlinenodiscardconstexprnoexcept

Left shift a 128 bit integer.

Parameters
lLow QWORD
hHigh QWORD
shiftBits to shift, between 0-127
Returns
Upper 64 bit of the result

Definition at line 1327 of file fp128_shared.h.

◆ twos_complement128()

void fp128::twos_complement128 ( uint64_t & l,
uint64_t & h )
inlineconstexprnoexcept

converts a 128 integer to negative via 2's complement.

Parameters
lLow QWORD (ref)
hHigh QWORD (ref)

Definition at line 1345 of file fp128_shared.h.

◆ div_64bit()

bool fp128::div_64bit ( uint64_t * q,
uint64_t * r,
const uint64_t * u,
uint64_t v,
int64_t m )
inlinestaticnoexcept

64 bit words unsigned divide function. Variation of the code from the book Hacker's Delight.

Parameters
q(output) Pointer to receive the quotient. Expected to be initialized to zero
r(output, optional) Pointer to receive the remainder. Can be nullptr
uPointer to Numerator, an array of uint64_t
vdenominator (uint64_t)
mCount of elements in u
Returns
true on success, false when a pointer is null or the divisor is zero.

Definition at line 1359 of file fp128_shared.h.

◆ div_128bit() [1/2]

template<int64_t m>
bool fp128::div_128bit ( uint64_t * q,
uint64_t * r,
const uint64_t * u,
const uint64_t * v )
inlinestaticnoexcept

Divides an unsigned integer of up to 256 bits by a 128 bit one. Knuth algorithm D, 64 bit limbs.

This is the divide every 128 bit type in this library reaches once the divisor needs more than 64 bits: int128_t and uint128_t divide 128 by 128, fixed_point128 and float128 divide 256 by 128 because they scale the numerator by 2^128 first to keep the fraction bits of the quotient.

The limb width is the whole point. The same algorithm over 32 bit limbs sees those shapes as m=4,n=4 and m=8,n=4 - up to five main loop passes with a four iteration multiply-subtract in each, where 64 bit limbs need one and three passes of two. The quotient estimate costs one DIV instruction either way. Measured on the 256/128 shape, pinned to a single core, the wider limbs are worth 3.1x under MSVC and 7.9x under clang-cl, and the float128 division benchmarks gain 109% and 382% respectively. Narrow limbs also cost Clang more than they cost MSVC: it used to trail by 1.6x on this division and is the faster of the two toolchains here.

The estimate needs a 128/64 divide, which x86-64 has and AArch64 does not; udiv128() provides it either way, falling back to the compiler runtime helper where there is no instruction.

Note
This does not shrink its operands: leading zero words in u cost one wasted pass each but no accuracy, and a divisor whose high word is zero is rejected rather than handled, because that case belongs in div_64bit() which is cheaper again. Every caller here already branches on it.

The word count is a template parameter so that every call site gets a division specialized for its own shape - the loops unrolled for that count - whether or not the compiler inlines it. Every caller in the library knows the count when it compiles. As a function argument it only became a constant where the compiler happened to inline the call or specialize it for its call sites, and with callers in three headers sharing one out of line copy, clang++ did neither: that copy cost fixed_point128's long division 15%. div_128bit(q, r, u, v, m) below takes the count at run time.

Template Parameters
mCount of words in u. Must be 2, 3 or 4.
Parameters
q(output) Quotient, m - 1 words, q[0] lowest. Only those words are written, so a caller wanting a wider zero filled result must zero the rest itself.
r(output, optional) Remainder, two words. Can be nullptr.
uNumerator, m words, u[0] lowest.
vDenominator, two words. v[1] must be non zero.
Returns
true on success, false when a parameter fails one of the conditions above.

Definition at line 1435 of file fp128_shared.h.

◆ div_128bit() [2/2]

bool fp128::div_128bit ( uint64_t * q,
uint64_t * r,
const uint64_t * u,
const uint64_t * v,
int64_t m )
inlinestaticnoexcept

div_128bit() with the word count of the numerator chosen at run time.

Dispatches to the specialization for m. The library's own callers all know the count when they compile and call div_128bit<m>() directly; this form is for a count that is only known at run time.

Parameters
q(output) Quotient, m - 1 words, q[0] lowest.
r(output, optional) Remainder, two words. Can be nullptr.
uNumerator, m words, u[0] lowest.
vDenominator, two words. v[1] must be non zero.
mCount of words in u. Must be 2, 3 or 4.
Returns
true on success, false when m is out of range or a parameter fails a condition of div_128bit<m>().

Definition at line 1526 of file fp128_shared.h.

◆ popcnt128()

uint64_t fp128::popcnt128 ( uint64_t l,
uint64_t h )
inlinenodiscardconstexprnoexcept

Counts the number of 1 bits (population count) in a 128-bit unsigned integer.

Parameters
lLow QWORD
hHigh QWORD
Returns
Number of 1 bits in the 128 bit value.

Definition at line 1545 of file fp128_shared.h.

◆ lzcnt128() [2/2]

uint64_t fp128::lzcnt128 ( uint64_t l,
uint64_t h )
inlinenodiscardconstexprnoexcept

Left zero count 128 bit.

Parameters
lLow QWORD
hHigh QWORD
Returns
Left zero count

Definition at line 1555 of file fp128_shared.h.

◆ log2() [3/5]

uint64_t fp128::log2 ( uint64_t l,
uint64_t h )
inlinenodiscardconstexprnoexcept

Calculates the Log base 2 of x: log2(x) Rounding is always towards zero so the maximum error is close to 1.

Parameters
lLower QWORD of the value
hHigh QWORD of the value
Returns
log2(x). Returns zero when x is zero.

Definition at line 1566 of file fp128_shared.h.

◆ log2() [4/5]

uint64_t fp128::log2 ( uint64_t x)
inlinenodiscardconstexprnoexcept

Calculates the Log base 2 of x: log2(x) Rounding is always towards zero so the maximum error is close to 1.

Parameters
xThe number to perform log2 on.
Returns
log2(x). Returns zero when x is zero.

Definition at line 1576 of file fp128_shared.h.

◆ log2() [5/5]

uint32_t fp128::log2 ( uint32_t x)
inlinenodiscardconstexprnoexcept

Calculates the Log base 2 of x: log2(x) Rounding is always towards zero so the maximum error is close to 1.

Parameters
xThe number to perform log2 on.
Returns
log2(x). Returns zero when x is zero.

Definition at line 1586 of file fp128_shared.h.

◆ mul128_high()

void fp128::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 )
inlineconstexprnoexcept

Upper 128 bits of the product of two 128 bit unsigned values.

Used by the argument reduction in fixed_point128::log2(), which needs a multiplication of two pure fractions and only the leading half of the result. Working on the raw QWORDs rather than on fixed_point128 keeps the reduction independent of that type's template parameter: both operands are values in [0,1) scaled by 2^128 whatever the caller's scaling happens to be.

The lowest QWORD of the 256 bit product is discarded. Nothing is added into that column, so it produces no carry and the result is the exact product truncated - low by less than 2^-256 of a relative unit, which is far below anything the caller can represent.

Parameters
a_lowLow QWORD of the first operand.
a_highHigh QWORD of the first operand.
b_lowLow QWORD of the second operand.
b_highHigh QWORD of the second operand.
res_lowReceives the low QWORD of the upper half of the product.
res_highReceives the high QWORD of the upper half of the product.

Definition at line 1610 of file fp128_shared.h.

◆ operator<<() [3/3]

template<bool IsSigned>
std::ostream & fp128::operator<< ( std::ostream & os,
const int128_base< IsSigned > & value )
inline

Writes a 128 bit integer to a stream, honouring its width, fill and adjustment.

The value is always written in decimal: that is the conversion the type provides, and a stream's hex and oct flags have no counterpart in it.

Definition at line 2136 of file int128_shared.h.

◆ operator>>() [3/3]

template<bool IsSigned>
std::istream & fp128::operator>> ( std::istream & is,
int128_base< IsSigned > & value )
inline

Reads a 128 bit integer from a stream, the way the builtin integer extractors do.

Reads an optional sign and the digits that follow it, and stops at the first character that is not one, leaving it in the stream: "12,34" gives 12 and leaves ",34". The digits are decimal, or hexadecimal after an 0x prefix; with std::hex or std::oct set they are read in that base, the prefix being optional for hex. A minus sign before an unsigned value wraps it around, as strtoull does.

Failure sets failbit, as for a builtin integer: no digits at all - "abc", or "0x" with nothing after it - stores zero, and a value outside the type stores the nearest end of its range, max() or min(). Leading white space is skipped unless skipws is off. This used to read a whole white space delimited token through the string constructor, which never failed: "abc" read as zero and an overflow wrapped silently.

Definition at line 2172 of file int128_shared.h.

◆ operator""_int128()

int128_t fp128::operator""_int128 ( const char * literal)
inlinenodiscard

User-defined literal for constructing int128_t from a string.

Defined at namespace scope rather than as a friend of the class template: its signature does not depend on the template parameter, so a friend definition inside the template would be emitted once per instantiation and collide. Literal operators are found by ordinary unqualified lookup only, never by ADL, so namespace scope is where they belong anyway.

Parameters
literalDecimal or hexadecimal digits with an optional sign, see the int128_t(const char*) constructor.
Returns
The parsed value.

Definition at line 90 of file int128_t.h.

◆ operator""_uint128()

uint128_t fp128::operator""_uint128 ( const char * literal)
inlinenodiscard

User-defined literal for constructing uint128_t from a string.

Defined at namespace scope rather than as a friend of the class template: its signature does not depend on the template parameter, so a friend definition inside the template would be emitted once per instantiation and collide. Literal operators are found by ordinary unqualified lookup only, never by ADL, so namespace scope is where they belong anyway.

Parameters
literalDecimal or hexadecimal digits, see the uint128_t(const char*) constructor.
Returns
The parsed value.

Definition at line 86 of file uint128_t.h.

Variable Documentation

◆ fp128_trig_series_table

uint64_t fp128::fp128_trig_series_table[][2]
inlineconstexpr

1 / (n(n+1)) for n = 1..40, with 125 fraction bits rounded to nearest, {high, low}.

The ratio of consecutive terms of the sine and cosine series: the sine term after x^n / n! is the previous one times x^2 / ((n+1)(n+2)), entries 2, 4, 6, ... of this table, and the cosine terms use entries 1, 3, 5, ... Generated with Python fractions (exact), see fixed_point128::TrigSeries().

Definition at line 172 of file fixed_point128.h.

◆ version_major

int32_t fp128::version_major = FP128_VERSION_MAJOR
staticconstexpr

Breaking changes to the public interface.

Definition at line 838 of file fp128_shared.h.

◆ version_minor

int32_t fp128::version_minor = FP128_VERSION_MINOR
staticconstexpr

Backwards compatible additions.

Definition at line 839 of file fp128_shared.h.

◆ version_patch

int32_t fp128::version_patch = FP128_VERSION_PATCH
staticconstexpr

Fixes that change neither.

Definition at line 840 of file fp128_shared.h.

◆ version_build

int32_t fp128::version_build = FP128_VERSION_BUILD
staticconstexpr

Rebuild of an unchanged source tree.

Definition at line 841 of file fp128_shared.h.

◆ version

int32_t fp128::version = FP128_VERSION
staticconstexpr

All four packed into one comparable integer.

Definition at line 842 of file fp128_shared.h.

◆ version_string

const char* fp128::version_string = FP128_VERSION_STRING
staticconstexpr

Dotted form, e.g. "0.9.0.0".

Definition at line 843 of file fp128_shared.h.

◆ flt_frac_bits

int32_t fp128::flt_frac_bits = 23
staticconstexpr

Mantissa bit count of an IEEE 754 float.

Definition at line 848 of file fp128_shared.h.

◆ flt_exp_bits

int32_t fp128::flt_exp_bits = 8
staticconstexpr

Exponent bit count of an IEEE 754 float.

Definition at line 849 of file fp128_shared.h.

◆ dbl_frac_bits

int32_t fp128::dbl_frac_bits = 52
staticconstexpr

Mantissa bit count of an IEEE 754 double.

Definition at line 850 of file fp128_shared.h.

◆ dbl_exp_bits

int32_t fp128::dbl_exp_bits = 11
staticconstexpr

Exponent bit count of an IEEE 754 double.

Definition at line 851 of file fp128_shared.h.

◆ log2_recip_table

uint64_t fp128::log2_recip_table[][2]
inlineconstexpr

1/(1 + j/64) as a 128 bit fraction, the reciprocals fixed_point128::log2() reduces with.

Entry zero would be exactly one, which is not a 128 bit fraction, so it holds the largest value below one instead. That makes the reduction a near no-op rather than an exact one, and log2_value_table absorbs the difference.

Definition at line 1652 of file fp128_shared.h.

◆ log2_value_table

uint64_t fp128::log2_value_table[][2]
inlineconstexpr

-log2 of the matching log2_recip_table entry, as a 128 bit fraction.

Derived from the reciprocal that is actually stored rather than from 1 + j/64, so that log2(m) = log2(m * recip) - log2(recip) holds exactly whatever the reciprocal rounded to. That is what keeps the argument reduction from contributing any error of its own.

Definition at line 1726 of file fp128_shared.h.

◆ log2_inv_n_table

uint64_t fp128::log2_inv_n_table[][2]
inlineconstexpr
Initial value:
= {
{0xB8AA3B295C17F0BBull, 0xBE87FED0691D3E89ull},
{0x5C551D94AE0BF85Dull, 0xDF43FF68348E9F44ull},
{0x3D8E13B87407FAE9ull, 0x3F82AA45785F14D8ull},
{0x2E2A8ECA5705FC2Eull, 0xEFA1FFB41A474FA2ull},
{0x24EED8A1DF37FCF2ull, 0x594E6629AE9F72E8ull},
{0x1EC709DC3A03FD74ull, 0x9FC15522BC2F8A6Cull},
{0x1A61762A7ADED93Full, 0x645C921DC5DF9B38ull},
{0x171547652B82FE17ull, 0x77D0FFDA0D23A7D1ull},
{0x1484B13D7C02A8F8ull, 0x6A80E36C7D7506F3ull},
{0x12776C50EF9BFE79ull, 0x2CA73314D74FB974ull},
{0x10C9A84994022D28ull, 0x5723A2CD20D41CF5ull},
{0x0F6384EE1D01FEBAull, 0x4FE0AA915E17C536ull},
{0x0E347AB4698BB00Eull, 0x711E274B1BC72C32ull},
{0x0D30BB153D6F6C9Full, 0xB22E490EE2EFCD9Cull},
{0x0C4F9D8B4A67FEFBull, 0x731A220DE4DFD0F8ull},
{0x0B8AA3B295C17F0Bull, 0xBBE87FED0691D3E9ull},
{0x0ADCD64DBA1F86A1ull, 0xA1CBC3B1E810C771ull},
{0x0A42589EBE01547Cull, 0x354071B63EBA8379ull},
{0x09B81E0FA687FF32ull, 0x4D65793363D91E3Dull},
{0x093BB62877CDFF3Cull, 0x9653998A6BA7DCBAull},
{0x08CB27637E4A486Aull, 0x76C98609EC9FDE68ull},
{0x0864D424CA011694ull, 0x2B91D166906A0E7Bull},
{0x080766BF04010A77ull, 0x77969BC6475A50A2ull},
{0x07B1C2770E80FF5Dull, 0x27F05548AF0BE29Bull},
}

1/(n*ln2) for n = 1 upwards, as a raw 128 bit value with 127 fraction bits; entry [i] holds 1/((i+1)*ln2).

Stored pre-scaled because the series loop reads one entry per iteration, and bringing a value into place from a decimal string every time is out of the question.

The division by ln(2) that turns the natural logarithm into a base two one is folded into these constants rather than applied once at the end. That removes a multiply from every call and, more importantly, the rounding that came with it - which mattered for the instantiations whose own precision is close to the 127 bits the series runs at.

Two readings of the same bits, one per consumer:

  • float128 takes an entry as a plain 128 bit fraction, which makes it 1/(2n*ln2) - half the mathematical value, so that every one of them stays below one. It doubles the series once at the end.
  • fixed_point128 takes it as a fixed_point128<1>, whose 126 fraction bits are one short of what the entry carries, so it shifts each one down by a bit as it reads it. That gives 1/(n*ln2) itself; entry zero is 1.4427 and the accumulator peaks around 1.47, both inside the range of that instantiation, which reaches just under 2.

Definition at line 1816 of file fp128_shared.h.

◆ log2_reduction_bits

int32_t fp128::log2_reduction_bits = 6
inlineconstexpr

Bits of argument reduction fixed_point128::log2() applies; log2_recip_table has 2^this entries.

Definition at line 1844 of file fp128_shared.h.