Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

641 righe
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 <cmath>
  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. for (;;) {
  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)++] = static_cast<char>(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] = static_cast<char>(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. ASSERT(digit <= 10);
  286. buffer[count - 1] = static_cast<char>(digit + '0');
  287. // Correct bad digits (in case we had a sequence of '9's). Propagate the
  288. // carry until we hat a non-'9' or til we reach the first digit.
  289. for (int i = count - 1; i > 0; --i) {
  290. if (buffer[i] != '0' + 10) break;
  291. buffer[i] = '0';
  292. buffer[i - 1]++;
  293. }
  294. if (buffer[0] == '0' + 10) {
  295. // Propagate a carry past the top place.
  296. buffer[0] = '1';
  297. (*decimal_point)++;
  298. }
  299. *length = count;
  300. }
  301. // Generates 'requested_digits' after the decimal point. It might omit
  302. // trailing '0's. If the input number is too small then no digits at all are
  303. // generated (ex.: 2 fixed digits for 0.00001).
  304. //
  305. // Input verifies: 1 <= (numerator + delta) / denominator < 10.
  306. static void BignumToFixed(int requested_digits, int* decimal_point,
  307. Bignum* numerator, Bignum* denominator,
  308. Vector<char>(buffer), int* length) {
  309. // Note that we have to look at more than just the requested_digits, since
  310. // a number could be rounded up. Example: v=0.5 with requested_digits=0.
  311. // Even though the power of v equals 0 we can't just stop here.
  312. if (-(*decimal_point) > requested_digits) {
  313. // The number is definitively too small.
  314. // Ex: 0.001 with requested_digits == 1.
  315. // Set decimal-point to -requested_digits. This is what Gay does.
  316. // Note that it should not have any effect anyways since the string is
  317. // empty.
  318. *decimal_point = -requested_digits;
  319. *length = 0;
  320. return;
  321. } else if (-(*decimal_point) == requested_digits) {
  322. // We only need to verify if the number rounds down or up.
  323. // Ex: 0.04 and 0.06 with requested_digits == 1.
  324. ASSERT(*decimal_point == -requested_digits);
  325. // Initially the fraction lies in range (1, 10]. Multiply the denominator
  326. // by 10 so that we can compare more easily.
  327. denominator->Times10();
  328. if (Bignum::PlusCompare(*numerator, *numerator, *denominator) >= 0) {
  329. // If the fraction is >= 0.5 then we have to include the rounded
  330. // digit.
  331. buffer[0] = '1';
  332. *length = 1;
  333. (*decimal_point)++;
  334. } else {
  335. // Note that we caught most of similar cases earlier.
  336. *length = 0;
  337. }
  338. return;
  339. } else {
  340. // The requested digits correspond to the digits after the point.
  341. // The variable 'needed_digits' includes the digits before the point.
  342. int needed_digits = (*decimal_point) + requested_digits;
  343. GenerateCountedDigits(needed_digits, decimal_point,
  344. numerator, denominator,
  345. buffer, length);
  346. }
  347. }
  348. // Returns an estimation of k such that 10^(k-1) <= v < 10^k where
  349. // v = f * 2^exponent and 2^52 <= f < 2^53.
  350. // v is hence a normalized double with the given exponent. The output is an
  351. // approximation for the exponent of the decimal approimation .digits * 10^k.
  352. //
  353. // The result might undershoot by 1 in which case 10^k <= v < 10^k+1.
  354. // Note: this property holds for v's upper boundary m+ too.
  355. // 10^k <= m+ < 10^k+1.
  356. // (see explanation below).
  357. //
  358. // Examples:
  359. // EstimatePower(0) => 16
  360. // EstimatePower(-52) => 0
  361. //
  362. // Note: e >= 0 => EstimatedPower(e) > 0. No similar claim can be made for e<0.
  363. static int EstimatePower(int exponent) {
  364. // This function estimates log10 of v where v = f*2^e (with e == exponent).
  365. // Note that 10^floor(log10(v)) <= v, but v <= 10^ceil(log10(v)).
  366. // Note that f is bounded by its container size. Let p = 53 (the double's
  367. // significand size). Then 2^(p-1) <= f < 2^p.
  368. //
  369. // Given that log10(v) == log2(v)/log2(10) and e+(len(f)-1) is quite close
  370. // to log2(v) the function is simplified to (e+(len(f)-1)/log2(10)).
  371. // The computed number undershoots by less than 0.631 (when we compute log3
  372. // and not log10).
  373. //
  374. // Optimization: since we only need an approximated result this computation
  375. // can be performed on 64 bit integers. On x86/x64 architecture the speedup is
  376. // not really measurable, though.
  377. //
  378. // Since we want to avoid overshooting we decrement by 1e10 so that
  379. // floating-point imprecisions don't affect us.
  380. //
  381. // Explanation for v's boundary m+: the computation takes advantage of
  382. // the fact that 2^(p-1) <= f < 2^p. Boundaries still satisfy this requirement
  383. // (even for denormals where the delta can be much more important).
  384. const double k1Log10 = 0.30102999566398114; // 1/lg(10)
  385. // For doubles len(f) == 53 (don't forget the hidden bit).
  386. const int kSignificandSize = Double::kSignificandSize;
  387. double estimate = ceil((exponent + kSignificandSize - 1) * k1Log10 - 1e-10);
  388. return static_cast<int>(estimate);
  389. }
  390. // See comments for InitialScaledStartValues.
  391. static void InitialScaledStartValuesPositiveExponent(
  392. uint64_t significand, int exponent,
  393. int estimated_power, bool need_boundary_deltas,
  394. Bignum* numerator, Bignum* denominator,
  395. Bignum* delta_minus, Bignum* delta_plus) {
  396. // A positive exponent implies a positive power.
  397. ASSERT(estimated_power >= 0);
  398. // Since the estimated_power is positive we simply multiply the denominator
  399. // by 10^estimated_power.
  400. // numerator = v.
  401. numerator->AssignUInt64(significand);
  402. numerator->ShiftLeft(exponent);
  403. // denominator = 10^estimated_power.
  404. denominator->AssignPowerUInt16(10, estimated_power);
  405. if (need_boundary_deltas) {
  406. // Introduce a common denominator so that the deltas to the boundaries are
  407. // integers.
  408. denominator->ShiftLeft(1);
  409. numerator->ShiftLeft(1);
  410. // Let v = f * 2^e, then m+ - v = 1/2 * 2^e; With the common
  411. // denominator (of 2) delta_plus equals 2^e.
  412. delta_plus->AssignUInt16(1);
  413. delta_plus->ShiftLeft(exponent);
  414. // Same for delta_minus. The adjustments if f == 2^p-1 are done later.
  415. delta_minus->AssignUInt16(1);
  416. delta_minus->ShiftLeft(exponent);
  417. }
  418. }
  419. // See comments for InitialScaledStartValues
  420. static void InitialScaledStartValuesNegativeExponentPositivePower(
  421. uint64_t significand, int exponent,
  422. int estimated_power, bool need_boundary_deltas,
  423. Bignum* numerator, Bignum* denominator,
  424. Bignum* delta_minus, Bignum* delta_plus) {
  425. // v = f * 2^e with e < 0, and with estimated_power >= 0.
  426. // This means that e is close to 0 (have a look at how estimated_power is
  427. // computed).
  428. // numerator = significand
  429. // since v = significand * 2^exponent this is equivalent to
  430. // numerator = v * / 2^-exponent
  431. numerator->AssignUInt64(significand);
  432. // denominator = 10^estimated_power * 2^-exponent (with exponent < 0)
  433. denominator->AssignPowerUInt16(10, estimated_power);
  434. denominator->ShiftLeft(-exponent);
  435. if (need_boundary_deltas) {
  436. // Introduce a common denominator so that the deltas to the boundaries are
  437. // integers.
  438. denominator->ShiftLeft(1);
  439. numerator->ShiftLeft(1);
  440. // Let v = f * 2^e, then m+ - v = 1/2 * 2^e; With the common
  441. // denominator (of 2) delta_plus equals 2^e.
  442. // Given that the denominator already includes v's exponent the distance
  443. // to the boundaries is simply 1.
  444. delta_plus->AssignUInt16(1);
  445. // Same for delta_minus. The adjustments if f == 2^p-1 are done later.
  446. delta_minus->AssignUInt16(1);
  447. }
  448. }
  449. // See comments for InitialScaledStartValues
  450. static void InitialScaledStartValuesNegativeExponentNegativePower(
  451. uint64_t significand, int exponent,
  452. int estimated_power, bool need_boundary_deltas,
  453. Bignum* numerator, Bignum* denominator,
  454. Bignum* delta_minus, Bignum* delta_plus) {
  455. // Instead of multiplying the denominator with 10^estimated_power we
  456. // multiply all values (numerator and deltas) by 10^-estimated_power.
  457. // Use numerator as temporary container for power_ten.
  458. Bignum* power_ten = numerator;
  459. power_ten->AssignPowerUInt16(10, -estimated_power);
  460. if (need_boundary_deltas) {
  461. // Since power_ten == numerator we must make a copy of 10^estimated_power
  462. // before we complete the computation of the numerator.
  463. // delta_plus = delta_minus = 10^estimated_power
  464. delta_plus->AssignBignum(*power_ten);
  465. delta_minus->AssignBignum(*power_ten);
  466. }
  467. // numerator = significand * 2 * 10^-estimated_power
  468. // since v = significand * 2^exponent this is equivalent to
  469. // numerator = v * 10^-estimated_power * 2 * 2^-exponent.
  470. // Remember: numerator has been abused as power_ten. So no need to assign it
  471. // to itself.
  472. ASSERT(numerator == power_ten);
  473. numerator->MultiplyByUInt64(significand);
  474. // denominator = 2 * 2^-exponent with exponent < 0.
  475. denominator->AssignUInt16(1);
  476. denominator->ShiftLeft(-exponent);
  477. if (need_boundary_deltas) {
  478. // Introduce a common denominator so that the deltas to the boundaries are
  479. // integers.
  480. numerator->ShiftLeft(1);
  481. denominator->ShiftLeft(1);
  482. // With this shift the boundaries have their correct value, since
  483. // delta_plus = 10^-estimated_power, and
  484. // delta_minus = 10^-estimated_power.
  485. // These assignments have been done earlier.
  486. // The adjustments if f == 2^p-1 (lower boundary is closer) are done later.
  487. }
  488. }
  489. // Let v = significand * 2^exponent.
  490. // Computes v / 10^estimated_power exactly, as a ratio of two bignums, numerator
  491. // and denominator. The functions GenerateShortestDigits and
  492. // GenerateCountedDigits will then convert this ratio to its decimal
  493. // representation d, with the required accuracy.
  494. // Then d * 10^estimated_power is the representation of v.
  495. // (Note: the fraction and the estimated_power might get adjusted before
  496. // generating the decimal representation.)
  497. //
  498. // The initial start values consist of:
  499. // - a scaled numerator: s.t. numerator/denominator == v / 10^estimated_power.
  500. // - a scaled (common) denominator.
  501. // optionally (used by GenerateShortestDigits to decide if it has the shortest
  502. // decimal converting back to v):
  503. // - v - m-: the distance to the lower boundary.
  504. // - m+ - v: the distance to the upper boundary.
  505. //
  506. // v, m+, m-, and therefore v - m- and m+ - v all share the same denominator.
  507. //
  508. // Let ep == estimated_power, then the returned values will satisfy:
  509. // v / 10^ep = numerator / denominator.
  510. // v's boundarys m- and m+:
  511. // m- / 10^ep == v / 10^ep - delta_minus / denominator
  512. // m+ / 10^ep == v / 10^ep + delta_plus / denominator
  513. // Or in other words:
  514. // m- == v - delta_minus * 10^ep / denominator;
  515. // m+ == v + delta_plus * 10^ep / denominator;
  516. //
  517. // Since 10^(k-1) <= v < 10^k (with k == estimated_power)
  518. // or 10^k <= v < 10^(k+1)
  519. // we then have 0.1 <= numerator/denominator < 1
  520. // or 1 <= numerator/denominator < 10
  521. //
  522. // It is then easy to kickstart the digit-generation routine.
  523. //
  524. // The boundary-deltas are only filled if the mode equals BIGNUM_DTOA_SHORTEST
  525. // or BIGNUM_DTOA_SHORTEST_SINGLE.
  526. static void InitialScaledStartValues(uint64_t significand,
  527. int exponent,
  528. bool lower_boundary_is_closer,
  529. int estimated_power,
  530. bool need_boundary_deltas,
  531. Bignum* numerator,
  532. Bignum* denominator,
  533. Bignum* delta_minus,
  534. Bignum* delta_plus) {
  535. if (exponent >= 0) {
  536. InitialScaledStartValuesPositiveExponent(
  537. significand, exponent, estimated_power, need_boundary_deltas,
  538. numerator, denominator, delta_minus, delta_plus);
  539. } else if (estimated_power >= 0) {
  540. InitialScaledStartValuesNegativeExponentPositivePower(
  541. significand, exponent, estimated_power, need_boundary_deltas,
  542. numerator, denominator, delta_minus, delta_plus);
  543. } else {
  544. InitialScaledStartValuesNegativeExponentNegativePower(
  545. significand, exponent, estimated_power, need_boundary_deltas,
  546. numerator, denominator, delta_minus, delta_plus);
  547. }
  548. if (need_boundary_deltas && lower_boundary_is_closer) {
  549. // The lower boundary is closer at half the distance of "normal" numbers.
  550. // Increase the common denominator and adapt all but the delta_minus.
  551. denominator->ShiftLeft(1); // *2
  552. numerator->ShiftLeft(1); // *2
  553. delta_plus->ShiftLeft(1); // *2
  554. }
  555. }
  556. // This routine multiplies numerator/denominator so that its values lies in the
  557. // range 1-10. That is after a call to this function we have:
  558. // 1 <= (numerator + delta_plus) /denominator < 10.
  559. // Let numerator the input before modification and numerator' the argument
  560. // after modification, then the output-parameter decimal_point is such that
  561. // numerator / denominator * 10^estimated_power ==
  562. // numerator' / denominator' * 10^(decimal_point - 1)
  563. // In some cases estimated_power was too low, and this is already the case. We
  564. // then simply adjust the power so that 10^(k-1) <= v < 10^k (with k ==
  565. // estimated_power) but do not touch the numerator or denominator.
  566. // Otherwise the routine multiplies the numerator and the deltas by 10.
  567. static void FixupMultiply10(int estimated_power, bool is_even,
  568. int* decimal_point,
  569. Bignum* numerator, Bignum* denominator,
  570. Bignum* delta_minus, Bignum* delta_plus) {
  571. bool in_range;
  572. if (is_even) {
  573. // For IEEE doubles half-way cases (in decimal system numbers ending with 5)
  574. // are rounded to the closest floating-point number with even significand.
  575. in_range = Bignum::PlusCompare(*numerator, *delta_plus, *denominator) >= 0;
  576. } else {
  577. in_range = Bignum::PlusCompare(*numerator, *delta_plus, *denominator) > 0;
  578. }
  579. if (in_range) {
  580. // Since numerator + delta_plus >= denominator we already have
  581. // 1 <= numerator/denominator < 10. Simply update the estimated_power.
  582. *decimal_point = estimated_power + 1;
  583. } else {
  584. *decimal_point = estimated_power;
  585. numerator->Times10();
  586. if (Bignum::Equal(*delta_minus, *delta_plus)) {
  587. delta_minus->Times10();
  588. delta_plus->AssignBignum(*delta_minus);
  589. } else {
  590. delta_minus->Times10();
  591. delta_plus->Times10();
  592. }
  593. }
  594. }
  595. } // namespace double_conversion