00001 // Copyright 2012 the V8 project authors. All rights reserved. 00002 // Redistribution and use in source and binary forms, with or without 00003 // modification, are permitted provided that the following conditions are 00004 // met: 00005 // 00006 // * Redistributions of source code must retain the above copyright 00007 // notice, this list of conditions and the following disclaimer. 00008 // * Redistributions in binary form must reproduce the above 00009 // copyright notice, this list of conditions and the following 00010 // disclaimer in the documentation and/or other materials provided 00011 // with the distribution. 00012 // * Neither the name of Google Inc. nor the names of its 00013 // contributors may be used to endorse or promote products derived 00014 // from this software without specific prior written permission. 00015 // 00016 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 00017 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 00018 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 00019 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 00020 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 00021 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 00022 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 00023 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 00024 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 00025 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 00026 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 00027 00028 #include "fast-dtoa.h" 00029 00030 #include "cached-powers.h" 00031 #include "diy-fp.h" 00032 #include "ieee.h" 00033 00034 namespace double_conversion { 00035 00036 // The minimal and maximal target exponent define the range of w's binary 00037 // exponent, where 'w' is the result of multiplying the input by a cached power 00038 // of ten. 00039 // 00040 // A different range might be chosen on a different platform, to optimize digit 00041 // generation, but a smaller range requires more powers of ten to be cached. 00042 static const int kMinimalTargetExponent = -60; 00043 static const int kMaximalTargetExponent = -32; 00044 00045 00046 // Adjusts the last digit of the generated number, and screens out generated 00047 // solutions that may be inaccurate. A solution may be inaccurate if it is 00048 // outside the safe interval, or if we cannot prove that it is closer to the 00049 // input than a neighboring representation of the same length. 00050 // 00051 // Input: * buffer containing the digits of too_high / 10^kappa 00052 // * the buffer's length 00053 // * distance_too_high_w == (too_high - w).f() * unit 00054 // * unsafe_interval == (too_high - too_low).f() * unit 00055 // * rest = (too_high - buffer * 10^kappa).f() * unit 00056 // * ten_kappa = 10^kappa * unit 00057 // * unit = the common multiplier 00058 // Output: returns true if the buffer is guaranteed to contain the closest 00059 // representable number to the input. 00060 // Modifies the generated digits in the buffer to approach (round towards) w. 00061 static bool RoundWeed(Vector<char> buffer, 00062 int length, 00063 uint64_t distance_too_high_w, 00064 uint64_t unsafe_interval, 00065 uint64_t rest, 00066 uint64_t ten_kappa, 00067 uint64_t unit) { 00068 uint64_t small_distance = distance_too_high_w - unit; 00069 uint64_t big_distance = distance_too_high_w + unit; 00070 // Let w_low = too_high - big_distance, and 00071 // w_high = too_high - small_distance. 00072 // Note: w_low < w < w_high 00073 // 00074 // The real w (* unit) must lie somewhere inside the interval 00075 // ]w_low; w_high[ (often written as "(w_low; w_high)") 00076 00077 // Basically the buffer currently contains a number in the unsafe interval 00078 // ]too_low; too_high[ with too_low < w < too_high 00079 // 00080 // too_high - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 00081 // ^v 1 unit ^ ^ ^ ^ 00082 // boundary_high --------------------- . . . . 00083 // ^v 1 unit . . . . 00084 // - - - - - - - - - - - - - - - - - - - + - - + - - - - - - . . 00085 // . . ^ . . 00086 // . big_distance . . . 00087 // . . . . rest 00088 // small_distance . . . . 00089 // v . . . . 00090 // w_high - - - - - - - - - - - - - - - - - - . . . . 00091 // ^v 1 unit . . . . 00092 // w ---------------------------------------- . . . . 00093 // ^v 1 unit v . . . 00094 // w_low - - - - - - - - - - - - - - - - - - - - - . . . 00095 // . . v 00096 // buffer --------------------------------------------------+-------+-------- 00097 // . . 00098 // safe_interval . 00099 // v . 00100 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - . 00101 // ^v 1 unit . 00102 // boundary_low ------------------------- unsafe_interval 00103 // ^v 1 unit v 00104 // too_low - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 00105 // 00106 // 00107 // Note that the value of buffer could lie anywhere inside the range too_low 00108 // to too_high. 00109 // 00110 // boundary_low, boundary_high and w are approximations of the real boundaries 00111 // and v (the input number). They are guaranteed to be precise up to one unit. 00112 // In fact the error is guaranteed to be strictly less than one unit. 00113 // 00114 // Anything that lies outside the unsafe interval is guaranteed not to round 00115 // to v when read again. 00116 // Anything that lies inside the safe interval is guaranteed to round to v 00117 // when read again. 00118 // If the number inside the buffer lies inside the unsafe interval but not 00119 // inside the safe interval then we simply do not know and bail out (returning 00120 // false). 00121 // 00122 // Similarly we have to take into account the imprecision of 'w' when finding 00123 // the closest representation of 'w'. If we have two potential 00124 // representations, and one is closer to both w_low and w_high, then we know 00125 // it is closer to the actual value v. 00126 // 00127 // By generating the digits of too_high we got the largest (closest to 00128 // too_high) buffer that is still in the unsafe interval. In the case where 00129 // w_high < buffer < too_high we try to decrement the buffer. 00130 // This way the buffer approaches (rounds towards) w. 00131 // There are 3 conditions that stop the decrementation process: 00132 // 1) the buffer is already below w_high 00133 // 2) decrementing the buffer would make it leave the unsafe interval 00134 // 3) decrementing the buffer would yield a number below w_high and farther 00135 // away than the current number. In other words: 00136 // (buffer{-1} < w_high) && w_high - buffer{-1} > buffer - w_high 00137 // Instead of using the buffer directly we use its distance to too_high. 00138 // Conceptually rest ~= too_high - buffer 00139 // We need to do the following tests in this order to avoid over- and 00140 // underflows. 00141 ASSERT(rest <= unsafe_interval); 00142 while (rest < small_distance && // Negated condition 1 00143 unsafe_interval - rest >= ten_kappa && // Negated condition 2 00144 (rest + ten_kappa < small_distance || // buffer{-1} > w_high 00145 small_distance - rest >= rest + ten_kappa - small_distance)) { 00146 buffer[length - 1]--; 00147 rest += ten_kappa; 00148 } 00149 00150 // We have approached w+ as much as possible. We now test if approaching w- 00151 // would require changing the buffer. If yes, then we have two possible 00152 // representations close to w, but we cannot decide which one is closer. 00153 if (rest < big_distance && 00154 unsafe_interval - rest >= ten_kappa && 00155 (rest + ten_kappa < big_distance || 00156 big_distance - rest > rest + ten_kappa - big_distance)) { 00157 return false; 00158 } 00159 00160 // Weeding test. 00161 // The safe interval is [too_low + 2 ulp; too_high - 2 ulp] 00162 // Since too_low = too_high - unsafe_interval this is equivalent to 00163 // [too_high - unsafe_interval + 4 ulp; too_high - 2 ulp] 00164 // Conceptually we have: rest ~= too_high - buffer 00165 return (2 * unit <= rest) && (rest <= unsafe_interval - 4 * unit); 00166 } 00167 00168 00169 // Rounds the buffer upwards if the result is closer to v by possibly adding 00170 // 1 to the buffer. If the precision of the calculation is not sufficient to 00171 // round correctly, return false. 00172 // The rounding might shift the whole buffer in which case the kappa is 00173 // adjusted. For example "99", kappa = 3 might become "10", kappa = 4. 00174 // 00175 // If 2*rest > ten_kappa then the buffer needs to be round up. 00176 // rest can have an error of +/- 1 unit. This function accounts for the 00177 // imprecision and returns false, if the rounding direction cannot be 00178 // unambiguously determined. 00179 // 00180 // Precondition: rest < ten_kappa. 00181 static bool RoundWeedCounted(Vector<char> buffer, 00182 int length, 00183 uint64_t rest, 00184 uint64_t ten_kappa, 00185 uint64_t unit, 00186 int* kappa) { 00187 ASSERT(rest < ten_kappa); 00188 // The following tests are done in a specific order to avoid overflows. They 00189 // will work correctly with any uint64 values of rest < ten_kappa and unit. 00190 // 00191 // If the unit is too big, then we don't know which way to round. For example 00192 // a unit of 50 means that the real number lies within rest +/- 50. If 00193 // 10^kappa == 40 then there is no way to tell which way to round. 00194 if (unit >= ten_kappa) return false; 00195 // Even if unit is just half the size of 10^kappa we are already completely 00196 // lost. (And after the previous test we know that the expression will not 00197 // over/underflow.) 00198 if (ten_kappa - unit <= unit) return false; 00199 // If 2 * (rest + unit) <= 10^kappa we can safely round down. 00200 if ((ten_kappa - rest > rest) && (ten_kappa - 2 * rest >= 2 * unit)) { 00201 return true; 00202 } 00203 // If 2 * (rest - unit) >= 10^kappa, then we can safely round up. 00204 if ((rest > unit) && (ten_kappa - (rest - unit) <= (rest - unit))) { 00205 // Increment the last digit recursively until we find a non '9' digit. 00206 buffer[length - 1]++; 00207 for (int i = length - 1; i > 0; --i) { 00208 if (buffer[i] != '0' + 10) break; 00209 buffer[i] = '0'; 00210 buffer[i - 1]++; 00211 } 00212 // If the first digit is now '0'+ 10 we had a buffer with all '9's. With the 00213 // exception of the first digit all digits are now '0'. Simply switch the 00214 // first digit to '1' and adjust the kappa. Example: "99" becomes "10" and 00215 // the power (the kappa) is increased. 00216 if (buffer[0] == '0' + 10) { 00217 buffer[0] = '1'; 00218 (*kappa) += 1; 00219 } 00220 return true; 00221 } 00222 return false; 00223 } 00224 00225 // Returns the biggest power of ten that is less than or equal to the given 00226 // number. We furthermore receive the maximum number of bits 'number' has. 00227 // 00228 // Returns power == 10^(exponent_plus_one-1) such that 00229 // power <= number < power * 10. 00230 // If number_bits == 0 then 0^(0-1) is returned. 00231 // The number of bits must be <= 32. 00232 // Precondition: number < (1 << (number_bits + 1)). 00233 00234 // Inspired by the method for finding an integer log base 10 from here: 00235 // http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10 00236 static unsigned int const kSmallPowersOfTen[] = 00237 {0, 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 00238 1000000000}; 00239 00240 static void BiggestPowerTen(uint32_t number, 00241 int number_bits, 00242 uint32_t* power, 00243 int* exponent_plus_one) { 00244 ASSERT(number < (1u << (number_bits + 1))); 00245 // 1233/4096 is approximately 1/lg(10). 00246 int exponent_plus_one_guess = ((number_bits + 1) * 1233 >> 12); 00247 // We increment to skip over the first entry in the kPowersOf10 table. 00248 // Note: kPowersOf10[i] == 10^(i-1). 00249 exponent_plus_one_guess++; 00250 // We don't have any guarantees that 2^number_bits <= number. 00251 // TODO(floitsch): can we change the 'while' into an 'if'? We definitely see 00252 // number < (2^number_bits - 1), but I haven't encountered 00253 // number < (2^number_bits - 2) yet. 00254 while (number < kSmallPowersOfTen[exponent_plus_one_guess]) { 00255 exponent_plus_one_guess--; 00256 } 00257 *power = kSmallPowersOfTen[exponent_plus_one_guess]; 00258 *exponent_plus_one = exponent_plus_one_guess; 00259 } 00260 00261 // Generates the digits of input number w. 00262 // w is a floating-point number (DiyFp), consisting of a significand and an 00263 // exponent. Its exponent is bounded by kMinimalTargetExponent and 00264 // kMaximalTargetExponent. 00265 // Hence -60 <= w.e() <= -32. 00266 // 00267 // Returns false if it fails, in which case the generated digits in the buffer 00268 // should not be used. 00269 // Preconditions: 00270 // * low, w and high are correct up to 1 ulp (unit in the last place). That 00271 // is, their error must be less than a unit of their last digits. 00272 // * low.e() == w.e() == high.e() 00273 // * low < w < high, and taking into account their error: low~ <= high~ 00274 // * kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent 00275 // Postconditions: returns false if procedure fails. 00276 // otherwise: 00277 // * buffer is not null-terminated, but len contains the number of digits. 00278 // * buffer contains the shortest possible decimal digit-sequence 00279 // such that LOW < buffer * 10^kappa < HIGH, where LOW and HIGH are the 00280 // correct values of low and high (without their error). 00281 // * if more than one decimal representation gives the minimal number of 00282 // decimal digits then the one closest to W (where W is the correct value 00283 // of w) is chosen. 00284 // Remark: this procedure takes into account the imprecision of its input 00285 // numbers. If the precision is not enough to guarantee all the postconditions 00286 // then false is returned. This usually happens rarely (~0.5%). 00287 // 00288 // Say, for the sake of example, that 00289 // w.e() == -48, and w.f() == 0x1234567890abcdef 00290 // w's value can be computed by w.f() * 2^w.e() 00291 // We can obtain w's integral digits by simply shifting w.f() by -w.e(). 00292 // -> w's integral part is 0x1234 00293 // w's fractional part is therefore 0x567890abcdef. 00294 // Printing w's integral part is easy (simply print 0x1234 in decimal). 00295 // In order to print its fraction we repeatedly multiply the fraction by 10 and 00296 // get each digit. Example the first digit after the point would be computed by 00297 // (0x567890abcdef * 10) >> 48. -> 3 00298 // The whole thing becomes slightly more complicated because we want to stop 00299 // once we have enough digits. That is, once the digits inside the buffer 00300 // represent 'w' we can stop. Everything inside the interval low - high 00301 // represents w. However we have to pay attention to low, high and w's 00302 // imprecision. 00303 static bool DigitGen(DiyFp low, 00304 DiyFp w, 00305 DiyFp high, 00306 Vector<char> buffer, 00307 int* length, 00308 int* kappa) { 00309 ASSERT(low.e() == w.e() && w.e() == high.e()); 00310 ASSERT(low.f() + 1 <= high.f() - 1); 00311 ASSERT(kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent); 00312 // low, w and high are imprecise, but by less than one ulp (unit in the last 00313 // place). 00314 // If we remove (resp. add) 1 ulp from low (resp. high) we are certain that 00315 // the new numbers are outside of the interval we want the final 00316 // representation to lie in. 00317 // Inversely adding (resp. removing) 1 ulp from low (resp. high) would yield 00318 // numbers that are certain to lie in the interval. We will use this fact 00319 // later on. 00320 // We will now start by generating the digits within the uncertain 00321 // interval. Later we will weed out representations that lie outside the safe 00322 // interval and thus _might_ lie outside the correct interval. 00323 uint64_t unit = 1; 00324 DiyFp too_low = DiyFp(low.f() - unit, low.e()); 00325 DiyFp too_high = DiyFp(high.f() + unit, high.e()); 00326 // too_low and too_high are guaranteed to lie outside the interval we want the 00327 // generated number in. 00328 DiyFp unsafe_interval = DiyFp::Minus(too_high, too_low); 00329 // We now cut the input number into two parts: the integral digits and the 00330 // fractionals. We will not write any decimal separator though, but adapt 00331 // kappa instead. 00332 // Reminder: we are currently computing the digits (stored inside the buffer) 00333 // such that: too_low < buffer * 10^kappa < too_high 00334 // We use too_high for the digit_generation and stop as soon as possible. 00335 // If we stop early we effectively round down. 00336 DiyFp one = DiyFp(static_cast<uint64_t>(1) << -w.e(), w.e()); 00337 // Division by one is a shift. 00338 uint32_t integrals = static_cast<uint32_t>(too_high.f() >> -one.e()); 00339 // Modulo by one is an and. 00340 uint64_t fractionals = too_high.f() & (one.f() - 1); 00341 uint32_t divisor; 00342 int divisor_exponent_plus_one; 00343 BiggestPowerTen(integrals, DiyFp::kSignificandSize - (-one.e()), 00344 &divisor, &divisor_exponent_plus_one); 00345 *kappa = divisor_exponent_plus_one; 00346 *length = 0; 00347 // Loop invariant: buffer = too_high / 10^kappa (integer division) 00348 // The invariant holds for the first iteration: kappa has been initialized 00349 // with the divisor exponent + 1. And the divisor is the biggest power of ten 00350 // that is smaller than integrals. 00351 while (*kappa > 0) { 00352 int digit = integrals / divisor; 00353 buffer[*length] = '0' + digit; 00354 (*length)++; 00355 integrals %= divisor; 00356 (*kappa)--; 00357 // Note that kappa now equals the exponent of the divisor and that the 00358 // invariant thus holds again. 00359 uint64_t rest = 00360 (static_cast<uint64_t>(integrals) << -one.e()) + fractionals; 00361 // Invariant: too_high = buffer * 10^kappa + DiyFp(rest, one.e()) 00362 // Reminder: unsafe_interval.e() == one.e() 00363 if (rest < unsafe_interval.f()) { 00364 // Rounding down (by not emitting the remaining digits) yields a number 00365 // that lies within the unsafe interval. 00366 return RoundWeed(buffer, *length, DiyFp::Minus(too_high, w).f(), 00367 unsafe_interval.f(), rest, 00368 static_cast<uint64_t>(divisor) << -one.e(), unit); 00369 } 00370 divisor /= 10; 00371 } 00372 00373 // The integrals have been generated. We are at the point of the decimal 00374 // separator. In the following loop we simply multiply the remaining digits by 00375 // 10 and divide by one. We just need to pay attention to multiply associated 00376 // data (like the interval or 'unit'), too. 00377 // Note that the multiplication by 10 does not overflow, because w.e >= -60 00378 // and thus one.e >= -60. 00379 ASSERT(one.e() >= -60); 00380 ASSERT(fractionals < one.f()); 00381 ASSERT(UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.f()); 00382 while (true) { 00383 fractionals *= 10; 00384 unit *= 10; 00385 unsafe_interval.set_f(unsafe_interval.f() * 10); 00386 // Integer division by one. 00387 int digit = static_cast<int>(fractionals >> -one.e()); 00388 buffer[*length] = '0' + digit; 00389 (*length)++; 00390 fractionals &= one.f() - 1; // Modulo by one. 00391 (*kappa)--; 00392 if (fractionals < unsafe_interval.f()) { 00393 return RoundWeed(buffer, *length, DiyFp::Minus(too_high, w).f() * unit, 00394 unsafe_interval.f(), fractionals, one.f(), unit); 00395 } 00396 } 00397 } 00398 00399 00400 00401 // Generates (at most) requested_digits digits of input number w. 00402 // w is a floating-point number (DiyFp), consisting of a significand and an 00403 // exponent. Its exponent is bounded by kMinimalTargetExponent and 00404 // kMaximalTargetExponent. 00405 // Hence -60 <= w.e() <= -32. 00406 // 00407 // Returns false if it fails, in which case the generated digits in the buffer 00408 // should not be used. 00409 // Preconditions: 00410 // * w is correct up to 1 ulp (unit in the last place). That 00411 // is, its error must be strictly less than a unit of its last digit. 00412 // * kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent 00413 // 00414 // Postconditions: returns false if procedure fails. 00415 // otherwise: 00416 // * buffer is not null-terminated, but length contains the number of 00417 // digits. 00418 // * the representation in buffer is the most precise representation of 00419 // requested_digits digits. 00420 // * buffer contains at most requested_digits digits of w. If there are less 00421 // than requested_digits digits then some trailing '0's have been removed. 00422 // * kappa is such that 00423 // w = buffer * 10^kappa + eps with |eps| < 10^kappa / 2. 00424 // 00425 // Remark: This procedure takes into account the imprecision of its input 00426 // numbers. If the precision is not enough to guarantee all the postconditions 00427 // then false is returned. This usually happens rarely, but the failure-rate 00428 // increases with higher requested_digits. 00429 static bool DigitGenCounted(DiyFp w, 00430 int requested_digits, 00431 Vector<char> buffer, 00432 int* length, 00433 int* kappa) { 00434 ASSERT(kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent); 00435 ASSERT(kMinimalTargetExponent >= -60); 00436 ASSERT(kMaximalTargetExponent <= -32); 00437 // w is assumed to have an error less than 1 unit. Whenever w is scaled we 00438 // also scale its error. 00439 uint64_t w_error = 1; 00440 // We cut the input number into two parts: the integral digits and the 00441 // fractional digits. We don't emit any decimal separator, but adapt kappa 00442 // instead. Example: instead of writing "1.2" we put "12" into the buffer and 00443 // increase kappa by 1. 00444 DiyFp one = DiyFp(static_cast<uint64_t>(1) << -w.e(), w.e()); 00445 // Division by one is a shift. 00446 uint32_t integrals = static_cast<uint32_t>(w.f() >> -one.e()); 00447 // Modulo by one is an and. 00448 uint64_t fractionals = w.f() & (one.f() - 1); 00449 uint32_t divisor; 00450 int divisor_exponent_plus_one; 00451 BiggestPowerTen(integrals, DiyFp::kSignificandSize - (-one.e()), 00452 &divisor, &divisor_exponent_plus_one); 00453 *kappa = divisor_exponent_plus_one; 00454 *length = 0; 00455 00456 // Loop invariant: buffer = w / 10^kappa (integer division) 00457 // The invariant holds for the first iteration: kappa has been initialized 00458 // with the divisor exponent + 1. And the divisor is the biggest power of ten 00459 // that is smaller than 'integrals'. 00460 while (*kappa > 0) { 00461 int digit = integrals / divisor; 00462 buffer[*length] = '0' + digit; 00463 (*length)++; 00464 requested_digits--; 00465 integrals %= divisor; 00466 (*kappa)--; 00467 // Note that kappa now equals the exponent of the divisor and that the 00468 // invariant thus holds again. 00469 if (requested_digits == 0) break; 00470 divisor /= 10; 00471 } 00472 00473 if (requested_digits == 0) { 00474 uint64_t rest = 00475 (static_cast<uint64_t>(integrals) << -one.e()) + fractionals; 00476 return RoundWeedCounted(buffer, *length, rest, 00477 static_cast<uint64_t>(divisor) << -one.e(), w_error, 00478 kappa); 00479 } 00480 00481 // The integrals have been generated. We are at the point of the decimal 00482 // separator. In the following loop we simply multiply the remaining digits by 00483 // 10 and divide by one. We just need to pay attention to multiply associated 00484 // data (the 'unit'), too. 00485 // Note that the multiplication by 10 does not overflow, because w.e >= -60 00486 // and thus one.e >= -60. 00487 ASSERT(one.e() >= -60); 00488 ASSERT(fractionals < one.f()); 00489 ASSERT(UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.f()); 00490 while (requested_digits > 0 && fractionals > w_error) { 00491 fractionals *= 10; 00492 w_error *= 10; 00493 // Integer division by one. 00494 int digit = static_cast<int>(fractionals >> -one.e()); 00495 buffer[*length] = '0' + digit; 00496 (*length)++; 00497 requested_digits--; 00498 fractionals &= one.f() - 1; // Modulo by one. 00499 (*kappa)--; 00500 } 00501 if (requested_digits != 0) return false; 00502 return RoundWeedCounted(buffer, *length, fractionals, one.f(), w_error, 00503 kappa); 00504 } 00505 00506 00507 // Provides a decimal representation of v. 00508 // Returns true if it succeeds, otherwise the result cannot be trusted. 00509 // There will be *length digits inside the buffer (not null-terminated). 00510 // If the function returns true then 00511 // v == (double) (buffer * 10^decimal_exponent). 00512 // The digits in the buffer are the shortest representation possible: no 00513 // 0.09999999999999999 instead of 0.1. The shorter representation will even be 00514 // chosen even if the longer one would be closer to v. 00515 // The last digit will be closest to the actual v. That is, even if several 00516 // digits might correctly yield 'v' when read again, the closest will be 00517 // computed. 00518 static bool Grisu3(double v, 00519 FastDtoaMode mode, 00520 Vector<char> buffer, 00521 int* length, 00522 int* decimal_exponent) { 00523 DiyFp w = Double(v).AsNormalizedDiyFp(); 00524 // boundary_minus and boundary_plus are the boundaries between v and its 00525 // closest floating-point neighbors. Any number strictly between 00526 // boundary_minus and boundary_plus will round to v when convert to a double. 00527 // Grisu3 will never output representations that lie exactly on a boundary. 00528 DiyFp boundary_minus, boundary_plus; 00529 if (mode == FAST_DTOA_SHORTEST) { 00530 Double(v).NormalizedBoundaries(&boundary_minus, &boundary_plus); 00531 } else { 00532 ASSERT(mode == FAST_DTOA_SHORTEST_SINGLE); 00533 float single_v = static_cast<float>(v); 00534 Single(single_v).NormalizedBoundaries(&boundary_minus, &boundary_plus); 00535 } 00536 ASSERT(boundary_plus.e() == w.e()); 00537 DiyFp ten_mk; // Cached power of ten: 10^-k 00538 int mk; // -k 00539 int ten_mk_minimal_binary_exponent = 00540 kMinimalTargetExponent - (w.e() + DiyFp::kSignificandSize); 00541 int ten_mk_maximal_binary_exponent = 00542 kMaximalTargetExponent - (w.e() + DiyFp::kSignificandSize); 00543 PowersOfTenCache::GetCachedPowerForBinaryExponentRange( 00544 ten_mk_minimal_binary_exponent, 00545 ten_mk_maximal_binary_exponent, 00546 &ten_mk, &mk); 00547 ASSERT((kMinimalTargetExponent <= w.e() + ten_mk.e() + 00548 DiyFp::kSignificandSize) && 00549 (kMaximalTargetExponent >= w.e() + ten_mk.e() + 00550 DiyFp::kSignificandSize)); 00551 // Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a 00552 // 64 bit significand and ten_mk is thus only precise up to 64 bits. 00553 00554 // The DiyFp::Times procedure rounds its result, and ten_mk is approximated 00555 // too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now 00556 // off by a small amount. 00557 // In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w. 00558 // In other words: let f = scaled_w.f() and e = scaled_w.e(), then 00559 // (f-1) * 2^e < w*10^k < (f+1) * 2^e 00560 DiyFp scaled_w = DiyFp::Times(w, ten_mk); 00561 ASSERT(scaled_w.e() == 00562 boundary_plus.e() + ten_mk.e() + DiyFp::kSignificandSize); 00563 // In theory it would be possible to avoid some recomputations by computing 00564 // the difference between w and boundary_minus/plus (a power of 2) and to 00565 // compute scaled_boundary_minus/plus by subtracting/adding from 00566 // scaled_w. However the code becomes much less readable and the speed 00567 // enhancements are not terriffic. 00568 DiyFp scaled_boundary_minus = DiyFp::Times(boundary_minus, ten_mk); 00569 DiyFp scaled_boundary_plus = DiyFp::Times(boundary_plus, ten_mk); 00570 00571 // DigitGen will generate the digits of scaled_w. Therefore we have 00572 // v == (double) (scaled_w * 10^-mk). 00573 // Set decimal_exponent == -mk and pass it to DigitGen. If scaled_w is not an 00574 // integer than it will be updated. For instance if scaled_w == 1.23 then 00575 // the buffer will be filled with "123" und the decimal_exponent will be 00576 // decreased by 2. 00577 int kappa; 00578 bool result = DigitGen(scaled_boundary_minus, scaled_w, scaled_boundary_plus, 00579 buffer, length, &kappa); 00580 *decimal_exponent = -mk + kappa; 00581 return result; 00582 } 00583 00584 00585 // The "counted" version of grisu3 (see above) only generates requested_digits 00586 // number of digits. This version does not generate the shortest representation, 00587 // and with enough requested digits 0.1 will at some point print as 0.9999999... 00588 // Grisu3 is too imprecise for real halfway cases (1.5 will not work) and 00589 // therefore the rounding strategy for halfway cases is irrelevant. 00590 static bool Grisu3Counted(double v, 00591 int requested_digits, 00592 Vector<char> buffer, 00593 int* length, 00594 int* decimal_exponent) { 00595 DiyFp w = Double(v).AsNormalizedDiyFp(); 00596 DiyFp ten_mk; // Cached power of ten: 10^-k 00597 int mk; // -k 00598 int ten_mk_minimal_binary_exponent = 00599 kMinimalTargetExponent - (w.e() + DiyFp::kSignificandSize); 00600 int ten_mk_maximal_binary_exponent = 00601 kMaximalTargetExponent - (w.e() + DiyFp::kSignificandSize); 00602 PowersOfTenCache::GetCachedPowerForBinaryExponentRange( 00603 ten_mk_minimal_binary_exponent, 00604 ten_mk_maximal_binary_exponent, 00605 &ten_mk, &mk); 00606 ASSERT((kMinimalTargetExponent <= w.e() + ten_mk.e() + 00607 DiyFp::kSignificandSize) && 00608 (kMaximalTargetExponent >= w.e() + ten_mk.e() + 00609 DiyFp::kSignificandSize)); 00610 // Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a 00611 // 64 bit significand and ten_mk is thus only precise up to 64 bits. 00612 00613 // The DiyFp::Times procedure rounds its result, and ten_mk is approximated 00614 // too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now 00615 // off by a small amount. 00616 // In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w. 00617 // In other words: let f = scaled_w.f() and e = scaled_w.e(), then 00618 // (f-1) * 2^e < w*10^k < (f+1) * 2^e 00619 DiyFp scaled_w = DiyFp::Times(w, ten_mk); 00620 00621 // We now have (double) (scaled_w * 10^-mk). 00622 // DigitGen will generate the first requested_digits digits of scaled_w and 00623 // return together with a kappa such that scaled_w ~= buffer * 10^kappa. (It 00624 // will not always be exactly the same since DigitGenCounted only produces a 00625 // limited number of digits.) 00626 int kappa; 00627 bool result = DigitGenCounted(scaled_w, requested_digits, 00628 buffer, length, &kappa); 00629 *decimal_exponent = -mk + kappa; 00630 return result; 00631 } 00632 00633 00634 bool FastDtoa(double v, 00635 FastDtoaMode mode, 00636 int requested_digits, 00637 Vector<char> buffer, 00638 int* length, 00639 int* decimal_point) { 00640 ASSERT(v > 0); 00641 ASSERT(!Double(v).IsSpecial()); 00642 00643 bool result = false; 00644 int decimal_exponent = 0; 00645 switch (mode) { 00646 case FAST_DTOA_SHORTEST: 00647 case FAST_DTOA_SHORTEST_SINGLE: 00648 result = Grisu3(v, mode, buffer, length, &decimal_exponent); 00649 break; 00650 case FAST_DTOA_PRECISION: 00651 result = Grisu3Counted(v, requested_digits, 00652 buffer, length, &decimal_exponent); 00653 break; 00654 default: 00655 UNREACHABLE(); 00656 } 00657 if (result) { 00658 *decimal_point = *length + decimal_exponent; 00659 buffer[*length] = '\0'; 00660 } 00661 return result; 00662 } 00663 00664 } // namespace double_conversion