Home | History | Annotate | Download | only in dtoa
      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 
     28 #include "config.h"
     29 
     30 #include "fast-dtoa.h"
     31 
     32 #include "cached-powers.h"
     33 #include "diy-fp.h"
     34 #include "double.h"
     35 
     36 namespace WTF {
     37 
     38 namespace double_conversion {
     39 
     40     // The minimal and maximal target exponent define the range of w's binary
     41     // exponent, where 'w' is the result of multiplying the input by a cached power
     42     // of ten.
     43     //
     44     // A different range might be chosen on a different platform, to optimize digit
     45     // generation, but a smaller range requires more powers of ten to be cached.
     46     static const int kMinimalTargetExponent = -60;
     47     static const int kMaximalTargetExponent = -32;
     48 
     49 
     50     // Adjusts the last digit of the generated number, and screens out generated
     51     // solutions that may be inaccurate. A solution may be inaccurate if it is
     52     // outside the safe interval, or if we cannot prove that it is closer to the
     53     // input than a neighboring representation of the same length.
     54     //
     55     // Input: * buffer containing the digits of too_high / 10^kappa
     56     //        * the buffer's length
     57     //        * distance_too_high_w == (too_high - w).f() * unit
     58     //        * unsafe_interval == (too_high - too_low).f() * unit
     59     //        * rest = (too_high - buffer * 10^kappa).f() * unit
     60     //        * ten_kappa = 10^kappa * unit
     61     //        * unit = the common multiplier
     62     // Output: returns true if the buffer is guaranteed to contain the closest
     63     //    representable number to the input.
     64     //  Modifies the generated digits in the buffer to approach (round towards) w.
     65     static bool RoundWeed(Vector<char> buffer,
     66                           int length,
     67                           uint64_t distance_too_high_w,
     68                           uint64_t unsafe_interval,
     69                           uint64_t rest,
     70                           uint64_t ten_kappa,
     71                           uint64_t unit) {
     72         uint64_t small_distance = distance_too_high_w - unit;
     73         uint64_t big_distance = distance_too_high_w + unit;
     74         // Let w_low  = too_high - big_distance, and
     75         //     w_high = too_high - small_distance.
     76         // Note: w_low < w < w_high
     77         //
     78         // The real w (* unit) must lie somewhere inside the interval
     79         // ]w_low; w_high[ (often written as "(w_low; w_high)")
     80 
     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         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 
    154         // We have approached w+ as much as possible. We now test if approaching w-
    155         // would require changing the buffer. If yes, then we have two possible
    156         // representations close to w, but we cannot decide which one is closer.
    157         if (rest < big_distance &&
    158             unsafe_interval - rest >= ten_kappa &&
    159             (rest + ten_kappa < big_distance ||
    160              big_distance - rest > rest + ten_kappa - big_distance)) {
    161                 return false;
    162             }
    163 
    164         // Weeding test.
    165         //   The safe interval is [too_low + 2 ulp; too_high - 2 ulp]
    166         //   Since too_low = too_high - unsafe_interval this is equivalent to
    167         //      [too_high - unsafe_interval + 4 ulp; too_high - 2 ulp]
    168         //   Conceptually we have: rest ~= too_high - buffer
    169         return (2 * unit <= rest) && (rest <= unsafe_interval - 4 * unit);
    170     }
    171 
    172 
    173     // Rounds the buffer upwards if the result is closer to v by possibly adding
    174     // 1 to the buffer. If the precision of the calculation is not sufficient to
    175     // round correctly, return false.
    176     // The rounding might shift the whole buffer in which case the kappa is
    177     // adjusted. For example "99", kappa = 3 might become "10", kappa = 4.
    178     //
    179     // If 2*rest > ten_kappa then the buffer needs to be round up.
    180     // rest can have an error of +/- 1 unit. This function accounts for the
    181     // imprecision and returns false, if the rounding direction cannot be
    182     // unambiguously determined.
    183     //
    184     // Precondition: rest < ten_kappa.
    185     static bool RoundWeedCounted(Vector<char> buffer,
    186                                  int length,
    187                                  uint64_t rest,
    188                                  uint64_t ten_kappa,
    189                                  uint64_t unit,
    190                                  int* kappa) {
    191         ASSERT(rest < ten_kappa);
    192         // The following tests are done in a specific order to avoid overflows. They
    193         // will work correctly with any uint64 values of rest < ten_kappa and unit.
    194         //
    195         // If the unit is too big, then we don't know which way to round. For example
    196         // a unit of 50 means that the real number lies within rest +/- 50. If
    197         // 10^kappa == 40 then there is no way to tell which way to round.
    198         if (unit >= ten_kappa) return false;
    199         // Even if unit is just half the size of 10^kappa we are already completely
    200         // lost. (And after the previous test we know that the expression will not
    201         // over/underflow.)
    202         if (ten_kappa - unit <= unit) return false;
    203         // If 2 * (rest + unit) <= 10^kappa we can safely round down.
    204         if ((ten_kappa - rest > rest) && (ten_kappa - 2 * rest >= 2 * unit)) {
    205             return true;
    206         }
    207         // If 2 * (rest - unit) >= 10^kappa, then we can safely round up.
    208         if ((rest > unit) && (ten_kappa - (rest - unit) <= (rest - unit))) {
    209             // Increment the last digit recursively until we find a non '9' digit.
    210             buffer[length - 1]++;
    211             for (int i = length - 1; i > 0; --i) {
    212                 if (buffer[i] != '0' + 10) break;
    213                 buffer[i] = '0';
    214                 buffer[i - 1]++;
    215             }
    216             // If the first digit is now '0'+ 10 we had a buffer with all '9's. With the
    217             // exception of the first digit all digits are now '0'. Simply switch the
    218             // first digit to '1' and adjust the kappa. Example: "99" becomes "10" and
    219             // the power (the kappa) is increased.
    220             if (buffer[0] == '0' + 10) {
    221                 buffer[0] = '1';
    222                 (*kappa) += 1;
    223             }
    224             return true;
    225         }
    226         return false;
    227     }
    228 
    229 
    230     static const uint32_t kTen4 = 10000;
    231     static const uint32_t kTen5 = 100000;
    232     static const uint32_t kTen6 = 1000000;
    233     static const uint32_t kTen7 = 10000000;
    234     static const uint32_t kTen8 = 100000000;
    235     static const uint32_t kTen9 = 1000000000;
    236 
    237     // Returns the biggest power of ten that is less than or equal to the given
    238     // number. We furthermore receive the maximum number of bits 'number' has.
    239     // If number_bits == 0 then 0^-1 is returned
    240     // The number of bits must be <= 32.
    241     // Precondition: number < (1 << (number_bits + 1)).
    242     static void BiggestPowerTen(uint32_t number,
    243                                 int number_bits,
    244                                 uint32_t* power,
    245                                 int* exponent) {
    246         ASSERT(number < (uint32_t)(1 << (number_bits + 1)));
    247 
    248         switch (number_bits) {
    249             case 32:
    250             case 31:
    251             case 30:
    252                 if (kTen9 <= number) {
    253                     *power = kTen9;
    254                     *exponent = 9;
    255                     break;
    256                 }  // else fallthrough
    257             case 29:
    258             case 28:
    259             case 27:
    260                 if (kTen8 <= number) {
    261                     *power = kTen8;
    262                     *exponent = 8;
    263                     break;
    264                 }  // else fallthrough
    265             case 26:
    266             case 25:
    267             case 24:
    268                 if (kTen7 <= number) {
    269                     *power = kTen7;
    270                     *exponent = 7;
    271                     break;
    272                 }  // else fallthrough
    273             case 23:
    274             case 22:
    275             case 21:
    276             case 20:
    277                 if (kTen6 <= number) {
    278                     *power = kTen6;
    279                     *exponent = 6;
    280                     break;
    281                 }  // else fallthrough
    282             case 19:
    283             case 18:
    284             case 17:
    285                 if (kTen5 <= number) {
    286                     *power = kTen5;
    287                     *exponent = 5;
    288                     break;
    289                 }  // else fallthrough
    290             case 16:
    291             case 15:
    292             case 14:
    293                 if (kTen4 <= number) {
    294                     *power = kTen4;
    295                     *exponent = 4;
    296                     break;
    297                 }  // else fallthrough
    298             case 13:
    299             case 12:
    300             case 11:
    301             case 10:
    302                 if (1000 <= number) {
    303                     *power = 1000;
    304                     *exponent = 3;
    305                     break;
    306                 }  // else fallthrough
    307             case 9:
    308             case 8:
    309             case 7:
    310                 if (100 <= number) {
    311                     *power = 100;
    312                     *exponent = 2;
    313                     break;
    314                 }  // else fallthrough
    315             case 6:
    316             case 5:
    317             case 4:
    318                 if (10 <= number) {
    319                     *power = 10;
    320                     *exponent = 1;
    321                     break;
    322                 }  // else fallthrough
    323             case 3:
    324             case 2:
    325             case 1:
    326                 if (1 <= number) {
    327                     *power = 1;
    328                     *exponent = 0;
    329                     break;
    330                 }  // else fallthrough
    331             case 0:
    332                 *power = 0;
    333                 *exponent = -1;
    334                 break;
    335             default:
    336                 // Following assignments are here to silence compiler warnings.
    337                 *power = 0;
    338                 *exponent = 0;
    339                 UNREACHABLE();
    340         }
    341     }
    342 
    343 
    344     // Generates the digits of input number w.
    345     // w is a floating-point number (DiyFp), consisting of a significand and an
    346     // exponent. Its exponent is bounded by kMinimalTargetExponent and
    347     // kMaximalTargetExponent.
    348     //       Hence -60 <= w.e() <= -32.
    349     //
    350     // Returns false if it fails, in which case the generated digits in the buffer
    351     // should not be used.
    352     // Preconditions:
    353     //  * low, w and high are correct up to 1 ulp (unit in the last place). That
    354     //    is, their error must be less than a unit of their last digits.
    355     //  * low.e() == w.e() == high.e()
    356     //  * low < w < high, and taking into account their error: low~ <= high~
    357     //  * kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent
    358     // Postconditions: returns false if procedure fails.
    359     //   otherwise:
    360     //     * buffer is not null-terminated, but len contains the number of digits.
    361     //     * buffer contains the shortest possible decimal digit-sequence
    362     //       such that LOW < buffer * 10^kappa < HIGH, where LOW and HIGH are the
    363     //       correct values of low and high (without their error).
    364     //     * if more than one decimal representation gives the minimal number of
    365     //       decimal digits then the one closest to W (where W is the correct value
    366     //       of w) is chosen.
    367     // Remark: this procedure takes into account the imprecision of its input
    368     //   numbers. If the precision is not enough to guarantee all the postconditions
    369     //   then false is returned. This usually happens rarely (~0.5%).
    370     //
    371     // Say, for the sake of example, that
    372     //   w.e() == -48, and w.f() == 0x1234567890abcdef
    373     // w's value can be computed by w.f() * 2^w.e()
    374     // We can obtain w's integral digits by simply shifting w.f() by -w.e().
    375     //  -> w's integral part is 0x1234
    376     //  w's fractional part is therefore 0x567890abcdef.
    377     // Printing w's integral part is easy (simply print 0x1234 in decimal).
    378     // In order to print its fraction we repeatedly multiply the fraction by 10 and
    379     // get each digit. Example the first digit after the point would be computed by
    380     //   (0x567890abcdef * 10) >> 48. -> 3
    381     // The whole thing becomes slightly more complicated because we want to stop
    382     // once we have enough digits. That is, once the digits inside the buffer
    383     // represent 'w' we can stop. Everything inside the interval low - high
    384     // represents w. However we have to pay attention to low, high and w's
    385     // imprecision.
    386     static bool DigitGen(DiyFp low,
    387                          DiyFp w,
    388                          DiyFp high,
    389                          Vector<char> buffer,
    390                          int* length,
    391                          int* kappa) {
    392         ASSERT(low.e() == w.e() && w.e() == high.e());
    393         ASSERT(low.f() + 1 <= high.f() - 1);
    394         ASSERT(kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent);
    395         // low, w and high are imprecise, but by less than one ulp (unit in the last
    396         // place).
    397         // If we remove (resp. add) 1 ulp from low (resp. high) we are certain that
    398         // the new numbers are outside of the interval we want the final
    399         // representation to lie in.
    400         // Inversely adding (resp. removing) 1 ulp from low (resp. high) would yield
    401         // numbers that are certain to lie in the interval. We will use this fact
    402         // later on.
    403         // We will now start by generating the digits within the uncertain
    404         // interval. Later we will weed out representations that lie outside the safe
    405         // interval and thus _might_ lie outside the correct interval.
    406         uint64_t unit = 1;
    407         DiyFp too_low = DiyFp(low.f() - unit, low.e());
    408         DiyFp too_high = DiyFp(high.f() + unit, high.e());
    409         // too_low and too_high are guaranteed to lie outside the interval we want the
    410         // generated number in.
    411         DiyFp unsafe_interval = DiyFp::Minus(too_high, too_low);
    412         // We now cut the input number into two parts: the integral digits and the
    413         // fractionals. We will not write any decimal separator though, but adapt
    414         // kappa instead.
    415         // Reminder: we are currently computing the digits (stored inside the buffer)
    416         // such that:   too_low < buffer * 10^kappa < too_high
    417         // We use too_high for the digit_generation and stop as soon as possible.
    418         // If we stop early we effectively round down.
    419         DiyFp one = DiyFp(static_cast<uint64_t>(1) << -w.e(), w.e());
    420         // Division by one is a shift.
    421         uint32_t integrals = static_cast<uint32_t>(too_high.f() >> -one.e());
    422         // Modulo by one is an and.
    423         uint64_t fractionals = too_high.f() & (one.f() - 1);
    424         uint32_t divisor;
    425         int divisor_exponent;
    426         BiggestPowerTen(integrals, DiyFp::kSignificandSize - (-one.e()),
    427                         &divisor, &divisor_exponent);
    428         *kappa = divisor_exponent + 1;
    429         *length = 0;
    430         // Loop invariant: buffer = too_high / 10^kappa  (integer division)
    431         // The invariant holds for the first iteration: kappa has been initialized
    432         // with the divisor exponent + 1. And the divisor is the biggest power of ten
    433         // that is smaller than integrals.
    434         while (*kappa > 0) {
    435             int digit = integrals / divisor;
    436             buffer[*length] = '0' + digit;
    437             (*length)++;
    438             integrals %= divisor;
    439             (*kappa)--;
    440             // Note that kappa now equals the exponent of the divisor and that the
    441             // invariant thus holds again.
    442             uint64_t rest =
    443             (static_cast<uint64_t>(integrals) << -one.e()) + fractionals;
    444             // Invariant: too_high = buffer * 10^kappa + DiyFp(rest, one.e())
    445             // Reminder: unsafe_interval.e() == one.e()
    446             if (rest < unsafe_interval.f()) {
    447                 // Rounding down (by not emitting the remaining digits) yields a number
    448                 // that lies within the unsafe interval.
    449                 return RoundWeed(buffer, *length, DiyFp::Minus(too_high, w).f(),
    450                                  unsafe_interval.f(), rest,
    451                                  static_cast<uint64_t>(divisor) << -one.e(), unit);
    452             }
    453             divisor /= 10;
    454         }
    455 
    456         // The integrals have been generated. We are at the point of the decimal
    457         // separator. In the following loop we simply multiply the remaining digits by
    458         // 10 and divide by one. We just need to pay attention to multiply associated
    459         // data (like the interval or 'unit'), too.
    460         // Note that the multiplication by 10 does not overflow, because w.e >= -60
    461         // and thus one.e >= -60.
    462         ASSERT(one.e() >= -60);
    463         ASSERT(fractionals < one.f());
    464         ASSERT(UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.f());
    465         while (true) {
    466             fractionals *= 10;
    467             unit *= 10;
    468             unsafe_interval.set_f(unsafe_interval.f() * 10);
    469             // Integer division by one.
    470             int digit = static_cast<int>(fractionals >> -one.e());
    471             buffer[*length] = '0' + digit;
    472             (*length)++;
    473             fractionals &= one.f() - 1;  // Modulo by one.
    474             (*kappa)--;
    475             if (fractionals < unsafe_interval.f()) {
    476                 return RoundWeed(buffer, *length, DiyFp::Minus(too_high, w).f() * unit,
    477                                  unsafe_interval.f(), fractionals, one.f(), unit);
    478             }
    479         }
    480     }
    481 
    482 
    483 
    484     // Generates (at most) requested_digits digits of input number w.
    485     // w is a floating-point number (DiyFp), consisting of a significand and an
    486     // exponent. Its exponent is bounded by kMinimalTargetExponent and
    487     // kMaximalTargetExponent.
    488     //       Hence -60 <= w.e() <= -32.
    489     //
    490     // Returns false if it fails, in which case the generated digits in the buffer
    491     // should not be used.
    492     // Preconditions:
    493     //  * w is correct up to 1 ulp (unit in the last place). That
    494     //    is, its error must be strictly less than a unit of its last digit.
    495     //  * kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent
    496     //
    497     // Postconditions: returns false if procedure fails.
    498     //   otherwise:
    499     //     * buffer is not null-terminated, but length contains the number of
    500     //       digits.
    501     //     * the representation in buffer is the most precise representation of
    502     //       requested_digits digits.
    503     //     * buffer contains at most requested_digits digits of w. If there are less
    504     //       than requested_digits digits then some trailing '0's have been removed.
    505     //     * kappa is such that
    506     //            w = buffer * 10^kappa + eps with |eps| < 10^kappa / 2.
    507     //
    508     // Remark: This procedure takes into account the imprecision of its input
    509     //   numbers. If the precision is not enough to guarantee all the postconditions
    510     //   then false is returned. This usually happens rarely, but the failure-rate
    511     //   increases with higher requested_digits.
    512     static bool DigitGenCounted(DiyFp w,
    513                                 int requested_digits,
    514                                 Vector<char> buffer,
    515                                 int* length,
    516                                 int* kappa) {
    517         ASSERT(kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent);
    518         ASSERT(kMinimalTargetExponent >= -60);
    519         ASSERT(kMaximalTargetExponent <= -32);
    520         // w is assumed to have an error less than 1 unit. Whenever w is scaled we
    521         // also scale its error.
    522         uint64_t w_error = 1;
    523         // We cut the input number into two parts: the integral digits and the
    524         // fractional digits. We don't emit any decimal separator, but adapt kappa
    525         // instead. Example: instead of writing "1.2" we put "12" into the buffer and
    526         // increase kappa by 1.
    527         DiyFp one = DiyFp(static_cast<uint64_t>(1) << -w.e(), w.e());
    528         // Division by one is a shift.
    529         uint32_t integrals = static_cast<uint32_t>(w.f() >> -one.e());
    530         // Modulo by one is an and.
    531         uint64_t fractionals = w.f() & (one.f() - 1);
    532         uint32_t divisor;
    533         int divisor_exponent;
    534         BiggestPowerTen(integrals, DiyFp::kSignificandSize - (-one.e()),
    535                         &divisor, &divisor_exponent);
    536         *kappa = divisor_exponent + 1;
    537         *length = 0;
    538 
    539         // Loop invariant: buffer = w / 10^kappa  (integer division)
    540         // The invariant holds for the first iteration: kappa has been initialized
    541         // with the divisor exponent + 1. And the divisor is the biggest power of ten
    542         // that is smaller than 'integrals'.
    543         while (*kappa > 0) {
    544             int digit = integrals / divisor;
    545             buffer[*length] = '0' + digit;
    546             (*length)++;
    547             requested_digits--;
    548             integrals %= divisor;
    549             (*kappa)--;
    550             // Note that kappa now equals the exponent of the divisor and that the
    551             // invariant thus holds again.
    552             if (requested_digits == 0) break;
    553             divisor /= 10;
    554         }
    555 
    556         if (requested_digits == 0) {
    557             uint64_t rest =
    558             (static_cast<uint64_t>(integrals) << -one.e()) + fractionals;
    559             return RoundWeedCounted(buffer, *length, rest,
    560                                     static_cast<uint64_t>(divisor) << -one.e(), w_error,
    561                                     kappa);
    562         }
    563 
    564         // The integrals have been generated. We are at the point of the decimal
    565         // separator. In the following loop we simply multiply the remaining digits by
    566         // 10 and divide by one. We just need to pay attention to multiply associated
    567         // data (the 'unit'), too.
    568         // Note that the multiplication by 10 does not overflow, because w.e >= -60
    569         // and thus one.e >= -60.
    570         ASSERT(one.e() >= -60);
    571         ASSERT(fractionals < one.f());
    572         ASSERT(UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.f());
    573         while (requested_digits > 0 && fractionals > w_error) {
    574             fractionals *= 10;
    575             w_error *= 10;
    576             // Integer division by one.
    577             int digit = static_cast<int>(fractionals >> -one.e());
    578             buffer[*length] = '0' + digit;
    579             (*length)++;
    580             requested_digits--;
    581             fractionals &= one.f() - 1;  // Modulo by one.
    582             (*kappa)--;
    583         }
    584         if (requested_digits != 0) return false;
    585         return RoundWeedCounted(buffer, *length, fractionals, one.f(), w_error,
    586                                 kappa);
    587     }
    588 
    589 
    590     // Provides a decimal representation of v.
    591     // Returns true if it succeeds, otherwise the result cannot be trusted.
    592     // There will be *length digits inside the buffer (not null-terminated).
    593     // If the function returns true then
    594     //        v == (double) (buffer * 10^decimal_exponent).
    595     // The digits in the buffer are the shortest representation possible: no
    596     // 0.09999999999999999 instead of 0.1. The shorter representation will even be
    597     // chosen even if the longer one would be closer to v.
    598     // The last digit will be closest to the actual v. That is, even if several
    599     // digits might correctly yield 'v' when read again, the closest will be
    600     // computed.
    601     static bool Grisu3(double v,
    602                        Vector<char> buffer,
    603                        int* length,
    604                        int* decimal_exponent) {
    605         DiyFp w = Double(v).AsNormalizedDiyFp();
    606         // boundary_minus and boundary_plus are the boundaries between v and its
    607         // closest floating-point neighbors. Any number strictly between
    608         // boundary_minus and boundary_plus will round to v when convert to a double.
    609         // Grisu3 will never output representations that lie exactly on a boundary.
    610         DiyFp boundary_minus, boundary_plus;
    611         Double(v).NormalizedBoundaries(&boundary_minus, &boundary_plus);
    612         ASSERT(boundary_plus.e() == w.e());
    613         DiyFp ten_mk;  // Cached power of ten: 10^-k
    614         int mk;        // -k
    615         int ten_mk_minimal_binary_exponent =
    616         kMinimalTargetExponent - (w.e() + DiyFp::kSignificandSize);
    617         int ten_mk_maximal_binary_exponent =
    618         kMaximalTargetExponent - (w.e() + DiyFp::kSignificandSize);
    619         PowersOfTenCache::GetCachedPowerForBinaryExponentRange(
    620                                                                ten_mk_minimal_binary_exponent,
    621                                                                ten_mk_maximal_binary_exponent,
    622                                                                &ten_mk, &mk);
    623         ASSERT((kMinimalTargetExponent <= w.e() + ten_mk.e() +
    624                 DiyFp::kSignificandSize) &&
    625                (kMaximalTargetExponent >= w.e() + ten_mk.e() +
    626                 DiyFp::kSignificandSize));
    627         // Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a
    628         // 64 bit significand and ten_mk is thus only precise up to 64 bits.
    629 
    630         // The DiyFp::Times procedure rounds its result, and ten_mk is approximated
    631         // too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now
    632         // off by a small amount.
    633         // In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w.
    634         // In other words: let f = scaled_w.f() and e = scaled_w.e(), then
    635         //           (f-1) * 2^e < w*10^k < (f+1) * 2^e
    636         DiyFp scaled_w = DiyFp::Times(w, ten_mk);
    637         ASSERT(scaled_w.e() ==
    638                boundary_plus.e() + ten_mk.e() + DiyFp::kSignificandSize);
    639         // In theory it would be possible to avoid some recomputations by computing
    640         // the difference between w and boundary_minus/plus (a power of 2) and to
    641         // compute scaled_boundary_minus/plus by subtracting/adding from
    642         // scaled_w. However the code becomes much less readable and the speed
    643         // enhancements are not terriffic.
    644         DiyFp scaled_boundary_minus = DiyFp::Times(boundary_minus, ten_mk);
    645         DiyFp scaled_boundary_plus  = DiyFp::Times(boundary_plus,  ten_mk);
    646 
    647         // DigitGen will generate the digits of scaled_w. Therefore we have
    648         // v == (double) (scaled_w * 10^-mk).
    649         // Set decimal_exponent == -mk and pass it to DigitGen. If scaled_w is not an
    650         // integer than it will be updated. For instance if scaled_w == 1.23 then
    651         // the buffer will be filled with "123" und the decimal_exponent will be
    652         // decreased by 2.
    653         int kappa;
    654         bool result = DigitGen(scaled_boundary_minus, scaled_w, scaled_boundary_plus,
    655                                buffer, length, &kappa);
    656         *decimal_exponent = -mk + kappa;
    657         return result;
    658     }
    659 
    660 
    661     // The "counted" version of grisu3 (see above) only generates requested_digits
    662     // number of digits. This version does not generate the shortest representation,
    663     // and with enough requested digits 0.1 will at some point print as 0.9999999...
    664     // Grisu3 is too imprecise for real halfway cases (1.5 will not work) and
    665     // therefore the rounding strategy for halfway cases is irrelevant.
    666     static bool Grisu3Counted(double v,
    667                               int requested_digits,
    668                               Vector<char> buffer,
    669                               int* length,
    670                               int* decimal_exponent) {
    671         DiyFp w = Double(v).AsNormalizedDiyFp();
    672         DiyFp ten_mk;  // Cached power of ten: 10^-k
    673         int mk;        // -k
    674         int ten_mk_minimal_binary_exponent =
    675         kMinimalTargetExponent - (w.e() + DiyFp::kSignificandSize);
    676         int ten_mk_maximal_binary_exponent =
    677         kMaximalTargetExponent - (w.e() + DiyFp::kSignificandSize);
    678         PowersOfTenCache::GetCachedPowerForBinaryExponentRange(
    679                                                                ten_mk_minimal_binary_exponent,
    680                                                                ten_mk_maximal_binary_exponent,
    681                                                                &ten_mk, &mk);
    682         ASSERT((kMinimalTargetExponent <= w.e() + ten_mk.e() +
    683                 DiyFp::kSignificandSize) &&
    684                (kMaximalTargetExponent >= w.e() + ten_mk.e() +
    685                 DiyFp::kSignificandSize));
    686         // Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a
    687         // 64 bit significand and ten_mk is thus only precise up to 64 bits.
    688 
    689         // The DiyFp::Times procedure rounds its result, and ten_mk is approximated
    690         // too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now
    691         // off by a small amount.
    692         // In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w.
    693         // In other words: let f = scaled_w.f() and e = scaled_w.e(), then
    694         //           (f-1) * 2^e < w*10^k < (f+1) * 2^e
    695         DiyFp scaled_w = DiyFp::Times(w, ten_mk);
    696 
    697         // We now have (double) (scaled_w * 10^-mk).
    698         // DigitGen will generate the first requested_digits digits of scaled_w and
    699         // return together with a kappa such that scaled_w ~= buffer * 10^kappa. (It
    700         // will not always be exactly the same since DigitGenCounted only produces a
    701         // limited number of digits.)
    702         int kappa;
    703         bool result = DigitGenCounted(scaled_w, requested_digits,
    704                                       buffer, length, &kappa);
    705         *decimal_exponent = -mk + kappa;
    706         return result;
    707     }
    708 
    709 
    710     bool FastDtoa(double v,
    711                   FastDtoaMode mode,
    712                   int requested_digits,
    713                   Vector<char> buffer,
    714                   int* length,
    715                   int* decimal_point) {
    716         ASSERT(v > 0);
    717         ASSERT(!Double(v).IsSpecial());
    718 
    719         bool result = false;
    720         int decimal_exponent = 0;
    721         switch (mode) {
    722             case FAST_DTOA_SHORTEST:
    723                 result = Grisu3(v, buffer, length, &decimal_exponent);
    724                 break;
    725             case FAST_DTOA_PRECISION:
    726                 result = Grisu3Counted(v, requested_digits,
    727                                        buffer, length, &decimal_exponent);
    728                 break;
    729             default:
    730                 UNREACHABLE();
    731         }
    732         if (result) {
    733             *decimal_point = *length + decimal_exponent;
    734             buffer[*length] = '\0';
    735         }
    736         return result;
    737     }
    738 
    739 }  // namespace double_conversion
    740 
    741 } // namespace WTF
    742