double-conversion-fast-dtoa.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. // © 2018 and later: Unicode, Inc. and others.
  2. // License & terms of use: http://www.unicode.org/copyright.html
  3. //
  4. // From the double-conversion library. Original license:
  5. //
  6. // Copyright 2012 the V8 project authors. All rights reserved.
  7. // Redistribution and use in source and binary forms, with or without
  8. // modification, are permitted provided that the following conditions are
  9. // met:
  10. //
  11. // * Redistributions of source code must retain the above copyright
  12. // notice, this list of conditions and the following disclaimer.
  13. // * Redistributions in binary form must reproduce the above
  14. // copyright notice, this list of conditions and the following
  15. // disclaimer in the documentation and/or other materials provided
  16. // with the distribution.
  17. // * Neither the name of Google Inc. nor the names of its
  18. // contributors may be used to endorse or promote products derived
  19. // from this software without specific prior written permission.
  20. //
  21. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. // ICU PATCH: ifdef around UCONFIG_NO_FORMATTING
  33. #include "unicode/utypes.h"
  34. #if !UCONFIG_NO_FORMATTING
  35. // ICU PATCH: Customize header file paths for ICU.
  36. #include "double-conversion-fast-dtoa.h"
  37. #include "double-conversion-cached-powers.h"
  38. #include "double-conversion-diy-fp.h"
  39. #include "double-conversion-ieee.h"
  40. // ICU PATCH: Wrap in ICU namespace
  41. U_NAMESPACE_BEGIN
  42. namespace double_conversion {
  43. // The minimal and maximal target exponent define the range of w's binary
  44. // exponent, where 'w' is the result of multiplying the input by a cached power
  45. // of ten.
  46. //
  47. // A different range might be chosen on a different platform, to optimize digit
  48. // generation, but a smaller range requires more powers of ten to be cached.
  49. static const int kMinimalTargetExponent = -60;
  50. static const int kMaximalTargetExponent = -32;
  51. // Adjusts the last digit of the generated number, and screens out generated
  52. // solutions that may be inaccurate. A solution may be inaccurate if it is
  53. // outside the safe interval, or if we cannot prove that it is closer to the
  54. // input than a neighboring representation of the same length.
  55. //
  56. // Input: * buffer containing the digits of too_high / 10^kappa
  57. // * the buffer's length
  58. // * distance_too_high_w == (too_high - w).f() * unit
  59. // * unsafe_interval == (too_high - too_low).f() * unit
  60. // * rest = (too_high - buffer * 10^kappa).f() * unit
  61. // * ten_kappa = 10^kappa * unit
  62. // * unit = the common multiplier
  63. // Output: returns true if the buffer is guaranteed to contain the closest
  64. // representable number to the input.
  65. // Modifies the generated digits in the buffer to approach (round towards) w.
  66. static bool RoundWeed(Vector<char> buffer,
  67. int length,
  68. uint64_t distance_too_high_w,
  69. uint64_t unsafe_interval,
  70. uint64_t rest,
  71. uint64_t ten_kappa,
  72. uint64_t unit) {
  73. uint64_t small_distance = distance_too_high_w - unit;
  74. uint64_t big_distance = distance_too_high_w + unit;
  75. // Let w_low = too_high - big_distance, and
  76. // w_high = too_high - small_distance.
  77. // Note: w_low < w < w_high
  78. //
  79. // The real w (* unit) must lie somewhere inside the interval
  80. // ]w_low; w_high[ (often written as "(w_low; w_high)")
  81. // Basically the buffer currently contains a number in the unsafe interval
  82. // ]too_low; too_high[ with too_low < w < too_high
  83. //
  84. // too_high - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  85. // ^v 1 unit ^ ^ ^ ^
  86. // boundary_high --------------------- . . . .
  87. // ^v 1 unit . . . .
  88. // - - - - - - - - - - - - - - - - - - - + - - + - - - - - - . .
  89. // . . ^ . .
  90. // . big_distance . . .
  91. // . . . . rest
  92. // small_distance . . . .
  93. // v . . . .
  94. // w_high - - - - - - - - - - - - - - - - - - . . . .
  95. // ^v 1 unit . . . .
  96. // w ---------------------------------------- . . . .
  97. // ^v 1 unit v . . .
  98. // w_low - - - - - - - - - - - - - - - - - - - - - . . .
  99. // . . v
  100. // buffer --------------------------------------------------+-------+--------
  101. // . .
  102. // safe_interval .
  103. // v .
  104. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - .
  105. // ^v 1 unit .
  106. // boundary_low ------------------------- unsafe_interval
  107. // ^v 1 unit v
  108. // too_low - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  109. //
  110. //
  111. // Note that the value of buffer could lie anywhere inside the range too_low
  112. // to too_high.
  113. //
  114. // boundary_low, boundary_high and w are approximations of the real boundaries
  115. // and v (the input number). They are guaranteed to be precise up to one unit.
  116. // In fact the error is guaranteed to be strictly less than one unit.
  117. //
  118. // Anything that lies outside the unsafe interval is guaranteed not to round
  119. // to v when read again.
  120. // Anything that lies inside the safe interval is guaranteed to round to v
  121. // when read again.
  122. // If the number inside the buffer lies inside the unsafe interval but not
  123. // inside the safe interval then we simply do not know and bail out (returning
  124. // false).
  125. //
  126. // Similarly we have to take into account the imprecision of 'w' when finding
  127. // the closest representation of 'w'. If we have two potential
  128. // representations, and one is closer to both w_low and w_high, then we know
  129. // it is closer to the actual value v.
  130. //
  131. // By generating the digits of too_high we got the largest (closest to
  132. // too_high) buffer that is still in the unsafe interval. In the case where
  133. // w_high < buffer < too_high we try to decrement the buffer.
  134. // This way the buffer approaches (rounds towards) w.
  135. // There are 3 conditions that stop the decrementation process:
  136. // 1) the buffer is already below w_high
  137. // 2) decrementing the buffer would make it leave the unsafe interval
  138. // 3) decrementing the buffer would yield a number below w_high and farther
  139. // away than the current number. In other words:
  140. // (buffer{-1} < w_high) && w_high - buffer{-1} > buffer - w_high
  141. // Instead of using the buffer directly we use its distance to too_high.
  142. // Conceptually rest ~= too_high - buffer
  143. // We need to do the following tests in this order to avoid over- and
  144. // underflows.
  145. DOUBLE_CONVERSION_ASSERT(rest <= unsafe_interval);
  146. while (rest < small_distance && // Negated condition 1
  147. unsafe_interval - rest >= ten_kappa && // Negated condition 2
  148. (rest + ten_kappa < small_distance || // buffer{-1} > w_high
  149. small_distance - rest >= rest + ten_kappa - small_distance)) {
  150. buffer[length - 1]--;
  151. rest += ten_kappa;
  152. }
  153. // We have approached w+ as much as possible. We now test if approaching w-
  154. // would require changing the buffer. If yes, then we have two possible
  155. // representations close to w, but we cannot decide which one is closer.
  156. if (rest < big_distance &&
  157. unsafe_interval - rest >= ten_kappa &&
  158. (rest + ten_kappa < big_distance ||
  159. big_distance - rest > rest + ten_kappa - big_distance)) {
  160. return false;
  161. }
  162. // Weeding test.
  163. // The safe interval is [too_low + 2 ulp; too_high - 2 ulp]
  164. // Since too_low = too_high - unsafe_interval this is equivalent to
  165. // [too_high - unsafe_interval + 4 ulp; too_high - 2 ulp]
  166. // Conceptually we have: rest ~= too_high - buffer
  167. return (2 * unit <= rest) && (rest <= unsafe_interval - 4 * unit);
  168. }
  169. // Rounds the buffer upwards if the result is closer to v by possibly adding
  170. // 1 to the buffer. If the precision of the calculation is not sufficient to
  171. // round correctly, return false.
  172. // The rounding might shift the whole buffer in which case the kappa is
  173. // adjusted. For example "99", kappa = 3 might become "10", kappa = 4.
  174. //
  175. // If 2*rest > ten_kappa then the buffer needs to be round up.
  176. // rest can have an error of +/- 1 unit. This function accounts for the
  177. // imprecision and returns false, if the rounding direction cannot be
  178. // unambiguously determined.
  179. //
  180. // Precondition: rest < ten_kappa.
  181. static bool RoundWeedCounted(Vector<char> buffer,
  182. int length,
  183. uint64_t rest,
  184. uint64_t ten_kappa,
  185. uint64_t unit,
  186. int* kappa) {
  187. DOUBLE_CONVERSION_ASSERT(rest < ten_kappa);
  188. // The following tests are done in a specific order to avoid overflows. They
  189. // will work correctly with any uint64 values of rest < ten_kappa and unit.
  190. //
  191. // If the unit is too big, then we don't know which way to round. For example
  192. // a unit of 50 means that the real number lies within rest +/- 50. If
  193. // 10^kappa == 40 then there is no way to tell which way to round.
  194. if (unit >= ten_kappa) return false;
  195. // Even if unit is just half the size of 10^kappa we are already completely
  196. // lost. (And after the previous test we know that the expression will not
  197. // over/underflow.)
  198. if (ten_kappa - unit <= unit) return false;
  199. // If 2 * (rest + unit) <= 10^kappa we can safely round down.
  200. if ((ten_kappa - rest > rest) && (ten_kappa - 2 * rest >= 2 * unit)) {
  201. return true;
  202. }
  203. // If 2 * (rest - unit) >= 10^kappa, then we can safely round up.
  204. if ((rest > unit) && (ten_kappa - (rest - unit) <= (rest - unit))) {
  205. // Increment the last digit recursively until we find a non '9' digit.
  206. buffer[length - 1]++;
  207. for (int i = length - 1; i > 0; --i) {
  208. if (buffer[i] != '0' + 10) break;
  209. buffer[i] = '0';
  210. buffer[i - 1]++;
  211. }
  212. // If the first digit is now '0'+ 10 we had a buffer with all '9's. With the
  213. // exception of the first digit all digits are now '0'. Simply switch the
  214. // first digit to '1' and adjust the kappa. Example: "99" becomes "10" and
  215. // the power (the kappa) is increased.
  216. if (buffer[0] == '0' + 10) {
  217. buffer[0] = '1';
  218. (*kappa) += 1;
  219. }
  220. return true;
  221. }
  222. return false;
  223. }
  224. // Returns the biggest power of ten that is less than or equal to the given
  225. // number. We furthermore receive the maximum number of bits 'number' has.
  226. //
  227. // Returns power == 10^(exponent_plus_one-1) such that
  228. // power <= number < power * 10.
  229. // If number_bits == 0 then 0^(0-1) is returned.
  230. // The number of bits must be <= 32.
  231. // Precondition: number < (1 << (number_bits + 1)).
  232. // Inspired by the method for finding an integer log base 10 from here:
  233. // http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10
  234. static unsigned int const kSmallPowersOfTen[] =
  235. {0, 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
  236. 1000000000};
  237. static void BiggestPowerTen(uint32_t number,
  238. int number_bits,
  239. uint32_t* power,
  240. int* exponent_plus_one) {
  241. DOUBLE_CONVERSION_ASSERT(number < (1u << (number_bits + 1)));
  242. // 1233/4096 is approximately 1/lg(10).
  243. int exponent_plus_one_guess = ((number_bits + 1) * 1233 >> 12);
  244. // We increment to skip over the first entry in the kPowersOf10 table.
  245. // Note: kPowersOf10[i] == 10^(i-1).
  246. exponent_plus_one_guess++;
  247. // We don't have any guarantees that 2^number_bits <= number.
  248. if (number < kSmallPowersOfTen[exponent_plus_one_guess]) {
  249. exponent_plus_one_guess--;
  250. }
  251. *power = kSmallPowersOfTen[exponent_plus_one_guess];
  252. *exponent_plus_one = exponent_plus_one_guess;
  253. }
  254. // Generates the digits of input number w.
  255. // w is a floating-point number (DiyFp), consisting of a significand and an
  256. // exponent. Its exponent is bounded by kMinimalTargetExponent and
  257. // kMaximalTargetExponent.
  258. // Hence -60 <= w.e() <= -32.
  259. //
  260. // Returns false if it fails, in which case the generated digits in the buffer
  261. // should not be used.
  262. // Preconditions:
  263. // * low, w and high are correct up to 1 ulp (unit in the last place). That
  264. // is, their error must be less than a unit of their last digits.
  265. // * low.e() == w.e() == high.e()
  266. // * low < w < high, and taking into account their error: low~ <= high~
  267. // * kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent
  268. // Postconditions: returns false if procedure fails.
  269. // otherwise:
  270. // * buffer is not null-terminated, but len contains the number of digits.
  271. // * buffer contains the shortest possible decimal digit-sequence
  272. // such that LOW < buffer * 10^kappa < HIGH, where LOW and HIGH are the
  273. // correct values of low and high (without their error).
  274. // * if more than one decimal representation gives the minimal number of
  275. // decimal digits then the one closest to W (where W is the correct value
  276. // of w) is chosen.
  277. // Remark: this procedure takes into account the imprecision of its input
  278. // numbers. If the precision is not enough to guarantee all the postconditions
  279. // then false is returned. This usually happens rarely (~0.5%).
  280. //
  281. // Say, for the sake of example, that
  282. // w.e() == -48, and w.f() == 0x1234567890abcdef
  283. // w's value can be computed by w.f() * 2^w.e()
  284. // We can obtain w's integral digits by simply shifting w.f() by -w.e().
  285. // -> w's integral part is 0x1234
  286. // w's fractional part is therefore 0x567890abcdef.
  287. // Printing w's integral part is easy (simply print 0x1234 in decimal).
  288. // In order to print its fraction we repeatedly multiply the fraction by 10 and
  289. // get each digit. Example the first digit after the point would be computed by
  290. // (0x567890abcdef * 10) >> 48. -> 3
  291. // The whole thing becomes slightly more complicated because we want to stop
  292. // once we have enough digits. That is, once the digits inside the buffer
  293. // represent 'w' we can stop. Everything inside the interval low - high
  294. // represents w. However we have to pay attention to low, high and w's
  295. // imprecision.
  296. static bool DigitGen(DiyFp low,
  297. DiyFp w,
  298. DiyFp high,
  299. Vector<char> buffer,
  300. int* length,
  301. int* kappa) {
  302. DOUBLE_CONVERSION_ASSERT(low.e() == w.e() && w.e() == high.e());
  303. DOUBLE_CONVERSION_ASSERT(low.f() + 1 <= high.f() - 1);
  304. DOUBLE_CONVERSION_ASSERT(kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent);
  305. // low, w and high are imprecise, but by less than one ulp (unit in the last
  306. // place).
  307. // If we remove (resp. add) 1 ulp from low (resp. high) we are certain that
  308. // the new numbers are outside of the interval we want the final
  309. // representation to lie in.
  310. // Inversely adding (resp. removing) 1 ulp from low (resp. high) would yield
  311. // numbers that are certain to lie in the interval. We will use this fact
  312. // later on.
  313. // We will now start by generating the digits within the uncertain
  314. // interval. Later we will weed out representations that lie outside the safe
  315. // interval and thus _might_ lie outside the correct interval.
  316. uint64_t unit = 1;
  317. DiyFp too_low = DiyFp(low.f() - unit, low.e());
  318. DiyFp too_high = DiyFp(high.f() + unit, high.e());
  319. // too_low and too_high are guaranteed to lie outside the interval we want the
  320. // generated number in.
  321. DiyFp unsafe_interval = DiyFp::Minus(too_high, too_low);
  322. // We now cut the input number into two parts: the integral digits and the
  323. // fractionals. We will not write any decimal separator though, but adapt
  324. // kappa instead.
  325. // Reminder: we are currently computing the digits (stored inside the buffer)
  326. // such that: too_low < buffer * 10^kappa < too_high
  327. // We use too_high for the digit_generation and stop as soon as possible.
  328. // If we stop early we effectively round down.
  329. DiyFp one = DiyFp(static_cast<uint64_t>(1) << -w.e(), w.e());
  330. // Division by one is a shift.
  331. uint32_t integrals = static_cast<uint32_t>(too_high.f() >> -one.e());
  332. // Modulo by one is an and.
  333. uint64_t fractionals = too_high.f() & (one.f() - 1);
  334. uint32_t divisor;
  335. int divisor_exponent_plus_one;
  336. BiggestPowerTen(integrals, DiyFp::kSignificandSize - (-one.e()),
  337. &divisor, &divisor_exponent_plus_one);
  338. *kappa = divisor_exponent_plus_one;
  339. *length = 0;
  340. // Loop invariant: buffer = too_high / 10^kappa (integer division)
  341. // The invariant holds for the first iteration: kappa has been initialized
  342. // with the divisor exponent + 1. And the divisor is the biggest power of ten
  343. // that is smaller than integrals.
  344. while (*kappa > 0) {
  345. int digit = integrals / divisor;
  346. DOUBLE_CONVERSION_ASSERT(digit <= 9);
  347. buffer[*length] = static_cast<char>('0' + digit);
  348. (*length)++;
  349. integrals %= divisor;
  350. (*kappa)--;
  351. // Note that kappa now equals the exponent of the divisor and that the
  352. // invariant thus holds again.
  353. uint64_t rest =
  354. (static_cast<uint64_t>(integrals) << -one.e()) + fractionals;
  355. // Invariant: too_high = buffer * 10^kappa + DiyFp(rest, one.e())
  356. // Reminder: unsafe_interval.e() == one.e()
  357. if (rest < unsafe_interval.f()) {
  358. // Rounding down (by not emitting the remaining digits) yields a number
  359. // that lies within the unsafe interval.
  360. return RoundWeed(buffer, *length, DiyFp::Minus(too_high, w).f(),
  361. unsafe_interval.f(), rest,
  362. static_cast<uint64_t>(divisor) << -one.e(), unit);
  363. }
  364. divisor /= 10;
  365. }
  366. // The integrals have been generated. We are at the point of the decimal
  367. // separator. In the following loop we simply multiply the remaining digits by
  368. // 10 and divide by one. We just need to pay attention to multiply associated
  369. // data (like the interval or 'unit'), too.
  370. // Note that the multiplication by 10 does not overflow, because w.e >= -60
  371. // and thus one.e >= -60.
  372. DOUBLE_CONVERSION_ASSERT(one.e() >= -60);
  373. DOUBLE_CONVERSION_ASSERT(fractionals < one.f());
  374. DOUBLE_CONVERSION_ASSERT(DOUBLE_CONVERSION_UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.f());
  375. for (;;) {
  376. fractionals *= 10;
  377. unit *= 10;
  378. unsafe_interval.set_f(unsafe_interval.f() * 10);
  379. // Integer division by one.
  380. int digit = static_cast<int>(fractionals >> -one.e());
  381. DOUBLE_CONVERSION_ASSERT(digit <= 9);
  382. buffer[*length] = static_cast<char>('0' + digit);
  383. (*length)++;
  384. fractionals &= one.f() - 1; // Modulo by one.
  385. (*kappa)--;
  386. if (fractionals < unsafe_interval.f()) {
  387. return RoundWeed(buffer, *length, DiyFp::Minus(too_high, w).f() * unit,
  388. unsafe_interval.f(), fractionals, one.f(), unit);
  389. }
  390. }
  391. }
  392. // Generates (at most) requested_digits digits of input number w.
  393. // w is a floating-point number (DiyFp), consisting of a significand and an
  394. // exponent. Its exponent is bounded by kMinimalTargetExponent and
  395. // kMaximalTargetExponent.
  396. // Hence -60 <= w.e() <= -32.
  397. //
  398. // Returns false if it fails, in which case the generated digits in the buffer
  399. // should not be used.
  400. // Preconditions:
  401. // * w is correct up to 1 ulp (unit in the last place). That
  402. // is, its error must be strictly less than a unit of its last digit.
  403. // * kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent
  404. //
  405. // Postconditions: returns false if procedure fails.
  406. // otherwise:
  407. // * buffer is not null-terminated, but length contains the number of
  408. // digits.
  409. // * the representation in buffer is the most precise representation of
  410. // requested_digits digits.
  411. // * buffer contains at most requested_digits digits of w. If there are less
  412. // than requested_digits digits then some trailing '0's have been removed.
  413. // * kappa is such that
  414. // w = buffer * 10^kappa + eps with |eps| < 10^kappa / 2.
  415. //
  416. // Remark: This procedure takes into account the imprecision of its input
  417. // numbers. If the precision is not enough to guarantee all the postconditions
  418. // then false is returned. This usually happens rarely, but the failure-rate
  419. // increases with higher requested_digits.
  420. static bool DigitGenCounted(DiyFp w,
  421. int requested_digits,
  422. Vector<char> buffer,
  423. int* length,
  424. int* kappa) {
  425. DOUBLE_CONVERSION_ASSERT(kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent);
  426. DOUBLE_CONVERSION_ASSERT(kMinimalTargetExponent >= -60);
  427. DOUBLE_CONVERSION_ASSERT(kMaximalTargetExponent <= -32);
  428. // w is assumed to have an error less than 1 unit. Whenever w is scaled we
  429. // also scale its error.
  430. uint64_t w_error = 1;
  431. // We cut the input number into two parts: the integral digits and the
  432. // fractional digits. We don't emit any decimal separator, but adapt kappa
  433. // instead. Example: instead of writing "1.2" we put "12" into the buffer and
  434. // increase kappa by 1.
  435. DiyFp one = DiyFp(static_cast<uint64_t>(1) << -w.e(), w.e());
  436. // Division by one is a shift.
  437. uint32_t integrals = static_cast<uint32_t>(w.f() >> -one.e());
  438. // Modulo by one is an and.
  439. uint64_t fractionals = w.f() & (one.f() - 1);
  440. uint32_t divisor;
  441. int divisor_exponent_plus_one;
  442. BiggestPowerTen(integrals, DiyFp::kSignificandSize - (-one.e()),
  443. &divisor, &divisor_exponent_plus_one);
  444. *kappa = divisor_exponent_plus_one;
  445. *length = 0;
  446. // Loop invariant: buffer = w / 10^kappa (integer division)
  447. // The invariant holds for the first iteration: kappa has been initialized
  448. // with the divisor exponent + 1. And the divisor is the biggest power of ten
  449. // that is smaller than 'integrals'.
  450. while (*kappa > 0) {
  451. int digit = integrals / divisor;
  452. DOUBLE_CONVERSION_ASSERT(digit <= 9);
  453. buffer[*length] = static_cast<char>('0' + digit);
  454. (*length)++;
  455. requested_digits--;
  456. integrals %= divisor;
  457. (*kappa)--;
  458. // Note that kappa now equals the exponent of the divisor and that the
  459. // invariant thus holds again.
  460. if (requested_digits == 0) break;
  461. divisor /= 10;
  462. }
  463. if (requested_digits == 0) {
  464. uint64_t rest =
  465. (static_cast<uint64_t>(integrals) << -one.e()) + fractionals;
  466. return RoundWeedCounted(buffer, *length, rest,
  467. static_cast<uint64_t>(divisor) << -one.e(), w_error,
  468. kappa);
  469. }
  470. // The integrals have been generated. We are at the point of the decimal
  471. // separator. In the following loop we simply multiply the remaining digits by
  472. // 10 and divide by one. We just need to pay attention to multiply associated
  473. // data (the 'unit'), too.
  474. // Note that the multiplication by 10 does not overflow, because w.e >= -60
  475. // and thus one.e >= -60.
  476. DOUBLE_CONVERSION_ASSERT(one.e() >= -60);
  477. DOUBLE_CONVERSION_ASSERT(fractionals < one.f());
  478. DOUBLE_CONVERSION_ASSERT(DOUBLE_CONVERSION_UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.f());
  479. while (requested_digits > 0 && fractionals > w_error) {
  480. fractionals *= 10;
  481. w_error *= 10;
  482. // Integer division by one.
  483. int digit = static_cast<int>(fractionals >> -one.e());
  484. DOUBLE_CONVERSION_ASSERT(digit <= 9);
  485. buffer[*length] = static_cast<char>('0' + digit);
  486. (*length)++;
  487. requested_digits--;
  488. fractionals &= one.f() - 1; // Modulo by one.
  489. (*kappa)--;
  490. }
  491. if (requested_digits != 0) return false;
  492. return RoundWeedCounted(buffer, *length, fractionals, one.f(), w_error,
  493. kappa);
  494. }
  495. // Provides a decimal representation of v.
  496. // Returns true if it succeeds, otherwise the result cannot be trusted.
  497. // There will be *length digits inside the buffer (not null-terminated).
  498. // If the function returns true then
  499. // v == (double) (buffer * 10^decimal_exponent).
  500. // The digits in the buffer are the shortest representation possible: no
  501. // 0.09999999999999999 instead of 0.1. The shorter representation will even be
  502. // chosen even if the longer one would be closer to v.
  503. // The last digit will be closest to the actual v. That is, even if several
  504. // digits might correctly yield 'v' when read again, the closest will be
  505. // computed.
  506. static bool Grisu3(double v,
  507. FastDtoaMode mode,
  508. Vector<char> buffer,
  509. int* length,
  510. int* decimal_exponent) {
  511. DiyFp w = Double(v).AsNormalizedDiyFp();
  512. // boundary_minus and boundary_plus are the boundaries between v and its
  513. // closest floating-point neighbors. Any number strictly between
  514. // boundary_minus and boundary_plus will round to v when convert to a double.
  515. // Grisu3 will never output representations that lie exactly on a boundary.
  516. DiyFp boundary_minus, boundary_plus;
  517. if (mode == FAST_DTOA_SHORTEST) {
  518. Double(v).NormalizedBoundaries(&boundary_minus, &boundary_plus);
  519. } else {
  520. DOUBLE_CONVERSION_ASSERT(mode == FAST_DTOA_SHORTEST_SINGLE);
  521. float single_v = static_cast<float>(v);
  522. Single(single_v).NormalizedBoundaries(&boundary_minus, &boundary_plus);
  523. }
  524. DOUBLE_CONVERSION_ASSERT(boundary_plus.e() == w.e());
  525. DiyFp ten_mk; // Cached power of ten: 10^-k
  526. int mk; // -k
  527. int ten_mk_minimal_binary_exponent =
  528. kMinimalTargetExponent - (w.e() + DiyFp::kSignificandSize);
  529. int ten_mk_maximal_binary_exponent =
  530. kMaximalTargetExponent - (w.e() + DiyFp::kSignificandSize);
  531. PowersOfTenCache::GetCachedPowerForBinaryExponentRange(
  532. ten_mk_minimal_binary_exponent,
  533. ten_mk_maximal_binary_exponent,
  534. &ten_mk, &mk);
  535. DOUBLE_CONVERSION_ASSERT((kMinimalTargetExponent <= w.e() + ten_mk.e() +
  536. DiyFp::kSignificandSize) &&
  537. (kMaximalTargetExponent >= w.e() + ten_mk.e() +
  538. DiyFp::kSignificandSize));
  539. // Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a
  540. // 64 bit significand and ten_mk is thus only precise up to 64 bits.
  541. // The DiyFp::Times procedure rounds its result, and ten_mk is approximated
  542. // too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now
  543. // off by a small amount.
  544. // In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w.
  545. // In other words: let f = scaled_w.f() and e = scaled_w.e(), then
  546. // (f-1) * 2^e < w*10^k < (f+1) * 2^e
  547. DiyFp scaled_w = DiyFp::Times(w, ten_mk);
  548. DOUBLE_CONVERSION_ASSERT(scaled_w.e() ==
  549. boundary_plus.e() + ten_mk.e() + DiyFp::kSignificandSize);
  550. // In theory it would be possible to avoid some recomputations by computing
  551. // the difference between w and boundary_minus/plus (a power of 2) and to
  552. // compute scaled_boundary_minus/plus by subtracting/adding from
  553. // scaled_w. However the code becomes much less readable and the speed
  554. // enhancements are not terrific.
  555. DiyFp scaled_boundary_minus = DiyFp::Times(boundary_minus, ten_mk);
  556. DiyFp scaled_boundary_plus = DiyFp::Times(boundary_plus, ten_mk);
  557. // DigitGen will generate the digits of scaled_w. Therefore we have
  558. // v == (double) (scaled_w * 10^-mk).
  559. // Set decimal_exponent == -mk and pass it to DigitGen. If scaled_w is not an
  560. // integer than it will be updated. For instance if scaled_w == 1.23 then
  561. // the buffer will be filled with "123" and the decimal_exponent will be
  562. // decreased by 2.
  563. int kappa;
  564. bool result = DigitGen(scaled_boundary_minus, scaled_w, scaled_boundary_plus,
  565. buffer, length, &kappa);
  566. *decimal_exponent = -mk + kappa;
  567. return result;
  568. }
  569. // The "counted" version of grisu3 (see above) only generates requested_digits
  570. // number of digits. This version does not generate the shortest representation,
  571. // and with enough requested digits 0.1 will at some point print as 0.9999999...
  572. // Grisu3 is too imprecise for real halfway cases (1.5 will not work) and
  573. // therefore the rounding strategy for halfway cases is irrelevant.
  574. static bool Grisu3Counted(double v,
  575. int requested_digits,
  576. Vector<char> buffer,
  577. int* length,
  578. int* decimal_exponent) {
  579. DiyFp w = Double(v).AsNormalizedDiyFp();
  580. DiyFp ten_mk; // Cached power of ten: 10^-k
  581. int mk; // -k
  582. int ten_mk_minimal_binary_exponent =
  583. kMinimalTargetExponent - (w.e() + DiyFp::kSignificandSize);
  584. int ten_mk_maximal_binary_exponent =
  585. kMaximalTargetExponent - (w.e() + DiyFp::kSignificandSize);
  586. PowersOfTenCache::GetCachedPowerForBinaryExponentRange(
  587. ten_mk_minimal_binary_exponent,
  588. ten_mk_maximal_binary_exponent,
  589. &ten_mk, &mk);
  590. DOUBLE_CONVERSION_ASSERT((kMinimalTargetExponent <= w.e() + ten_mk.e() +
  591. DiyFp::kSignificandSize) &&
  592. (kMaximalTargetExponent >= w.e() + ten_mk.e() +
  593. DiyFp::kSignificandSize));
  594. // Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a
  595. // 64 bit significand and ten_mk is thus only precise up to 64 bits.
  596. // The DiyFp::Times procedure rounds its result, and ten_mk is approximated
  597. // too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now
  598. // off by a small amount.
  599. // In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w.
  600. // In other words: let f = scaled_w.f() and e = scaled_w.e(), then
  601. // (f-1) * 2^e < w*10^k < (f+1) * 2^e
  602. DiyFp scaled_w = DiyFp::Times(w, ten_mk);
  603. // We now have (double) (scaled_w * 10^-mk).
  604. // DigitGen will generate the first requested_digits digits of scaled_w and
  605. // return together with a kappa such that scaled_w ~= buffer * 10^kappa. (It
  606. // will not always be exactly the same since DigitGenCounted only produces a
  607. // limited number of digits.)
  608. int kappa;
  609. bool result = DigitGenCounted(scaled_w, requested_digits,
  610. buffer, length, &kappa);
  611. *decimal_exponent = -mk + kappa;
  612. return result;
  613. }
  614. bool FastDtoa(double v,
  615. FastDtoaMode mode,
  616. int requested_digits,
  617. Vector<char> buffer,
  618. int* length,
  619. int* decimal_point) {
  620. DOUBLE_CONVERSION_ASSERT(v > 0);
  621. DOUBLE_CONVERSION_ASSERT(!Double(v).IsSpecial());
  622. bool result = false;
  623. int decimal_exponent = 0;
  624. switch (mode) {
  625. case FAST_DTOA_SHORTEST:
  626. case FAST_DTOA_SHORTEST_SINGLE:
  627. result = Grisu3(v, mode, buffer, length, &decimal_exponent);
  628. break;
  629. case FAST_DTOA_PRECISION:
  630. result = Grisu3Counted(v, requested_digits,
  631. buffer, length, &decimal_exponent);
  632. break;
  633. default:
  634. DOUBLE_CONVERSION_UNREACHABLE();
  635. }
  636. if (result) {
  637. *decimal_point = *length + decimal_exponent;
  638. buffer[*length] = '\0';
  639. }
  640. return result;
  641. }
  642. } // namespace double_conversion
  643. // ICU PATCH: Close ICU namespace
  644. U_NAMESPACE_END
  645. #endif // ICU PATCH: close #if !UCONFIG_NO_FORMATTING