#pragma once12#include <cstring>3#include <cstdint>4#include <array>5#include <cmath>67namespace grisu2 {8/*!9implements the Grisu2 algorithm for binary to decimal floating-point10conversion.11Adapted from JSON for Modern C++1213This implementation is a slightly modified version of the reference14implementation which may be obtained from15http://florian.loitsch.com/publications (bench.tar.gz).16The code is distributed under the MIT license, Copyright (c) 2009 Florian17Loitsch. For a detailed description of the algorithm see: [1] Loitsch, "Printing18Floating-Point Numbers Quickly and Accurately with Integers", Proceedings of the19ACM SIGPLAN 2010 Conference on Programming Language Design and Implementation,20PLDI 2010 [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and21Accurately", Proceedings of the ACM SIGPLAN 1996 Conference on Programming22Language Design and Implementation, PLDI 199623*/2425template <typename Target, typename Source>26Target reinterpret_bits(const Source source) {27static_assert(sizeof(Target) == sizeof(Source), "size mismatch");2829Target target;30std::memcpy(&target, &source, sizeof(Source));31return target;32}3334struct diyfp // f * 2^e35{36static constexpr int kPrecision = 64; // = q3738std::uint64_t f = 0;39int e = 0;4041constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {}4243/*!44@brief returns x - y45@pre x.e == y.e and x.f >= y.f46*/47static diyfp sub(const diyfp &x, const diyfp &y) noexcept {4849return {x.f - y.f, x.e};50}5152/*!53@brief returns x * y54@note The result is rounded. (Only the upper q bits are returned.)55*/56static diyfp mul(const diyfp &x, const diyfp &y) noexcept {57static_assert(kPrecision == 64, "internal error");5859// Computes:60// f = round((x.f * y.f) / 2^q)61// e = x.e + y.e + q6263// Emulate the 64-bit * 64-bit multiplication:64//65// p = u * v66// = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi)67// = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) +68// 2^64 (u_hi v_hi ) = (p0 ) + 2^32 ((p1 ) + (p2 ))69// + 2^64 (p3 ) = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo +70// 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 ) =71// (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi +72// p2_hi + p3) = (p0_lo ) + 2^32 (Q ) + 2^64 (H ) = (p0_lo ) +73// 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H )74//75// (Since Q might be larger than 2^32 - 1)76//77// = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H)78//79// (Q_hi + H does not overflow a 64-bit int)80//81// = p_lo + 2^64 p_hi8283const std::uint64_t u_lo = x.f & 0xFFFFFFFFu;84const std::uint64_t u_hi = x.f >> 32u;85const std::uint64_t v_lo = y.f & 0xFFFFFFFFu;86const std::uint64_t v_hi = y.f >> 32u;8788const std::uint64_t p0 = u_lo * v_lo;89const std::uint64_t p1 = u_lo * v_hi;90const std::uint64_t p2 = u_hi * v_lo;91const std::uint64_t p3 = u_hi * v_hi;9293const std::uint64_t p0_hi = p0 >> 32u;94const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu;95const std::uint64_t p1_hi = p1 >> 32u;96const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu;97const std::uint64_t p2_hi = p2 >> 32u;9899std::uint64_t Q = p0_hi + p1_lo + p2_lo;100101// The full product might now be computed as102//103// p_hi = p3 + p2_hi + p1_hi + (Q >> 32)104// p_lo = p0_lo + (Q << 32)105//106// But in this particular case here, the full p_lo is not required.107// Effectively we only need to add the highest bit in p_lo to p_hi (and108// Q_hi + 1 does not overflow).109110Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up111112const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u);113114return {h, x.e + y.e + 64};115}116117/*!118@brief normalize x such that the significand is >= 2^(q-1)119@pre x.f != 0120*/121static diyfp normalize(diyfp x) noexcept {122123while ((x.f >> 63u) == 0) {124x.f <<= 1u;125x.e--;126}127128return x;129}130131/*!132@brief normalize x such that the result has the exponent E133@pre e >= x.e and the upper e - x.e bits of x.f must be zero.134*/135static diyfp normalize_to(const diyfp &x,136const int target_exponent) noexcept {137const int delta = x.e - target_exponent;138139return {x.f << delta, target_exponent};140}141};142143struct boundaries {144diyfp w;145diyfp minus;146diyfp plus;147};148149/*!150Compute the (normalized) diyfp representing the input number 'value' and its151boundaries.152@pre value must be finite and positive153*/154template <typename FloatType> boundaries compute_boundaries(FloatType value) {155156// Convert the IEEE representation into a diyfp.157//158// If v is denormal:159// value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1))160// If v is normalized:161// value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1))162163static_assert(std::numeric_limits<FloatType>::is_iec559,164"internal error: dtoa_short requires an IEEE-754 "165"floating-point implementation");166167constexpr int kPrecision =168std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit)169constexpr int kBias =170std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1);171constexpr int kMinExp = 1 - kBias;172constexpr std::uint64_t kHiddenBit = std::uint64_t{1}173<< (kPrecision - 1); // = 2^(p-1)174175using bits_type = typename std::conditional<kPrecision == 24, std::uint32_t,176std::uint64_t>::type;177178const std::uint64_t bits = reinterpret_bits<bits_type>(value);179const std::uint64_t E = bits >> (kPrecision - 1);180const std::uint64_t F = bits & (kHiddenBit - 1);181182const bool is_denormal = E == 0;183const diyfp v = is_denormal184? diyfp(F, kMinExp)185: diyfp(F + kHiddenBit, static_cast<int>(E) - kBias);186187// Compute the boundaries m- and m+ of the floating-point value188// v = f * 2^e.189//190// Determine v- and v+, the floating-point predecessor and successor if v,191// respectively.192//193// v- = v - 2^e if f != 2^(p-1) or e == e_min (A)194// = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B)195//196// v+ = v + 2^e197//198// Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_199// between m- and m+ round to v, regardless of how the input rounding200// algorithm breaks ties.201//202// ---+-------------+-------------+-------------+-------------+--- (A)203// v- m- v m+ v+204//205// -----------------+------+------+-------------+-------------+--- (B)206// v- m- v m+ v+207208const bool lower_boundary_is_closer = F == 0 && E > 1;209const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1);210const diyfp m_minus = lower_boundary_is_closer211? diyfp(4 * v.f - 1, v.e - 2) // (B)212: diyfp(2 * v.f - 1, v.e - 1); // (A)213214// Determine the normalized w+ = m+.215const diyfp w_plus = diyfp::normalize(m_plus);216217// Determine w- = m- such that e_(w-) = e_(w+).218const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e);219220return {diyfp::normalize(v), w_minus, w_plus};221}222223// Given normalized diyfp w, Grisu needs to find a (normalized) cached224// power-of-ten c, such that the exponent of the product c * w = f * 2^e lies225// within a certain range [alpha, gamma] (Definition 3.2 from [1])226//227// alpha <= e = e_c + e_w + q <= gamma228//229// or230//231// f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q232// <= f_c * f_w * 2^gamma233//234// Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies235//236// 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma237//238// or239//240// 2^(q - 2 + alpha) <= c * w < 2^(q + gamma)241//242// The choice of (alpha,gamma) determines the size of the table and the form of243// the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well244// in practice:245//246// The idea is to cut the number c * w = f * 2^e into two parts, which can be247// processed independently: An integral part p1, and a fractional part p2:248//249// f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e250// = (f div 2^-e) + (f mod 2^-e) * 2^e251// = p1 + p2 * 2^e252//253// The conversion of p1 into decimal form requires a series of divisions and254// modulos by (a power of) 10. These operations are faster for 32-bit than for255// 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be256// achieved by choosing257//258// -e >= 32 or e <= -32 := gamma259//260// In order to convert the fractional part261//262// p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ...263//264// into decimal form, the fraction is repeatedly multiplied by 10 and the digits265// d[-i] are extracted in order:266//267// (10 * p2) div 2^-e = d[-1]268// (10 * p2) mod 2^-e = d[-2] / 10^1 + ...269//270// The multiplication by 10 must not overflow. It is sufficient to choose271//272// 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64.273//274// Since p2 = f mod 2^-e < 2^-e,275//276// -e <= 60 or e >= -60 := alpha277278constexpr int kAlpha = -60;279constexpr int kGamma = -32;280281struct cached_power // c = f * 2^e ~= 10^k282{283std::uint64_t f;284int e;285int k;286};287288/*!289For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached290power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c291satisfies (Definition 3.2 from [1])292alpha <= e_c + e + q <= gamma.293*/294inline cached_power get_cached_power_for_binary_exponent(int e) {295// Now296//297// alpha <= e_c + e + q <= gamma (1)298// ==> f_c * 2^alpha <= c * 2^e * 2^q299//300// and since the c's are normalized, 2^(q-1) <= f_c,301//302// ==> 2^(q - 1 + alpha) <= c * 2^(e + q)303// ==> 2^(alpha - e - 1) <= c304//305// If c were an exact power of ten, i.e. c = 10^k, one may determine k as306//307// k = ceil( log_10( 2^(alpha - e - 1) ) )308// = ceil( (alpha - e - 1) * log_10(2) )309//310// From the paper:311// "In theory the result of the procedure could be wrong since c is rounded,312// and the computation itself is approximated [...]. In practice, however,313// this simple function is sufficient."314//315// For IEEE double precision floating-point numbers converted into316// normalized diyfp's w = f * 2^e, with q = 64,317//318// e >= -1022 (min IEEE exponent)319// -52 (p - 1)320// -52 (p - 1, possibly normalize denormal IEEE numbers)321// -11 (normalize the diyfp)322// = -1137323//324// and325//326// e <= +1023 (max IEEE exponent)327// -52 (p - 1)328// -11 (normalize the diyfp)329// = 960330//331// This binary exponent range [-1137,960] results in a decimal exponent332// range [-307,324]. One does not need to store a cached power for each333// k in this range. For each such k it suffices to find a cached power334// such that the exponent of the product lies in [alpha,gamma].335// This implies that the difference of the decimal exponents of adjacent336// table entries must be less than or equal to337//338// floor( (gamma - alpha) * log_10(2) ) = 8.339//340// (A smaller distance gamma-alpha would require a larger table.)341342// NB:343// Actually this function returns c, such that -60 <= e_c + e + 64 <= -34.344345constexpr int kCachedPowersMinDecExp = -300;346constexpr int kCachedPowersDecStep = 8;347348static constexpr std::array<cached_power, 79> kCachedPowers = {{349{0xAB70FE17C79AC6CA, -1060, -300}, {0xFF77B1FCBEBCDC4F, -1034, -292},350{0xBE5691EF416BD60C, -1007, -284}, {0x8DD01FAD907FFC3C, -980, -276},351{0xD3515C2831559A83, -954, -268}, {0x9D71AC8FADA6C9B5, -927, -260},352{0xEA9C227723EE8BCB, -901, -252}, {0xAECC49914078536D, -874, -244},353{0x823C12795DB6CE57, -847, -236}, {0xC21094364DFB5637, -821, -228},354{0x9096EA6F3848984F, -794, -220}, {0xD77485CB25823AC7, -768, -212},355{0xA086CFCD97BF97F4, -741, -204}, {0xEF340A98172AACE5, -715, -196},356{0xB23867FB2A35B28E, -688, -188}, {0x84C8D4DFD2C63F3B, -661, -180},357{0xC5DD44271AD3CDBA, -635, -172}, {0x936B9FCEBB25C996, -608, -164},358{0xDBAC6C247D62A584, -582, -156}, {0xA3AB66580D5FDAF6, -555, -148},359{0xF3E2F893DEC3F126, -529, -140}, {0xB5B5ADA8AAFF80B8, -502, -132},360{0x87625F056C7C4A8B, -475, -124}, {0xC9BCFF6034C13053, -449, -116},361{0x964E858C91BA2655, -422, -108}, {0xDFF9772470297EBD, -396, -100},362{0xA6DFBD9FB8E5B88F, -369, -92}, {0xF8A95FCF88747D94, -343, -84},363{0xB94470938FA89BCF, -316, -76}, {0x8A08F0F8BF0F156B, -289, -68},364{0xCDB02555653131B6, -263, -60}, {0x993FE2C6D07B7FAC, -236, -52},365{0xE45C10C42A2B3B06, -210, -44}, {0xAA242499697392D3, -183, -36},366{0xFD87B5F28300CA0E, -157, -28}, {0xBCE5086492111AEB, -130, -20},367{0x8CBCCC096F5088CC, -103, -12}, {0xD1B71758E219652C, -77, -4},368{0x9C40000000000000, -50, 4}, {0xE8D4A51000000000, -24, 12},369{0xAD78EBC5AC620000, 3, 20}, {0x813F3978F8940984, 30, 28},370{0xC097CE7BC90715B3, 56, 36}, {0x8F7E32CE7BEA5C70, 83, 44},371{0xD5D238A4ABE98068, 109, 52}, {0x9F4F2726179A2245, 136, 60},372{0xED63A231D4C4FB27, 162, 68}, {0xB0DE65388CC8ADA8, 189, 76},373{0x83C7088E1AAB65DB, 216, 84}, {0xC45D1DF942711D9A, 242, 92},374{0x924D692CA61BE758, 269, 100}, {0xDA01EE641A708DEA, 295, 108},375{0xA26DA3999AEF774A, 322, 116}, {0xF209787BB47D6B85, 348, 124},376{0xB454E4A179DD1877, 375, 132}, {0x865B86925B9BC5C2, 402, 140},377{0xC83553C5C8965D3D, 428, 148}, {0x952AB45CFA97A0B3, 455, 156},378{0xDE469FBD99A05FE3, 481, 164}, {0xA59BC234DB398C25, 508, 172},379{0xF6C69A72A3989F5C, 534, 180}, {0xB7DCBF5354E9BECE, 561, 188},380{0x88FCF317F22241E2, 588, 196}, {0xCC20CE9BD35C78A5, 614, 204},381{0x98165AF37B2153DF, 641, 212}, {0xE2A0B5DC971F303A, 667, 220},382{0xA8D9D1535CE3B396, 694, 228}, {0xFB9B7CD9A4A7443C, 720, 236},383{0xBB764C4CA7A44410, 747, 244}, {0x8BAB8EEFB6409C1A, 774, 252},384{0xD01FEF10A657842C, 800, 260}, {0x9B10A4E5E9913129, 827, 268},385{0xE7109BFBA19C0C9D, 853, 276}, {0xAC2820D9623BF429, 880, 284},386{0x80444B5E7AA7CF85, 907, 292}, {0xBF21E44003ACDD2D, 933, 300},387{0x8E679C2F5E44FF8F, 960, 308}, {0xD433179D9C8CB841, 986, 316},388{0x9E19DB92B4E31BA9, 1013, 324},389}};390391// This computation gives exactly the same results for k as392// k = ceil((kAlpha - e - 1) * 0.30102999566398114)393// for |e| <= 1500, but doesn't require floating-point operations.394// NB: log_10(2) ~= 78913 / 2^18395const int f = kAlpha - e - 1;396const int k = (f * 78913) / (1 << 18) + static_cast<int>(f > 0);397398const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) /399kCachedPowersDecStep;400401const cached_power cached = kCachedPowers[static_cast<std::size_t>(index)];402403return cached;404}405406/*!407For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k.408For n == 0, returns 1 and sets pow10 := 1.409*/410inline int find_largest_pow10(const std::uint32_t n, std::uint32_t &pow10) {411// LCOV_EXCL_START412if (n >= 1000000000) {413pow10 = 1000000000;414return 10;415}416// LCOV_EXCL_STOP417else if (n >= 100000000) {418pow10 = 100000000;419return 9;420} else if (n >= 10000000) {421pow10 = 10000000;422return 8;423} else if (n >= 1000000) {424pow10 = 1000000;425return 7;426} else if (n >= 100000) {427pow10 = 100000;428return 6;429} else if (n >= 10000) {430pow10 = 10000;431return 5;432} else if (n >= 1000) {433pow10 = 1000;434return 4;435} else if (n >= 100) {436pow10 = 100;437return 3;438} else if (n >= 10) {439pow10 = 10;440return 2;441} else {442pow10 = 1;443return 1;444}445}446447inline void grisu2_round(char *buf, int len, std::uint64_t dist,448std::uint64_t delta, std::uint64_t rest,449std::uint64_t ten_k) {450451// <--------------------------- delta ---->452// <---- dist --------->453// --------------[------------------+-------------------]--------------454// M- w M+455//456// ten_k457// <------>458// <---- rest ---->459// --------------[------------------+----+--------------]--------------460// w V461// = buf * 10^k462//463// ten_k represents a unit-in-the-last-place in the decimal representation464// stored in buf.465// Decrement buf by ten_k while this takes buf closer to w.466467// The tests are written in this order to avoid overflow in unsigned468// integer arithmetic.469470while (rest < dist && delta - rest >= ten_k &&471(rest + ten_k < dist || dist - rest > rest + ten_k - dist)) {472buf[len - 1]--;473rest += ten_k;474}475}476477/*!478Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+.479M- and M+ must be normalized and share the same exponent -60 <= e <= -32.480*/481inline void grisu2_digit_gen(char *buffer, int &length, int &decimal_exponent,482diyfp M_minus, diyfp w, diyfp M_plus) {483static_assert(kAlpha >= -60, "internal error");484static_assert(kGamma <= -32, "internal error");485486// Generates the digits (and the exponent) of a decimal floating-point487// number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's488// w, M- and M+ share the same exponent e, which satisfies alpha <= e <=489// gamma.490//491// <--------------------------- delta ---->492// <---- dist --------->493// --------------[------------------+-------------------]--------------494// M- w M+495//496// Grisu2 generates the digits of M+ from left to right and stops as soon as497// V is in [M-,M+].498499std::uint64_t delta =500diyfp::sub(M_plus, M_minus)501.f; // (significand of (M+ - M-), implicit exponent is e)502std::uint64_t dist =503diyfp::sub(M_plus, w)504.f; // (significand of (M+ - w ), implicit exponent is e)505506// Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0):507//508// M+ = f * 2^e509// = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e510// = ((p1 ) * 2^-e + (p2 )) * 2^e511// = p1 + p2 * 2^e512513const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e);514515auto p1 = static_cast<std::uint32_t>(516M_plus.f >>517-one.e); // p1 = f div 2^-e (Since -e >= 32, p1 fits into a 32-bit int.)518std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e519520// 1)521//522// Generate the digits of the integral part p1 = d[n-1]...d[1]d[0]523524std::uint32_t pow10;525const int k = find_largest_pow10(p1, pow10);526527// 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1)528//529// p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1))530// = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1))531//532// M+ = p1 + p2 * 2^e533// = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e534// = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e535// = d[k-1] * 10^(k-1) + ( rest) * 2^e536//537// Now generate the digits d[n] of p1 from left to right (n = k-1,...,0)538//539// p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0]540//541// but stop as soon as542//543// rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e544545int n = k;546while (n > 0) {547// Invariants:548// M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k)549// pow10 = 10^(n-1) <= p1 < 10^n550//551const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1)552const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1)553//554// M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e555// = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e)556//557buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d558//559// M+ = buffer * 10^(n-1) + (r + p2 * 2^e)560//561p1 = r;562n--;563//564// M+ = buffer * 10^n + (p1 + p2 * 2^e)565// pow10 = 10^n566//567568// Now check if enough digits have been generated.569// Compute570//571// p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e572//573// Note:574// Since rest and delta share the same exponent e, it suffices to575// compare the significands.576const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2;577if (rest <= delta) {578// V = buffer * 10^n, with M- <= V <= M+.579580decimal_exponent += n;581582// We may now just stop. But instead look if the buffer could be583// decremented to bring V closer to w.584//585// pow10 = 10^n is now 1 ulp in the decimal representation V.586// The rounding procedure works with diyfp's with an implicit587// exponent of e.588//589// 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e590//591const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e;592grisu2_round(buffer, length, dist, delta, rest, ten_n);593594return;595}596597pow10 /= 10;598//599// pow10 = 10^(n-1) <= p1 < 10^n600// Invariants restored.601}602603// 2)604//605// The digits of the integral part have been generated:606//607// M+ = d[k-1]...d[1]d[0] + p2 * 2^e608// = buffer + p2 * 2^e609//610// Now generate the digits of the fractional part p2 * 2^e.611//612// Note:613// No decimal point is generated: the exponent is adjusted instead.614//615// p2 actually represents the fraction616//617// p2 * 2^e618// = p2 / 2^-e619// = d[-1] / 10^1 + d[-2] / 10^2 + ...620//621// Now generate the digits d[-m] of p1 from left to right (m = 1,2,...)622//623// p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m624// + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...)625//626// using627//628// 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e)629// = ( d) * 2^-e + ( r)630//631// or632// 10^m * p2 * 2^e = d + r * 2^e633//634// i.e.635//636// M+ = buffer + p2 * 2^e637// = buffer + 10^-m * (d + r * 2^e)638// = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e639//640// and stop as soon as 10^-m * r * 2^e <= delta * 2^e641642int m = 0;643for (;;) {644// Invariant:645// M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...)646// * 2^e647// = buffer * 10^-m + 10^-m * (p2 )648// * 2^e = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e =649// buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e +650// (10*p2 mod 2^-e)) * 2^e651//652p2 *= 10;653const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e654const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e655//656// M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e657// = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e))658// = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e659//660buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d661//662// M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e663//664p2 = r;665m++;666//667// M+ = buffer * 10^-m + 10^-m * p2 * 2^e668// Invariant restored.669670// Check if enough digits have been generated.671//672// 10^-m * p2 * 2^e <= delta * 2^e673// p2 * 2^e <= 10^m * delta * 2^e674// p2 <= 10^m * delta675delta *= 10;676dist *= 10;677if (p2 <= delta) {678break;679}680}681682// V = buffer * 10^-m, with M- <= V <= M+.683684decimal_exponent -= m;685686// 1 ulp in the decimal representation is now 10^-m.687// Since delta and dist are now scaled by 10^m, we need to do the688// same with ulp in order to keep the units in sync.689//690// 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e691//692const std::uint64_t ten_m = one.f;693grisu2_round(buffer, length, dist, delta, p2, ten_m);694695// By construction this algorithm generates the shortest possible decimal696// number (Loitsch, Theorem 6.2) which rounds back to w.697// For an input number of precision p, at least698//699// N = 1 + ceil(p * log_10(2))700//701// decimal digits are sufficient to identify all binary floating-point702// numbers (Matula, "In-and-Out conversions").703// This implies that the algorithm does not produce more than N decimal704// digits.705//706// N = 17 for p = 53 (IEEE double precision)707// N = 9 for p = 24 (IEEE single precision)708}709710/*!711v = buf * 10^decimal_exponent712len is the length of the buffer (number of decimal digits)713The buffer must be large enough, i.e. >= max_digits10.714*/715inline void grisu2_core(char *buf, int &len, int &decimal_exponent, diyfp m_minus,716diyfp v, diyfp m_plus) {717718// --------(-----------------------+-----------------------)-------- (A)719// m- v m+720//721// --------------------(-----------+-----------------------)-------- (B)722// m- v m+723//724// First scale v (and m- and m+) such that the exponent is in the range725// [alpha, gamma].726727const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e);728729const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k730731// The exponent of the products is = v.e + c_minus_k.e + q and is in the range732// [alpha,gamma]733const diyfp w = diyfp::mul(v, c_minus_k);734const diyfp w_minus = diyfp::mul(m_minus, c_minus_k);735const diyfp w_plus = diyfp::mul(m_plus, c_minus_k);736737// ----(---+---)---------------(---+---)---------------(---+---)----738// w- w w+739// = c*m- = c*v = c*m+740//741// diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and742// w+ are now off by a small amount.743// In fact:744//745// w - v * 10^k < 1 ulp746//747// To account for this inaccuracy, add resp. subtract 1 ulp.748//749// --------+---[---------------(---+---)---------------]---+--------750// w- M- w M+ w+751//752// Now any number in [M-, M+] (bounds included) will round to w when input,753// regardless of how the input rounding algorithm breaks ties.754//755// And digit_gen generates the shortest possible such number in [M-, M+].756// Note that this does not mean that Grisu2 always generates the shortest757// possible number in the interval (m-, m+).758const diyfp M_minus(w_minus.f + 1, w_minus.e);759const diyfp M_plus(w_plus.f - 1, w_plus.e);760761decimal_exponent = -cached.k; // = -(-k) = k762763grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus);764}765766/*!767v = buf * 10^decimal_exponent768len is the length of the buffer (number of decimal digits)769The buffer must be large enough, i.e. >= max_digits10.770*/771template <typename FloatType>772void grisu2_wrap(char *buf, int &len, int &decimal_exponent, FloatType value) {773static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3,774"internal error: not enough precision");775776// If the neighbors (and boundaries) of 'value' are always computed for777// double-precision numbers, all float's can be recovered using strtod (and778// strtof). However, the resulting decimal representations are not exactly779// "short".780//781// The documentation for 'std::to_chars'782// (https://en.cppreference.com/w/cpp/utility/to_chars) says "value is783// converted to a string as if by std::sprintf in the default ("C") locale"784// and since sprintf promotes float's to double's, I think this is exactly785// what 'std::to_chars' does. On the other hand, the documentation for786// 'std::to_chars' requires that "parsing the representation using the787// corresponding std::from_chars function recovers value exactly". That788// indicates that single precision floating-point numbers should be recovered789// using 'std::strtof'.790//791// NB: If the neighbors are computed for single-precision numbers, there is a792// single float793// (7.0385307e-26f) which can't be recovered using strtod. The resulting794// double precision value is off by 1 ulp.795#if 0796const boundaries w = compute_boundaries(static_cast<double>(value));797#else798const boundaries w = compute_boundaries(value);799#endif800801grisu2_core(buf, len, decimal_exponent, w.minus, w.w, w.plus);802}803804/*!805@brief appends a decimal representation of e to buf806@return a pointer to the element following the exponent.807@pre -1000 < e < 1000808*/809inline char *append_exponent(char *buf, int e) {810811if (e < 0) {812e = -e;813*buf++ = '-';814} else {815*buf++ = '+';816}817818auto k = static_cast<std::uint32_t>(e);819if (k < 10) {820// Always print at least two digits in the exponent.821// This is for compatibility with printf("%g").822*buf++ = '0';823*buf++ = static_cast<char>('0' + k);824} else if (k < 100) {825*buf++ = static_cast<char>('0' + k / 10);826k %= 10;827*buf++ = static_cast<char>('0' + k);828} else {829*buf++ = static_cast<char>('0' + k / 100);830k %= 100;831*buf++ = static_cast<char>('0' + k / 10);832k %= 10;833*buf++ = static_cast<char>('0' + k);834}835836return buf;837}838839/*!840@brief prettify v = buf * 10^decimal_exponent841If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point842notation. Otherwise it will be printed in exponential notation.843@pre min_exp < 0844@pre max_exp > 0845*/846inline char *format_buffer(char *buf, int len, int decimal_exponent,847int min_exp, int max_exp) {848849const int k = len;850const int n = len + decimal_exponent;851852// v = buf * 10^(n-k)853// k is the length of the buffer (number of decimal digits)854// n is the position of the decimal point relative to the start of the buffer.855856if (k <= n && n <= max_exp) {857// digits[000]858// len <= max_exp + 2859860std::memset(buf + k, '0', static_cast<size_t>(n) - static_cast<size_t>(k));861return buf + (static_cast<size_t>(n));862}863864if (0 < n && n <= max_exp) {865// dig.its866// len <= max_digits10 + 1867std::memmove(buf + (static_cast<size_t>(n) + 1), buf + n,868static_cast<size_t>(k) - static_cast<size_t>(n));869buf[n] = '.';870return buf + (static_cast<size_t>(k) + 1U);871}872873if (min_exp < n && n <= 0) {874// 0.[000]digits875// len <= 2 + (-min_exp - 1) + max_digits10876877std::memmove(buf + (2 + static_cast<size_t>(-n)), buf,878static_cast<size_t>(k));879buf[0] = '0';880buf[1] = '.';881std::memset(buf + 2, '0', static_cast<size_t>(-n));882return buf + (2U + static_cast<size_t>(-n) + static_cast<size_t>(k));883}884885if (k == 1) {886// dE+123887// len <= 1 + 5888889buf += 1;890} else {891// d.igitsE+123892// len <= max_digits10 + 1 + 5893894std::memmove(buf + 2, buf + 1, static_cast<size_t>(k) - 1);895buf[1] = '.';896buf += 1 + static_cast<size_t>(k);897}898899*buf++ = 'e';900return append_exponent(buf, n - 1);901}902903/*!904The format of the resulting decimal representation is similar to printf's %g905format. Returns an iterator pointing past-the-end of the decimal representation.906@note The input number must be finite, i.e. NaN's and Inf's are not supported.907@note The buffer must be large enough.908@note The result is NOT null-terminated.909*/910template <typename FloatType>911char *to_chars(char *first, FloatType value) {912bool negative = std::signbit(value);913if (negative) {914value = -value;915*first++ = '-';916}917if (value == 0) // +-0918{919*first++ = '0';920return first;921}922// Compute v = buffer * 10^decimal_exponent.923// The decimal digits are stored in the buffer, which needs to be interpreted924// as an unsigned decimal integer.925// len is the length of the buffer, i.e. the number of decimal digits.926int len = 0;927int decimal_exponent = 0;928grisu2_wrap(first, len, decimal_exponent, value);929// Format the buffer like printf("%.*g", prec, value)930constexpr int kMinExp = -4;931constexpr int kMaxExp = std::numeric_limits<double>::digits10;932933return format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp);934}935} // namespace grisu2936937938