to_chars.hpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  1. #pragma once
  2. #include <cassert> // assert
  3. #include <ciso646> // or, and, not
  4. #include <cmath> // signbit, isfinite
  5. #include <cstdint> // intN_t, uintN_t
  6. #include <cstring> // memcpy, memmove
  7. namespace nlohmann
  8. {
  9. namespace detail
  10. {
  11. /*!
  12. @brief implements the Grisu2 algorithm for binary to decimal floating-point
  13. conversion.
  14. This implementation is a slightly modified version of the reference
  15. implementation which may be obtained from
  16. http://florian.loitsch.com/publications (bench.tar.gz).
  17. The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch.
  18. For a detailed description of the algorithm see:
  19. [1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with
  20. Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming
  21. Language Design and Implementation, PLDI 2010
  22. [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately",
  23. Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language
  24. Design and Implementation, PLDI 1996
  25. */
  26. namespace dtoa_impl
  27. {
  28. template <typename Target, typename Source>
  29. Target reinterpret_bits(const Source source)
  30. {
  31. static_assert(sizeof(Target) == sizeof(Source), "size mismatch");
  32. Target target;
  33. std::memcpy(&target, &source, sizeof(Source));
  34. return target;
  35. }
  36. struct diyfp // f * 2^e
  37. {
  38. static constexpr int kPrecision = 64; // = q
  39. uint64_t f;
  40. int e;
  41. constexpr diyfp() noexcept : f(0), e(0) {}
  42. constexpr diyfp(uint64_t f_, int e_) noexcept : f(f_), e(e_) {}
  43. /*!
  44. @brief returns x - y
  45. @pre x.e == y.e and x.f >= y.f
  46. */
  47. static diyfp sub(const diyfp& x, const diyfp& y) noexcept
  48. {
  49. assert(x.e == y.e);
  50. assert(x.f >= y.f);
  51. return diyfp(x.f - y.f, x.e);
  52. }
  53. /*!
  54. @brief returns x * y
  55. @note The result is rounded. (Only the upper q bits are returned.)
  56. */
  57. static diyfp mul(const diyfp& x, const diyfp& y) noexcept
  58. {
  59. static_assert(kPrecision == 64, "internal error");
  60. // Computes:
  61. // f = round((x.f * y.f) / 2^q)
  62. // e = x.e + y.e + q
  63. // Emulate the 64-bit * 64-bit multiplication:
  64. //
  65. // p = u * v
  66. // = (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 )) + 2^64 (u_hi v_hi )
  68. // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 )
  69. // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 )
  70. // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3)
  71. // = (p0_lo ) + 2^32 (Q ) + 2^64 (H )
  72. // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H )
  73. //
  74. // (Since Q might be larger than 2^32 - 1)
  75. //
  76. // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H)
  77. //
  78. // (Q_hi + H does not overflow a 64-bit int)
  79. //
  80. // = p_lo + 2^64 p_hi
  81. const uint64_t u_lo = x.f & 0xFFFFFFFF;
  82. const uint64_t u_hi = x.f >> 32;
  83. const uint64_t v_lo = y.f & 0xFFFFFFFF;
  84. const uint64_t v_hi = y.f >> 32;
  85. const uint64_t p0 = u_lo * v_lo;
  86. const uint64_t p1 = u_lo * v_hi;
  87. const uint64_t p2 = u_hi * v_lo;
  88. const uint64_t p3 = u_hi * v_hi;
  89. const uint64_t p0_hi = p0 >> 32;
  90. const uint64_t p1_lo = p1 & 0xFFFFFFFF;
  91. const uint64_t p1_hi = p1 >> 32;
  92. const uint64_t p2_lo = p2 & 0xFFFFFFFF;
  93. const uint64_t p2_hi = p2 >> 32;
  94. uint64_t Q = p0_hi + p1_lo + p2_lo;
  95. // The full product might now be computed as
  96. //
  97. // p_hi = p3 + p2_hi + p1_hi + (Q >> 32)
  98. // p_lo = p0_lo + (Q << 32)
  99. //
  100. // But in this particular case here, the full p_lo is not required.
  101. // Effectively we only need to add the highest bit in p_lo to p_hi (and
  102. // Q_hi + 1 does not overflow).
  103. Q += uint64_t{1} << (64 - 32 - 1); // round, ties up
  104. const uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32);
  105. return diyfp(h, x.e + y.e + 64);
  106. }
  107. /*!
  108. @brief normalize x such that the significand is >= 2^(q-1)
  109. @pre x.f != 0
  110. */
  111. static diyfp normalize(diyfp x) noexcept
  112. {
  113. assert(x.f != 0);
  114. while ((x.f >> 63) == 0)
  115. {
  116. x.f <<= 1;
  117. x.e--;
  118. }
  119. return x;
  120. }
  121. /*!
  122. @brief normalize x such that the result has the exponent E
  123. @pre e >= x.e and the upper e - x.e bits of x.f must be zero.
  124. */
  125. static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept
  126. {
  127. const int delta = x.e - target_exponent;
  128. assert(delta >= 0);
  129. assert(((x.f << delta) >> delta) == x.f);
  130. return diyfp(x.f << delta, target_exponent);
  131. }
  132. };
  133. struct boundaries
  134. {
  135. diyfp w;
  136. diyfp minus;
  137. diyfp plus;
  138. };
  139. /*!
  140. Compute the (normalized) diyfp representing the input number 'value' and its
  141. boundaries.
  142. @pre value must be finite and positive
  143. */
  144. template <typename FloatType>
  145. boundaries compute_boundaries(FloatType value)
  146. {
  147. assert(std::isfinite(value));
  148. assert(value > 0);
  149. // Convert the IEEE representation into a diyfp.
  150. //
  151. // If v is denormal:
  152. // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1))
  153. // If v is normalized:
  154. // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1))
  155. static_assert(std::numeric_limits<FloatType>::is_iec559,
  156. "internal error: dtoa_short requires an IEEE-754 floating-point implementation");
  157. constexpr int kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit)
  158. constexpr int kBias = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1);
  159. constexpr int kMinExp = 1 - kBias;
  160. constexpr uint64_t kHiddenBit = uint64_t{1} << (kPrecision - 1); // = 2^(p-1)
  161. using bits_type = typename std::conditional< kPrecision == 24, uint32_t, uint64_t >::type;
  162. const uint64_t bits = reinterpret_bits<bits_type>(value);
  163. const uint64_t E = bits >> (kPrecision - 1);
  164. const uint64_t F = bits & (kHiddenBit - 1);
  165. const bool is_denormal = (E == 0);
  166. const diyfp v = is_denormal
  167. ? diyfp(F, kMinExp)
  168. : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias);
  169. // Compute the boundaries m- and m+ of the floating-point value
  170. // v = f * 2^e.
  171. //
  172. // Determine v- and v+, the floating-point predecessor and successor if v,
  173. // respectively.
  174. //
  175. // v- = v - 2^e if f != 2^(p-1) or e == e_min (A)
  176. // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B)
  177. //
  178. // v+ = v + 2^e
  179. //
  180. // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_
  181. // between m- and m+ round to v, regardless of how the input rounding
  182. // algorithm breaks ties.
  183. //
  184. // ---+-------------+-------------+-------------+-------------+--- (A)
  185. // v- m- v m+ v+
  186. //
  187. // -----------------+------+------+-------------+-------------+--- (B)
  188. // v- m- v m+ v+
  189. const bool lower_boundary_is_closer = (F == 0 and E > 1);
  190. const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1);
  191. const diyfp m_minus = lower_boundary_is_closer
  192. ? diyfp(4 * v.f - 1, v.e - 2) // (B)
  193. : diyfp(2 * v.f - 1, v.e - 1); // (A)
  194. // Determine the normalized w+ = m+.
  195. const diyfp w_plus = diyfp::normalize(m_plus);
  196. // Determine w- = m- such that e_(w-) = e_(w+).
  197. const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e);
  198. return {diyfp::normalize(v), w_minus, w_plus};
  199. }
  200. // Given normalized diyfp w, Grisu needs to find a (normalized) cached
  201. // power-of-ten c, such that the exponent of the product c * w = f * 2^e lies
  202. // within a certain range [alpha, gamma] (Definition 3.2 from [1])
  203. //
  204. // alpha <= e = e_c + e_w + q <= gamma
  205. //
  206. // or
  207. //
  208. // f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q
  209. // <= f_c * f_w * 2^gamma
  210. //
  211. // Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies
  212. //
  213. // 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma
  214. //
  215. // or
  216. //
  217. // 2^(q - 2 + alpha) <= c * w < 2^(q + gamma)
  218. //
  219. // The choice of (alpha,gamma) determines the size of the table and the form of
  220. // the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well
  221. // in practice:
  222. //
  223. // The idea is to cut the number c * w = f * 2^e into two parts, which can be
  224. // processed independently: An integral part p1, and a fractional part p2:
  225. //
  226. // f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e
  227. // = (f div 2^-e) + (f mod 2^-e) * 2^e
  228. // = p1 + p2 * 2^e
  229. //
  230. // The conversion of p1 into decimal form requires a series of divisions and
  231. // modulos by (a power of) 10. These operations are faster for 32-bit than for
  232. // 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be
  233. // achieved by choosing
  234. //
  235. // -e >= 32 or e <= -32 := gamma
  236. //
  237. // In order to convert the fractional part
  238. //
  239. // p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ...
  240. //
  241. // into decimal form, the fraction is repeatedly multiplied by 10 and the digits
  242. // d[-i] are extracted in order:
  243. //
  244. // (10 * p2) div 2^-e = d[-1]
  245. // (10 * p2) mod 2^-e = d[-2] / 10^1 + ...
  246. //
  247. // The multiplication by 10 must not overflow. It is sufficient to choose
  248. //
  249. // 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64.
  250. //
  251. // Since p2 = f mod 2^-e < 2^-e,
  252. //
  253. // -e <= 60 or e >= -60 := alpha
  254. constexpr int kAlpha = -60;
  255. constexpr int kGamma = -32;
  256. struct cached_power // c = f * 2^e ~= 10^k
  257. {
  258. uint64_t f;
  259. int e;
  260. int k;
  261. };
  262. /*!
  263. For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached
  264. power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c
  265. satisfies (Definition 3.2 from [1])
  266. alpha <= e_c + e + q <= gamma.
  267. */
  268. inline cached_power get_cached_power_for_binary_exponent(int e)
  269. {
  270. // Now
  271. //
  272. // alpha <= e_c + e + q <= gamma (1)
  273. // ==> f_c * 2^alpha <= c * 2^e * 2^q
  274. //
  275. // and since the c's are normalized, 2^(q-1) <= f_c,
  276. //
  277. // ==> 2^(q - 1 + alpha) <= c * 2^(e + q)
  278. // ==> 2^(alpha - e - 1) <= c
  279. //
  280. // If c were an exakt power of ten, i.e. c = 10^k, one may determine k as
  281. //
  282. // k = ceil( log_10( 2^(alpha - e - 1) ) )
  283. // = ceil( (alpha - e - 1) * log_10(2) )
  284. //
  285. // From the paper:
  286. // "In theory the result of the procedure could be wrong since c is rounded,
  287. // and the computation itself is approximated [...]. In practice, however,
  288. // this simple function is sufficient."
  289. //
  290. // For IEEE double precision floating-point numbers converted into
  291. // normalized diyfp's w = f * 2^e, with q = 64,
  292. //
  293. // e >= -1022 (min IEEE exponent)
  294. // -52 (p - 1)
  295. // -52 (p - 1, possibly normalize denormal IEEE numbers)
  296. // -11 (normalize the diyfp)
  297. // = -1137
  298. //
  299. // and
  300. //
  301. // e <= +1023 (max IEEE exponent)
  302. // -52 (p - 1)
  303. // -11 (normalize the diyfp)
  304. // = 960
  305. //
  306. // This binary exponent range [-1137,960] results in a decimal exponent
  307. // range [-307,324]. One does not need to store a cached power for each
  308. // k in this range. For each such k it suffices to find a cached power
  309. // such that the exponent of the product lies in [alpha,gamma].
  310. // This implies that the difference of the decimal exponents of adjacent
  311. // table entries must be less than or equal to
  312. //
  313. // floor( (gamma - alpha) * log_10(2) ) = 8.
  314. //
  315. // (A smaller distance gamma-alpha would require a larger table.)
  316. // NB:
  317. // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34.
  318. constexpr int kCachedPowersSize = 79;
  319. constexpr int kCachedPowersMinDecExp = -300;
  320. constexpr int kCachedPowersDecStep = 8;
  321. static constexpr cached_power kCachedPowers[] =
  322. {
  323. { 0xAB70FE17C79AC6CA, -1060, -300 },
  324. { 0xFF77B1FCBEBCDC4F, -1034, -292 },
  325. { 0xBE5691EF416BD60C, -1007, -284 },
  326. { 0x8DD01FAD907FFC3C, -980, -276 },
  327. { 0xD3515C2831559A83, -954, -268 },
  328. { 0x9D71AC8FADA6C9B5, -927, -260 },
  329. { 0xEA9C227723EE8BCB, -901, -252 },
  330. { 0xAECC49914078536D, -874, -244 },
  331. { 0x823C12795DB6CE57, -847, -236 },
  332. { 0xC21094364DFB5637, -821, -228 },
  333. { 0x9096EA6F3848984F, -794, -220 },
  334. { 0xD77485CB25823AC7, -768, -212 },
  335. { 0xA086CFCD97BF97F4, -741, -204 },
  336. { 0xEF340A98172AACE5, -715, -196 },
  337. { 0xB23867FB2A35B28E, -688, -188 },
  338. { 0x84C8D4DFD2C63F3B, -661, -180 },
  339. { 0xC5DD44271AD3CDBA, -635, -172 },
  340. { 0x936B9FCEBB25C996, -608, -164 },
  341. { 0xDBAC6C247D62A584, -582, -156 },
  342. { 0xA3AB66580D5FDAF6, -555, -148 },
  343. { 0xF3E2F893DEC3F126, -529, -140 },
  344. { 0xB5B5ADA8AAFF80B8, -502, -132 },
  345. { 0x87625F056C7C4A8B, -475, -124 },
  346. { 0xC9BCFF6034C13053, -449, -116 },
  347. { 0x964E858C91BA2655, -422, -108 },
  348. { 0xDFF9772470297EBD, -396, -100 },
  349. { 0xA6DFBD9FB8E5B88F, -369, -92 },
  350. { 0xF8A95FCF88747D94, -343, -84 },
  351. { 0xB94470938FA89BCF, -316, -76 },
  352. { 0x8A08F0F8BF0F156B, -289, -68 },
  353. { 0xCDB02555653131B6, -263, -60 },
  354. { 0x993FE2C6D07B7FAC, -236, -52 },
  355. { 0xE45C10C42A2B3B06, -210, -44 },
  356. { 0xAA242499697392D3, -183, -36 },
  357. { 0xFD87B5F28300CA0E, -157, -28 },
  358. { 0xBCE5086492111AEB, -130, -20 },
  359. { 0x8CBCCC096F5088CC, -103, -12 },
  360. { 0xD1B71758E219652C, -77, -4 },
  361. { 0x9C40000000000000, -50, 4 },
  362. { 0xE8D4A51000000000, -24, 12 },
  363. { 0xAD78EBC5AC620000, 3, 20 },
  364. { 0x813F3978F8940984, 30, 28 },
  365. { 0xC097CE7BC90715B3, 56, 36 },
  366. { 0x8F7E32CE7BEA5C70, 83, 44 },
  367. { 0xD5D238A4ABE98068, 109, 52 },
  368. { 0x9F4F2726179A2245, 136, 60 },
  369. { 0xED63A231D4C4FB27, 162, 68 },
  370. { 0xB0DE65388CC8ADA8, 189, 76 },
  371. { 0x83C7088E1AAB65DB, 216, 84 },
  372. { 0xC45D1DF942711D9A, 242, 92 },
  373. { 0x924D692CA61BE758, 269, 100 },
  374. { 0xDA01EE641A708DEA, 295, 108 },
  375. { 0xA26DA3999AEF774A, 322, 116 },
  376. { 0xF209787BB47D6B85, 348, 124 },
  377. { 0xB454E4A179DD1877, 375, 132 },
  378. { 0x865B86925B9BC5C2, 402, 140 },
  379. { 0xC83553C5C8965D3D, 428, 148 },
  380. { 0x952AB45CFA97A0B3, 455, 156 },
  381. { 0xDE469FBD99A05FE3, 481, 164 },
  382. { 0xA59BC234DB398C25, 508, 172 },
  383. { 0xF6C69A72A3989F5C, 534, 180 },
  384. { 0xB7DCBF5354E9BECE, 561, 188 },
  385. { 0x88FCF317F22241E2, 588, 196 },
  386. { 0xCC20CE9BD35C78A5, 614, 204 },
  387. { 0x98165AF37B2153DF, 641, 212 },
  388. { 0xE2A0B5DC971F303A, 667, 220 },
  389. { 0xA8D9D1535CE3B396, 694, 228 },
  390. { 0xFB9B7CD9A4A7443C, 720, 236 },
  391. { 0xBB764C4CA7A44410, 747, 244 },
  392. { 0x8BAB8EEFB6409C1A, 774, 252 },
  393. { 0xD01FEF10A657842C, 800, 260 },
  394. { 0x9B10A4E5E9913129, 827, 268 },
  395. { 0xE7109BFBA19C0C9D, 853, 276 },
  396. { 0xAC2820D9623BF429, 880, 284 },
  397. { 0x80444B5E7AA7CF85, 907, 292 },
  398. { 0xBF21E44003ACDD2D, 933, 300 },
  399. { 0x8E679C2F5E44FF8F, 960, 308 },
  400. { 0xD433179D9C8CB841, 986, 316 },
  401. { 0x9E19DB92B4E31BA9, 1013, 324 },
  402. };
  403. // This computation gives exactly the same results for k as
  404. // k = ceil((kAlpha - e - 1) * 0.30102999566398114)
  405. // for |e| <= 1500, but doesn't require floating-point operations.
  406. // NB: log_10(2) ~= 78913 / 2^18
  407. assert(e >= -1500);
  408. assert(e <= 1500);
  409. const int f = kAlpha - e - 1;
  410. const int k = (f * 78913) / (1 << 18) + (f > 0);
  411. const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep;
  412. assert(index >= 0);
  413. assert(index < kCachedPowersSize);
  414. static_cast<void>(kCachedPowersSize); // Fix warning.
  415. const cached_power cached = kCachedPowers[index];
  416. assert(kAlpha <= cached.e + e + 64);
  417. assert(kGamma >= cached.e + e + 64);
  418. return cached;
  419. }
  420. /*!
  421. For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k.
  422. For n == 0, returns 1 and sets pow10 := 1.
  423. */
  424. inline int find_largest_pow10(const uint32_t n, uint32_t& pow10)
  425. {
  426. // LCOV_EXCL_START
  427. if (n >= 1000000000)
  428. {
  429. pow10 = 1000000000;
  430. return 10;
  431. }
  432. // LCOV_EXCL_STOP
  433. else if (n >= 100000000)
  434. {
  435. pow10 = 100000000;
  436. return 9;
  437. }
  438. else if (n >= 10000000)
  439. {
  440. pow10 = 10000000;
  441. return 8;
  442. }
  443. else if (n >= 1000000)
  444. {
  445. pow10 = 1000000;
  446. return 7;
  447. }
  448. else if (n >= 100000)
  449. {
  450. pow10 = 100000;
  451. return 6;
  452. }
  453. else if (n >= 10000)
  454. {
  455. pow10 = 10000;
  456. return 5;
  457. }
  458. else if (n >= 1000)
  459. {
  460. pow10 = 1000;
  461. return 4;
  462. }
  463. else if (n >= 100)
  464. {
  465. pow10 = 100;
  466. return 3;
  467. }
  468. else if (n >= 10)
  469. {
  470. pow10 = 10;
  471. return 2;
  472. }
  473. else
  474. {
  475. pow10 = 1;
  476. return 1;
  477. }
  478. }
  479. inline void grisu2_round(char* buf, int len, uint64_t dist, uint64_t delta,
  480. uint64_t rest, uint64_t ten_k)
  481. {
  482. assert(len >= 1);
  483. assert(dist <= delta);
  484. assert(rest <= delta);
  485. assert(ten_k > 0);
  486. // <--------------------------- delta ---->
  487. // <---- dist --------->
  488. // --------------[------------------+-------------------]--------------
  489. // M- w M+
  490. //
  491. // ten_k
  492. // <------>
  493. // <---- rest ---->
  494. // --------------[------------------+----+--------------]--------------
  495. // w V
  496. // = buf * 10^k
  497. //
  498. // ten_k represents a unit-in-the-last-place in the decimal representation
  499. // stored in buf.
  500. // Decrement buf by ten_k while this takes buf closer to w.
  501. // The tests are written in this order to avoid overflow in unsigned
  502. // integer arithmetic.
  503. while (rest < dist
  504. and delta - rest >= ten_k
  505. and (rest + ten_k < dist or dist - rest > rest + ten_k - dist))
  506. {
  507. assert(buf[len - 1] != '0');
  508. buf[len - 1]--;
  509. rest += ten_k;
  510. }
  511. }
  512. /*!
  513. Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+.
  514. M- and M+ must be normalized and share the same exponent -60 <= e <= -32.
  515. */
  516. inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent,
  517. diyfp M_minus, diyfp w, diyfp M_plus)
  518. {
  519. static_assert(kAlpha >= -60, "internal error");
  520. static_assert(kGamma <= -32, "internal error");
  521. // Generates the digits (and the exponent) of a decimal floating-point
  522. // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's
  523. // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma.
  524. //
  525. // <--------------------------- delta ---->
  526. // <---- dist --------->
  527. // --------------[------------------+-------------------]--------------
  528. // M- w M+
  529. //
  530. // Grisu2 generates the digits of M+ from left to right and stops as soon as
  531. // V is in [M-,M+].
  532. assert(M_plus.e >= kAlpha);
  533. assert(M_plus.e <= kGamma);
  534. uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e)
  535. uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e)
  536. // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0):
  537. //
  538. // M+ = f * 2^e
  539. // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e
  540. // = ((p1 ) * 2^-e + (p2 )) * 2^e
  541. // = p1 + p2 * 2^e
  542. const diyfp one(uint64_t{1} << -M_plus.e, M_plus.e);
  543. uint32_t p1 = static_cast<uint32_t>(M_plus.f >> -one.e); // p1 = f div 2^-e (Since -e >= 32, p1 fits into a 32-bit int.)
  544. uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e
  545. // 1)
  546. //
  547. // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0]
  548. assert(p1 > 0);
  549. uint32_t pow10;
  550. const int k = find_largest_pow10(p1, pow10);
  551. // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1)
  552. //
  553. // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1))
  554. // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1))
  555. //
  556. // M+ = p1 + p2 * 2^e
  557. // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e
  558. // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e
  559. // = d[k-1] * 10^(k-1) + ( rest) * 2^e
  560. //
  561. // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0)
  562. //
  563. // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0]
  564. //
  565. // but stop as soon as
  566. //
  567. // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e
  568. int n = k;
  569. while (n > 0)
  570. {
  571. // Invariants:
  572. // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k)
  573. // pow10 = 10^(n-1) <= p1 < 10^n
  574. //
  575. const uint32_t d = p1 / pow10; // d = p1 div 10^(n-1)
  576. const uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1)
  577. //
  578. // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e
  579. // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e)
  580. //
  581. assert(d <= 9);
  582. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  583. //
  584. // M+ = buffer * 10^(n-1) + (r + p2 * 2^e)
  585. //
  586. p1 = r;
  587. n--;
  588. //
  589. // M+ = buffer * 10^n + (p1 + p2 * 2^e)
  590. // pow10 = 10^n
  591. //
  592. // Now check if enough digits have been generated.
  593. // Compute
  594. //
  595. // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e
  596. //
  597. // Note:
  598. // Since rest and delta share the same exponent e, it suffices to
  599. // compare the significands.
  600. const uint64_t rest = (uint64_t{p1} << -one.e) + p2;
  601. if (rest <= delta)
  602. {
  603. // V = buffer * 10^n, with M- <= V <= M+.
  604. decimal_exponent += n;
  605. // We may now just stop. But instead look if the buffer could be
  606. // decremented to bring V closer to w.
  607. //
  608. // pow10 = 10^n is now 1 ulp in the decimal representation V.
  609. // The rounding procedure works with diyfp's with an implicit
  610. // exponent of e.
  611. //
  612. // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e
  613. //
  614. const uint64_t ten_n = uint64_t{pow10} << -one.e;
  615. grisu2_round(buffer, length, dist, delta, rest, ten_n);
  616. return;
  617. }
  618. pow10 /= 10;
  619. //
  620. // pow10 = 10^(n-1) <= p1 < 10^n
  621. // Invariants restored.
  622. }
  623. // 2)
  624. //
  625. // The digits of the integral part have been generated:
  626. //
  627. // M+ = d[k-1]...d[1]d[0] + p2 * 2^e
  628. // = buffer + p2 * 2^e
  629. //
  630. // Now generate the digits of the fractional part p2 * 2^e.
  631. //
  632. // Note:
  633. // No decimal point is generated: the exponent is adjusted instead.
  634. //
  635. // p2 actually represents the fraction
  636. //
  637. // p2 * 2^e
  638. // = p2 / 2^-e
  639. // = d[-1] / 10^1 + d[-2] / 10^2 + ...
  640. //
  641. // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...)
  642. //
  643. // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m
  644. // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...)
  645. //
  646. // using
  647. //
  648. // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e)
  649. // = ( d) * 2^-e + ( r)
  650. //
  651. // or
  652. // 10^m * p2 * 2^e = d + r * 2^e
  653. //
  654. // i.e.
  655. //
  656. // M+ = buffer + p2 * 2^e
  657. // = buffer + 10^-m * (d + r * 2^e)
  658. // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e
  659. //
  660. // and stop as soon as 10^-m * r * 2^e <= delta * 2^e
  661. assert(p2 > delta);
  662. int m = 0;
  663. for (;;)
  664. {
  665. // Invariant:
  666. // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e
  667. // = buffer * 10^-m + 10^-m * (p2 ) * 2^e
  668. // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e
  669. // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e
  670. //
  671. assert(p2 <= UINT64_MAX / 10);
  672. p2 *= 10;
  673. const uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e
  674. const uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e
  675. //
  676. // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e
  677. // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e))
  678. // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e
  679. //
  680. assert(d <= 9);
  681. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  682. //
  683. // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e
  684. //
  685. p2 = r;
  686. m++;
  687. //
  688. // M+ = buffer * 10^-m + 10^-m * p2 * 2^e
  689. // Invariant restored.
  690. // Check if enough digits have been generated.
  691. //
  692. // 10^-m * p2 * 2^e <= delta * 2^e
  693. // p2 * 2^e <= 10^m * delta * 2^e
  694. // p2 <= 10^m * delta
  695. delta *= 10;
  696. dist *= 10;
  697. if (p2 <= delta)
  698. {
  699. break;
  700. }
  701. }
  702. // V = buffer * 10^-m, with M- <= V <= M+.
  703. decimal_exponent -= m;
  704. // 1 ulp in the decimal representation is now 10^-m.
  705. // Since delta and dist are now scaled by 10^m, we need to do the
  706. // same with ulp in order to keep the units in sync.
  707. //
  708. // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e
  709. //
  710. const uint64_t ten_m = one.f;
  711. grisu2_round(buffer, length, dist, delta, p2, ten_m);
  712. // By construction this algorithm generates the shortest possible decimal
  713. // number (Loitsch, Theorem 6.2) which rounds back to w.
  714. // For an input number of precision p, at least
  715. //
  716. // N = 1 + ceil(p * log_10(2))
  717. //
  718. // decimal digits are sufficient to identify all binary floating-point
  719. // numbers (Matula, "In-and-Out conversions").
  720. // This implies that the algorithm does not produce more than N decimal
  721. // digits.
  722. //
  723. // N = 17 for p = 53 (IEEE double precision)
  724. // N = 9 for p = 24 (IEEE single precision)
  725. }
  726. /*!
  727. v = buf * 10^decimal_exponent
  728. len is the length of the buffer (number of decimal digits)
  729. The buffer must be large enough, i.e. >= max_digits10.
  730. */
  731. inline void grisu2(char* buf, int& len, int& decimal_exponent,
  732. diyfp m_minus, diyfp v, diyfp m_plus)
  733. {
  734. assert(m_plus.e == m_minus.e);
  735. assert(m_plus.e == v.e);
  736. // --------(-----------------------+-----------------------)-------- (A)
  737. // m- v m+
  738. //
  739. // --------------------(-----------+-----------------------)-------- (B)
  740. // m- v m+
  741. //
  742. // First scale v (and m- and m+) such that the exponent is in the range
  743. // [alpha, gamma].
  744. const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e);
  745. const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k
  746. // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma]
  747. const diyfp w = diyfp::mul(v, c_minus_k);
  748. const diyfp w_minus = diyfp::mul(m_minus, c_minus_k);
  749. const diyfp w_plus = diyfp::mul(m_plus, c_minus_k);
  750. // ----(---+---)---------------(---+---)---------------(---+---)----
  751. // w- w w+
  752. // = c*m- = c*v = c*m+
  753. //
  754. // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and
  755. // w+ are now off by a small amount.
  756. // In fact:
  757. //
  758. // w - v * 10^k < 1 ulp
  759. //
  760. // To account for this inaccuracy, add resp. subtract 1 ulp.
  761. //
  762. // --------+---[---------------(---+---)---------------]---+--------
  763. // w- M- w M+ w+
  764. //
  765. // Now any number in [M-, M+] (bounds included) will round to w when input,
  766. // regardless of how the input rounding algorithm breaks ties.
  767. //
  768. // And digit_gen generates the shortest possible such number in [M-, M+].
  769. // Note that this does not mean that Grisu2 always generates the shortest
  770. // possible number in the interval (m-, m+).
  771. const diyfp M_minus(w_minus.f + 1, w_minus.e);
  772. const diyfp M_plus (w_plus.f - 1, w_plus.e );
  773. decimal_exponent = -cached.k; // = -(-k) = k
  774. grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus);
  775. }
  776. /*!
  777. v = buf * 10^decimal_exponent
  778. len is the length of the buffer (number of decimal digits)
  779. The buffer must be large enough, i.e. >= max_digits10.
  780. */
  781. template <typename FloatType>
  782. void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value)
  783. {
  784. static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3,
  785. "internal error: not enough precision");
  786. assert(std::isfinite(value));
  787. assert(value > 0);
  788. // If the neighbors (and boundaries) of 'value' are always computed for double-precision
  789. // numbers, all float's can be recovered using strtod (and strtof). However, the resulting
  790. // decimal representations are not exactly "short".
  791. //
  792. // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars)
  793. // says "value is converted to a string as if by std::sprintf in the default ("C") locale"
  794. // and since sprintf promotes float's to double's, I think this is exactly what 'std::to_chars'
  795. // does.
  796. // On the other hand, the documentation for 'std::to_chars' requires that "parsing the
  797. // representation using the corresponding std::from_chars function recovers value exactly". That
  798. // indicates that single precision floating-point numbers should be recovered using
  799. // 'std::strtof'.
  800. //
  801. // NB: If the neighbors are computed for single-precision numbers, there is a single float
  802. // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision
  803. // value is off by 1 ulp.
  804. #if 0
  805. const boundaries w = compute_boundaries(static_cast<double>(value));
  806. #else
  807. const boundaries w = compute_boundaries(value);
  808. #endif
  809. grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus);
  810. }
  811. /*!
  812. @brief appends a decimal representation of e to buf
  813. @return a pointer to the element following the exponent.
  814. @pre -1000 < e < 1000
  815. */
  816. inline char* append_exponent(char* buf, int e)
  817. {
  818. assert(e > -1000);
  819. assert(e < 1000);
  820. if (e < 0)
  821. {
  822. e = -e;
  823. *buf++ = '-';
  824. }
  825. else
  826. {
  827. *buf++ = '+';
  828. }
  829. uint32_t k = static_cast<uint32_t>(e);
  830. if (k < 10)
  831. {
  832. // Always print at least two digits in the exponent.
  833. // This is for compatibility with printf("%g").
  834. *buf++ = '0';
  835. *buf++ = static_cast<char>('0' + k);
  836. }
  837. else if (k < 100)
  838. {
  839. *buf++ = static_cast<char>('0' + k / 10);
  840. k %= 10;
  841. *buf++ = static_cast<char>('0' + k);
  842. }
  843. else
  844. {
  845. *buf++ = static_cast<char>('0' + k / 100);
  846. k %= 100;
  847. *buf++ = static_cast<char>('0' + k / 10);
  848. k %= 10;
  849. *buf++ = static_cast<char>('0' + k);
  850. }
  851. return buf;
  852. }
  853. /*!
  854. @brief prettify v = buf * 10^decimal_exponent
  855. If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point
  856. notation. Otherwise it will be printed in exponential notation.
  857. @pre min_exp < 0
  858. @pre max_exp > 0
  859. */
  860. inline char* format_buffer(char* buf, int len, int decimal_exponent,
  861. int min_exp, int max_exp)
  862. {
  863. assert(min_exp < 0);
  864. assert(max_exp > 0);
  865. const int k = len;
  866. const int n = len + decimal_exponent;
  867. // v = buf * 10^(n-k)
  868. // k is the length of the buffer (number of decimal digits)
  869. // n is the position of the decimal point relative to the start of the buffer.
  870. if (k <= n and n <= max_exp)
  871. {
  872. // digits[000]
  873. // len <= max_exp + 2
  874. std::memset(buf + k, '0', static_cast<size_t>(n - k));
  875. // Make it look like a floating-point number (#362, #378)
  876. buf[n + 0] = '.';
  877. buf[n + 1] = '0';
  878. return buf + (n + 2);
  879. }
  880. if (0 < n and n <= max_exp)
  881. {
  882. // dig.its
  883. // len <= max_digits10 + 1
  884. assert(k > n);
  885. std::memmove(buf + (n + 1), buf + n, static_cast<size_t>(k - n));
  886. buf[n] = '.';
  887. return buf + (k + 1);
  888. }
  889. if (min_exp < n and n <= 0)
  890. {
  891. // 0.[000]digits
  892. // len <= 2 + (-min_exp - 1) + max_digits10
  893. std::memmove(buf + (2 + -n), buf, static_cast<size_t>(k));
  894. buf[0] = '0';
  895. buf[1] = '.';
  896. std::memset(buf + 2, '0', static_cast<size_t>(-n));
  897. return buf + (2 + (-n) + k);
  898. }
  899. if (k == 1)
  900. {
  901. // dE+123
  902. // len <= 1 + 5
  903. buf += 1;
  904. }
  905. else
  906. {
  907. // d.igitsE+123
  908. // len <= max_digits10 + 1 + 5
  909. std::memmove(buf + 2, buf + 1, static_cast<size_t>(k - 1));
  910. buf[1] = '.';
  911. buf += 1 + k;
  912. }
  913. *buf++ = 'e';
  914. return append_exponent(buf, n - 1);
  915. }
  916. } // namespace dtoa_impl
  917. /*!
  918. @brief generates a decimal representation of the floating-point number value in [first, last).
  919. The format of the resulting decimal representation is similar to printf's %g
  920. format. Returns an iterator pointing past-the-end of the decimal representation.
  921. @note The input number must be finite, i.e. NaN's and Inf's are not supported.
  922. @note The buffer must be large enough.
  923. @note The result is NOT null-terminated.
  924. */
  925. template <typename FloatType>
  926. char* to_chars(char* first, char* last, FloatType value)
  927. {
  928. static_cast<void>(last); // maybe unused - fix warning
  929. assert(std::isfinite(value));
  930. // Use signbit(value) instead of (value < 0) since signbit works for -0.
  931. if (std::signbit(value))
  932. {
  933. value = -value;
  934. *first++ = '-';
  935. }
  936. if (value == 0) // +-0
  937. {
  938. *first++ = '0';
  939. // Make it look like a floating-point number (#362, #378)
  940. *first++ = '.';
  941. *first++ = '0';
  942. return first;
  943. }
  944. assert(last - first >= std::numeric_limits<FloatType>::max_digits10);
  945. // Compute v = buffer * 10^decimal_exponent.
  946. // The decimal digits are stored in the buffer, which needs to be interpreted
  947. // as an unsigned decimal integer.
  948. // len is the length of the buffer, i.e. the number of decimal digits.
  949. int len = 0;
  950. int decimal_exponent = 0;
  951. dtoa_impl::grisu2(first, len, decimal_exponent, value);
  952. assert(len <= std::numeric_limits<FloatType>::max_digits10);
  953. // Format the buffer like printf("%.*g", prec, value)
  954. constexpr int kMinExp = -4;
  955. // Use digits10 here to increase compatibility with version 2.
  956. constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10;
  957. assert(last - first >= kMaxExp + 2);
  958. assert(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10);
  959. assert(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);
  960. return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp);
  961. }
  962. } // namespace detail
  963. } // namespace nlohmann