You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

665 lines
30 KiB

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