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.

640 lines
27 KiB

  1. // Copyright 2010 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 <math.h>
  28. #include "bignum-dtoa.h"
  29. #include "bignum.h"
  30. #include "ieee.h"
  31. namespace double_conversion {
  32. static int NormalizedExponent(uint64_t significand, int exponent) {
  33. ASSERT(significand != 0);
  34. while ((significand & Double::kHiddenBit) == 0) {
  35. significand = significand << 1;
  36. exponent = exponent - 1;
  37. }
  38. return exponent;
  39. }
  40. // Forward declarations:
  41. // Returns an estimation of k such that 10^(k-1) <= v < 10^k.
  42. static int EstimatePower(int exponent);
  43. // Computes v / 10^estimated_power exactly, as a ratio of two bignums, numerator
  44. // and denominator.
  45. static void InitialScaledStartValues(uint64_t significand,
  46. int exponent,
  47. bool lower_boundary_is_closer,
  48. int estimated_power,
  49. bool need_boundary_deltas,
  50. Bignum* numerator,
  51. Bignum* denominator,
  52. Bignum* delta_minus,
  53. Bignum* delta_plus);
  54. // Multiplies numerator/denominator so that its values lies in the range 1-10.
  55. // Returns decimal_point s.t.
  56. // v = numerator'/denominator' * 10^(decimal_point-1)
  57. // where numerator' and denominator' are the values of numerator and
  58. // denominator after the call to this function.
  59. static void FixupMultiply10(int estimated_power, bool is_even,
  60. int* decimal_point,
  61. Bignum* numerator, Bignum* denominator,
  62. Bignum* delta_minus, Bignum* delta_plus);
  63. // Generates digits from the left to the right and stops when the generated
  64. // digits yield the shortest decimal representation of v.
  65. static void GenerateShortestDigits(Bignum* numerator, Bignum* denominator,
  66. Bignum* delta_minus, Bignum* delta_plus,
  67. bool is_even,
  68. Vector<char> buffer, int* length);
  69. // Generates 'requested_digits' after the decimal point.
  70. static void BignumToFixed(int requested_digits, int* decimal_point,
  71. Bignum* numerator, Bignum* denominator,
  72. Vector<char>(buffer), int* length);
  73. // Generates 'count' digits of numerator/denominator.
  74. // Once 'count' digits have been produced rounds the result depending on the
  75. // remainder (remainders of exactly .5 round upwards). Might update the
  76. // decimal_point when rounding up (for example for 0.9999).
  77. static void GenerateCountedDigits(int count, int* decimal_point,
  78. Bignum* numerator, Bignum* denominator,
  79. Vector<char>(buffer), int* length);
  80. void BignumDtoa(double v, BignumDtoaMode mode, int requested_digits,
  81. Vector<char> buffer, int* length, int* decimal_point) {
  82. ASSERT(v > 0);
  83. ASSERT(!Double(v).IsSpecial());
  84. uint64_t significand;
  85. int exponent;
  86. bool lower_boundary_is_closer;
  87. if (mode == BIGNUM_DTOA_SHORTEST_SINGLE) {
  88. float f = static_cast<float>(v);
  89. ASSERT(f == v);
  90. significand = Single(f).Significand();
  91. exponent = Single(f).Exponent();
  92. lower_boundary_is_closer = Single(f).LowerBoundaryIsCloser();
  93. } else {
  94. significand = Double(v).Significand();
  95. exponent = Double(v).Exponent();
  96. lower_boundary_is_closer = Double(v).LowerBoundaryIsCloser();
  97. }
  98. bool need_boundary_deltas =
  99. (mode == BIGNUM_DTOA_SHORTEST || mode == BIGNUM_DTOA_SHORTEST_SINGLE);
  100. bool is_even = (significand & 1) == 0;
  101. int normalized_exponent = NormalizedExponent(significand, exponent);
  102. // estimated_power might be too low by 1.
  103. int estimated_power = EstimatePower(normalized_exponent);
  104. // Shortcut for Fixed.
  105. // The requested digits correspond to the digits after the point. If the
  106. // number is much too small, then there is no need in trying to get any
  107. // digits.
  108. if (mode == BIGNUM_DTOA_FIXED && -estimated_power - 1 > requested_digits) {
  109. buffer[0] = '\0';
  110. *length = 0;
  111. // Set decimal-point to -requested_digits. This is what Gay does.
  112. // Note that it should not have any effect anyways since the string is
  113. // empty.
  114. *decimal_point = -requested_digits;
  115. return;
  116. }
  117. Bignum numerator;
  118. Bignum denominator;
  119. Bignum delta_minus;
  120. Bignum delta_plus;
  121. // Make sure the bignum can grow large enough. The smallest double equals
  122. // 4e-324. In this case the denominator needs fewer than 324*4 binary digits.
  123. // The maximum double is 1.7976931348623157e308 which needs fewer than
  124. // 308*4 binary digits.
  125. ASSERT(Bignum::kMaxSignificantBits >= 324*4);
  126. InitialScaledStartValues(significand, exponent, lower_boundary_is_closer,
  127. estimated_power, need_boundary_deltas,
  128. &numerator, &denominator,
  129. &delta_minus, &delta_plus);
  130. // We now have v = (numerator / denominator) * 10^estimated_power.
  131. FixupMultiply10(estimated_power, is_even, decimal_point,
  132. &numerator, &denominator,
  133. &delta_minus, &delta_plus);
  134. // We now have v = (numerator / denominator) * 10^(decimal_point-1), and
  135. // 1 <= (numerator + delta_plus) / denominator < 10
  136. switch (mode) {
  137. case BIGNUM_DTOA_SHORTEST:
  138. case BIGNUM_DTOA_SHORTEST_SINGLE:
  139. GenerateShortestDigits(&numerator, &denominator,
  140. &delta_minus, &delta_plus,
  141. is_even, buffer, length);
  142. break;
  143. case BIGNUM_DTOA_FIXED:
  144. BignumToFixed(requested_digits, decimal_point,
  145. &numerator, &denominator,
  146. buffer, length);
  147. break;
  148. case BIGNUM_DTOA_PRECISION:
  149. GenerateCountedDigits(requested_digits, decimal_point,
  150. &numerator, &denominator,
  151. buffer, length);
  152. break;
  153. default:
  154. UNREACHABLE();
  155. }
  156. buffer[*length] = '\0';
  157. }
  158. // The procedure starts generating digits from the left to the right and stops
  159. // when the generated digits yield the shortest decimal representation of v. A
  160. // decimal representation of v is a number lying closer to v than to any other
  161. // double, so it converts to v when read.
  162. //
  163. // This is true if d, the decimal representation, is between m- and m+, the
  164. // upper and lower boundaries. d must be strictly between them if !is_even.
  165. // m- := (numerator - delta_minus) / denominator
  166. // m+ := (numerator + delta_plus) / denominator
  167. //
  168. // Precondition: 0 <= (numerator+delta_plus) / denominator < 10.
  169. // If 1 <= (numerator+delta_plus) / denominator < 10 then no leading 0 digit
  170. // will be produced. This should be the standard precondition.
  171. static void GenerateShortestDigits(Bignum* numerator, Bignum* denominator,
  172. Bignum* delta_minus, Bignum* delta_plus,
  173. bool is_even,
  174. Vector<char> buffer, int* length) {
  175. // Small optimization: if delta_minus and delta_plus are the same just reuse
  176. // one of the two bignums.
  177. if (Bignum::Equal(*delta_minus, *delta_plus)) {
  178. delta_plus = delta_minus;
  179. }
  180. *length = 0;
  181. while (true) {
  182. uint16_t digit;
  183. digit = numerator->DivideModuloIntBignum(*denominator);
  184. ASSERT(digit <= 9); // digit is a uint16_t and therefore always positive.
  185. // digit = numerator / denominator (integer division).
  186. // numerator = numerator % denominator.
  187. buffer[(*length)++] = digit + '0';
  188. // Can we stop already?
  189. // If the remainder of the division is less than the distance to the lower
  190. // boundary we can stop. In this case we simply round down (discarding the
  191. // remainder).
  192. // Similarly we test if we can round up (using the upper boundary).
  193. bool in_delta_room_minus;
  194. bool in_delta_room_plus;
  195. if (is_even) {
  196. in_delta_room_minus = Bignum::LessEqual(*numerator, *delta_minus);
  197. } else {
  198. in_delta_room_minus = Bignum::Less(*numerator, *delta_minus);
  199. }
  200. if (is_even) {
  201. in_delta_room_plus =
  202. Bignum::PlusCompare(*numerator, *delta_plus, *denominator) >= 0;
  203. } else {
  204. in_delta_room_plus =
  205. Bignum::PlusCompare(*numerator, *delta_plus, *denominator) > 0;
  206. }
  207. if (!in_delta_room_minus && !in_delta_room_plus) {
  208. // Prepare for next iteration.
  209. numerator->Times10();
  210. delta_minus->Times10();
  211. // We optimized delta_plus to be equal to delta_minus (if they share the
  212. // same value). So don't multiply delta_plus if they point to the same
  213. // object.
  214. if (delta_minus != delta_plus) {
  215. delta_plus->Times10();
  216. }
  217. } else if (in_delta_room_minus && in_delta_room_plus) {
  218. // Let's see if 2*numerator < denominator.
  219. // If yes, then the next digit would be < 5 and we can round down.
  220. int compare = Bignum::PlusCompare(*numerator, *numerator, *denominator);
  221. if (compare < 0) {
  222. // Remaining digits are less than .5. -> Round down (== do nothing).
  223. } else if (compare > 0) {
  224. // Remaining digits are more than .5 of denominator. -> Round up.
  225. // Note that the last digit could not be a '9' as otherwise the whole
  226. // loop would have stopped earlier.
  227. // We still have an assert here in case the preconditions were not
  228. // satisfied.
  229. ASSERT(buffer[(*length) - 1] != '9');
  230. buffer[(*length) - 1]++;
  231. } else {
  232. // Halfway case.
  233. // TODO(floitsch): need a way to solve half-way cases.
  234. // For now let's round towards even (since this is what Gay seems to
  235. // do).
  236. if ((buffer[(*length) - 1] - '0') % 2 == 0) {
  237. // Round down => Do nothing.
  238. } else {
  239. ASSERT(buffer[(*length) - 1] != '9');
  240. buffer[(*length) - 1]++;
  241. }
  242. }
  243. return;
  244. } else if (in_delta_room_minus) {
  245. // Round down (== do nothing).
  246. return;
  247. } else { // in_delta_room_plus
  248. // Round up.
  249. // Note again that the last digit could not be '9' since this would have
  250. // stopped the loop earlier.
  251. // We still have an ASSERT here, in case the preconditions were not
  252. // satisfied.
  253. ASSERT(buffer[(*length) -1] != '9');
  254. buffer[(*length) - 1]++;
  255. return;
  256. }
  257. }
  258. }
  259. // Let v = numerator / denominator < 10.
  260. // Then we generate 'count' digits of d = x.xxxxx... (without the decimal point)
  261. // from left to right. Once 'count' digits have been produced we decide wether
  262. // to round up or down. Remainders of exactly .5 round upwards. Numbers such
  263. // as 9.999999 propagate a carry all the way, and change the
  264. // exponent (decimal_point), when rounding upwards.
  265. static void GenerateCountedDigits(int count, int* decimal_point,
  266. Bignum* numerator, Bignum* denominator,
  267. Vector<char>(buffer), int* length) {
  268. ASSERT(count >= 0);
  269. for (int i = 0; i < count - 1; ++i) {
  270. uint16_t digit;
  271. digit = numerator->DivideModuloIntBignum(*denominator);
  272. ASSERT(digit <= 9); // digit is a uint16_t and therefore always positive.
  273. // digit = numerator / denominator (integer division).
  274. // numerator = numerator % denominator.
  275. buffer[i] = digit + '0';
  276. // Prepare for next iteration.
  277. numerator->Times10();
  278. }
  279. // Generate the last digit.
  280. uint16_t digit;
  281. digit = numerator->DivideModuloIntBignum(*denominator);
  282. if (Bignum::PlusCompare(*numerator, *numerator, *denominator) >= 0) {
  283. digit++;
  284. }
  285. buffer[count - 1] = digit + '0';
  286. // Correct bad digits (in case we had a sequence of '9's). Propagate the
  287. // carry until we hat a non-'9' or til we reach the first digit.
  288. for (int i = count - 1; i > 0; --i) {
  289. if (buffer[i] != '0' + 10) break;
  290. buffer[i] = '0';
  291. buffer[i - 1]++;
  292. }
  293. if (buffer[0] == '0' + 10) {
  294. // Propagate a carry past the top place.
  295. buffer[0] = '1';
  296. (*decimal_point)++;
  297. }
  298. *length = count;
  299. }
  300. // Generates 'requested_digits' after the decimal point. It might omit
  301. // trailing '0's. If the input number is too small then no digits at all are
  302. // generated (ex.: 2 fixed digits for 0.00001).
  303. //
  304. // Input verifies: 1 <= (numerator + delta) / denominator < 10.
  305. static void BignumToFixed(int requested_digits, int* decimal_point,
  306. Bignum* numerator, Bignum* denominator,
  307. Vector<char>(buffer), int* length) {
  308. // Note that we have to look at more than just the requested_digits, since
  309. // a number could be rounded up. Example: v=0.5 with requested_digits=0.
  310. // Even though the power of v equals 0 we can't just stop here.
  311. if (-(*decimal_point) > requested_digits) {
  312. // The number is definitively too small.
  313. // Ex: 0.001 with requested_digits == 1.
  314. // Set decimal-point to -requested_digits. This is what Gay does.
  315. // Note that it should not have any effect anyways since the string is
  316. // empty.
  317. *decimal_point = -requested_digits;
  318. *length = 0;
  319. return;
  320. } else if (-(*decimal_point) == requested_digits) {
  321. // We only need to verify if the number rounds down or up.
  322. // Ex: 0.04 and 0.06 with requested_digits == 1.
  323. ASSERT(*decimal_point == -requested_digits);
  324. // Initially the fraction lies in range (1, 10]. Multiply the denominator
  325. // by 10 so that we can compare more easily.
  326. denominator->Times10();
  327. if (Bignum::PlusCompare(*numerator, *numerator, *denominator) >= 0) {
  328. // If the fraction is >= 0.5 then we have to include the rounded
  329. // digit.
  330. buffer[0] = '1';
  331. *length = 1;
  332. (*decimal_point)++;
  333. } else {
  334. // Note that we caught most of similar cases earlier.
  335. *length = 0;
  336. }
  337. return;
  338. } else {
  339. // The requested digits correspond to the digits after the point.
  340. // The variable 'needed_digits' includes the digits before the point.
  341. int needed_digits = (*decimal_point) + requested_digits;
  342. GenerateCountedDigits(needed_digits, decimal_point,
  343. numerator, denominator,
  344. buffer, length);
  345. }
  346. }
  347. // Returns an estimation of k such that 10^(k-1) <= v < 10^k where
  348. // v = f * 2^exponent and 2^52 <= f < 2^53.
  349. // v is hence a normalized double with the given exponent. The output is an
  350. // approximation for the exponent of the decimal approimation .digits * 10^k.
  351. //
  352. // The result might undershoot by 1 in which case 10^k <= v < 10^k+1.
  353. // Note: this property holds for v's upper boundary m+ too.
  354. // 10^k <= m+ < 10^k+1.
  355. // (see explanation below).
  356. //
  357. // Examples:
  358. // EstimatePower(0) => 16
  359. // EstimatePower(-52) => 0
  360. //
  361. // Note: e >= 0 => EstimatedPower(e) > 0. No similar claim can be made for e<0.
  362. static int EstimatePower(int exponent) {
  363. // This function estimates log10 of v where v = f*2^e (with e == exponent).
  364. // Note that 10^floor(log10(v)) <= v, but v <= 10^ceil(log10(v)).
  365. // Note that f is bounded by its container size. Let p = 53 (the double's
  366. // significand size). Then 2^(p-1) <= f < 2^p.
  367. //
  368. // Given that log10(v) == log2(v)/log2(10) and e+(len(f)-1) is quite close
  369. // to log2(v) the function is simplified to (e+(len(f)-1)/log2(10)).
  370. // The computed number undershoots by less than 0.631 (when we compute log3
  371. // and not log10).
  372. //
  373. // Optimization: since we only need an approximated result this computation
  374. // can be performed on 64 bit integers. On x86/x64 architecture the speedup is
  375. // not really measurable, though.
  376. //
  377. // Since we want to avoid overshooting we decrement by 1e10 so that
  378. // floating-point imprecisions don't affect us.
  379. //
  380. // Explanation for v's boundary m+: the computation takes advantage of
  381. // the fact that 2^(p-1) <= f < 2^p. Boundaries still satisfy this requirement
  382. // (even for denormals where the delta can be much more important).
  383. const double k1Log10 = 0.30102999566398114; // 1/lg(10)
  384. // For doubles len(f) == 53 (don't forget the hidden bit).
  385. const int kSignificandSize = Double::kSignificandSize;
  386. double estimate = ceil((exponent + kSignificandSize - 1) * k1Log10 - 1e-10);
  387. return static_cast<int>(estimate);
  388. }
  389. // See comments for InitialScaledStartValues.
  390. static void InitialScaledStartValuesPositiveExponent(
  391. uint64_t significand, int exponent,
  392. int estimated_power, bool need_boundary_deltas,
  393. Bignum* numerator, Bignum* denominator,
  394. Bignum* delta_minus, Bignum* delta_plus) {
  395. // A positive exponent implies a positive power.
  396. ASSERT(estimated_power >= 0);
  397. // Since the estimated_power is positive we simply multiply the denominator
  398. // by 10^estimated_power.
  399. // numerator = v.
  400. numerator->AssignUInt64(significand);
  401. numerator->ShiftLeft(exponent);
  402. // denominator = 10^estimated_power.
  403. denominator->AssignPowerUInt16(10, estimated_power);
  404. if (need_boundary_deltas) {
  405. // Introduce a common denominator so that the deltas to the boundaries are
  406. // integers.
  407. denominator->ShiftLeft(1);
  408. numerator->ShiftLeft(1);
  409. // Let v = f * 2^e, then m+ - v = 1/2 * 2^e; With the common
  410. // denominator (of 2) delta_plus equals 2^e.
  411. delta_plus->AssignUInt16(1);
  412. delta_plus->ShiftLeft(exponent);
  413. // Same for delta_minus. The adjustments if f == 2^p-1 are done later.
  414. delta_minus->AssignUInt16(1);
  415. delta_minus->ShiftLeft(exponent);
  416. }
  417. }
  418. // See comments for InitialScaledStartValues
  419. static void InitialScaledStartValuesNegativeExponentPositivePower(
  420. uint64_t significand, int exponent,
  421. int estimated_power, bool need_boundary_deltas,
  422. Bignum* numerator, Bignum* denominator,
  423. Bignum* delta_minus, Bignum* delta_plus) {
  424. // v = f * 2^e with e < 0, and with estimated_power >= 0.
  425. // This means that e is close to 0 (have a look at how estimated_power is
  426. // computed).
  427. // numerator = significand
  428. // since v = significand * 2^exponent this is equivalent to
  429. // numerator = v * / 2^-exponent
  430. numerator->AssignUInt64(significand);
  431. // denominator = 10^estimated_power * 2^-exponent (with exponent < 0)
  432. denominator->AssignPowerUInt16(10, estimated_power);
  433. denominator->ShiftLeft(-exponent);
  434. if (need_boundary_deltas) {
  435. // Introduce a common denominator so that the deltas to the boundaries are
  436. // integers.
  437. denominator->ShiftLeft(1);
  438. numerator->ShiftLeft(1);
  439. // Let v = f * 2^e, then m+ - v = 1/2 * 2^e; With the common
  440. // denominator (of 2) delta_plus equals 2^e.
  441. // Given that the denominator already includes v's exponent the distance
  442. // to the boundaries is simply 1.
  443. delta_plus->AssignUInt16(1);
  444. // Same for delta_minus. The adjustments if f == 2^p-1 are done later.
  445. delta_minus->AssignUInt16(1);
  446. }
  447. }
  448. // See comments for InitialScaledStartValues
  449. static void InitialScaledStartValuesNegativeExponentNegativePower(
  450. uint64_t significand, int exponent,
  451. int estimated_power, bool need_boundary_deltas,
  452. Bignum* numerator, Bignum* denominator,
  453. Bignum* delta_minus, Bignum* delta_plus) {
  454. // Instead of multiplying the denominator with 10^estimated_power we
  455. // multiply all values (numerator and deltas) by 10^-estimated_power.
  456. // Use numerator as temporary container for power_ten.
  457. Bignum* power_ten = numerator;
  458. power_ten->AssignPowerUInt16(10, -estimated_power);
  459. if (need_boundary_deltas) {
  460. // Since power_ten == numerator we must make a copy of 10^estimated_power
  461. // before we complete the computation of the numerator.
  462. // delta_plus = delta_minus = 10^estimated_power
  463. delta_plus->AssignBignum(*power_ten);
  464. delta_minus->AssignBignum(*power_ten);
  465. }
  466. // numerator = significand * 2 * 10^-estimated_power
  467. // since v = significand * 2^exponent this is equivalent to
  468. // numerator = v * 10^-estimated_power * 2 * 2^-exponent.
  469. // Remember: numerator has been abused as power_ten. So no need to assign it
  470. // to itself.
  471. ASSERT(numerator == power_ten);
  472. numerator->MultiplyByUInt64(significand);
  473. // denominator = 2 * 2^-exponent with exponent < 0.
  474. denominator->AssignUInt16(1);
  475. denominator->ShiftLeft(-exponent);
  476. if (need_boundary_deltas) {
  477. // Introduce a common denominator so that the deltas to the boundaries are
  478. // integers.
  479. numerator->ShiftLeft(1);
  480. denominator->ShiftLeft(1);
  481. // With this shift the boundaries have their correct value, since
  482. // delta_plus = 10^-estimated_power, and
  483. // delta_minus = 10^-estimated_power.
  484. // These assignments have been done earlier.
  485. // The adjustments if f == 2^p-1 (lower boundary is closer) are done later.
  486. }
  487. }
  488. // Let v = significand * 2^exponent.
  489. // Computes v / 10^estimated_power exactly, as a ratio of two bignums, numerator
  490. // and denominator. The functions GenerateShortestDigits and
  491. // GenerateCountedDigits will then convert this ratio to its decimal
  492. // representation d, with the required accuracy.
  493. // Then d * 10^estimated_power is the representation of v.
  494. // (Note: the fraction and the estimated_power might get adjusted before
  495. // generating the decimal representation.)
  496. //
  497. // The initial start values consist of:
  498. // - a scaled numerator: s.t. numerator/denominator == v / 10^estimated_power.
  499. // - a scaled (common) denominator.
  500. // optionally (used by GenerateShortestDigits to decide if it has the shortest
  501. // decimal converting back to v):
  502. // - v - m-: the distance to the lower boundary.
  503. // - m+ - v: the distance to the upper boundary.
  504. //
  505. // v, m+, m-, and therefore v - m- and m+ - v all share the same denominator.
  506. //
  507. // Let ep == estimated_power, then the returned values will satisfy:
  508. // v / 10^ep = numerator / denominator.
  509. // v's boundarys m- and m+:
  510. // m- / 10^ep == v / 10^ep - delta_minus / denominator
  511. // m+ / 10^ep == v / 10^ep + delta_plus / denominator
  512. // Or in other words:
  513. // m- == v - delta_minus * 10^ep / denominator;
  514. // m+ == v + delta_plus * 10^ep / denominator;
  515. //
  516. // Since 10^(k-1) <= v < 10^k (with k == estimated_power)
  517. // or 10^k <= v < 10^(k+1)
  518. // we then have 0.1 <= numerator/denominator < 1
  519. // or 1 <= numerator/denominator < 10
  520. //
  521. // It is then easy to kickstart the digit-generation routine.
  522. //
  523. // The boundary-deltas are only filled if the mode equals BIGNUM_DTOA_SHORTEST
  524. // or BIGNUM_DTOA_SHORTEST_SINGLE.
  525. static void InitialScaledStartValues(uint64_t significand,
  526. int exponent,
  527. bool lower_boundary_is_closer,
  528. int estimated_power,
  529. bool need_boundary_deltas,
  530. Bignum* numerator,
  531. Bignum* denominator,
  532. Bignum* delta_minus,
  533. Bignum* delta_plus) {
  534. if (exponent >= 0) {
  535. InitialScaledStartValuesPositiveExponent(
  536. significand, exponent, estimated_power, need_boundary_deltas,
  537. numerator, denominator, delta_minus, delta_plus);
  538. } else if (estimated_power >= 0) {
  539. InitialScaledStartValuesNegativeExponentPositivePower(
  540. significand, exponent, estimated_power, need_boundary_deltas,
  541. numerator, denominator, delta_minus, delta_plus);
  542. } else {
  543. InitialScaledStartValuesNegativeExponentNegativePower(
  544. significand, exponent, estimated_power, need_boundary_deltas,
  545. numerator, denominator, delta_minus, delta_plus);
  546. }
  547. if (need_boundary_deltas && lower_boundary_is_closer) {
  548. // The lower boundary is closer at half the distance of "normal" numbers.
  549. // Increase the common denominator and adapt all but the delta_minus.
  550. denominator->ShiftLeft(1); // *2
  551. numerator->ShiftLeft(1); // *2
  552. delta_plus->ShiftLeft(1); // *2
  553. }
  554. }
  555. // This routine multiplies numerator/denominator so that its values lies in the
  556. // range 1-10. That is after a call to this function we have:
  557. // 1 <= (numerator + delta_plus) /denominator < 10.
  558. // Let numerator the input before modification and numerator' the argument
  559. // after modification, then the output-parameter decimal_point is such that
  560. // numerator / denominator * 10^estimated_power ==
  561. // numerator' / denominator' * 10^(decimal_point - 1)
  562. // In some cases estimated_power was too low, and this is already the case. We
  563. // then simply adjust the power so that 10^(k-1) <= v < 10^k (with k ==
  564. // estimated_power) but do not touch the numerator or denominator.
  565. // Otherwise the routine multiplies the numerator and the deltas by 10.
  566. static void FixupMultiply10(int estimated_power, bool is_even,
  567. int* decimal_point,
  568. Bignum* numerator, Bignum* denominator,
  569. Bignum* delta_minus, Bignum* delta_plus) {
  570. bool in_range;
  571. if (is_even) {
  572. // For IEEE doubles half-way cases (in decimal system numbers ending with 5)
  573. // are rounded to the closest floating-point number with even significand.
  574. in_range = Bignum::PlusCompare(*numerator, *delta_plus, *denominator) >= 0;
  575. } else {
  576. in_range = Bignum::PlusCompare(*numerator, *delta_plus, *denominator) > 0;
  577. }
  578. if (in_range) {
  579. // Since numerator + delta_plus >= denominator we already have
  580. // 1 <= numerator/denominator < 10. Simply update the estimated_power.
  581. *decimal_point = estimated_power + 1;
  582. } else {
  583. *decimal_point = estimated_power;
  584. numerator->Times10();
  585. if (Bignum::Equal(*delta_minus, *delta_plus)) {
  586. delta_minus->Times10();
  587. delta_plus->AssignBignum(*delta_minus);
  588. } else {
  589. delta_minus->Times10();
  590. delta_plus->Times10();
  591. }
  592. }
  593. }
  594. } // namespace double_conversion