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 36namespace WTF { 37 38namespace 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(BufferReference<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(BufferReference<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 } 257 FALLTHROUGH; 258 case 29: 259 case 28: 260 case 27: 261 if (kTen8 <= number) { 262 *power = kTen8; 263 *exponent = 8; 264 break; 265 } 266 FALLTHROUGH; 267 case 26: 268 case 25: 269 case 24: 270 if (kTen7 <= number) { 271 *power = kTen7; 272 *exponent = 7; 273 break; 274 } 275 FALLTHROUGH; 276 case 23: 277 case 22: 278 case 21: 279 case 20: 280 if (kTen6 <= number) { 281 *power = kTen6; 282 *exponent = 6; 283 break; 284 } 285 FALLTHROUGH; 286 case 19: 287 case 18: 288 case 17: 289 if (kTen5 <= number) { 290 *power = kTen5; 291 *exponent = 5; 292 break; 293 } 294 FALLTHROUGH; 295 case 16: 296 case 15: 297 case 14: 298 if (kTen4 <= number) { 299 *power = kTen4; 300 *exponent = 4; 301 break; 302 } 303 FALLTHROUGH; 304 case 13: 305 case 12: 306 case 11: 307 case 10: 308 if (1000 <= number) { 309 *power = 1000; 310 *exponent = 3; 311 break; 312 } 313 FALLTHROUGH; 314 case 9: 315 case 8: 316 case 7: 317 if (100 <= number) { 318 *power = 100; 319 *exponent = 2; 320 break; 321 } 322 FALLTHROUGH; 323 case 6: 324 case 5: 325 case 4: 326 if (10 <= number) { 327 *power = 10; 328 *exponent = 1; 329 break; 330 } 331 FALLTHROUGH; 332 case 3: 333 case 2: 334 case 1: 335 if (1 <= number) { 336 *power = 1; 337 *exponent = 0; 338 break; 339 } 340 FALLTHROUGH; 341 case 0: 342 *power = 0; 343 *exponent = -1; 344 break; 345 default: 346 // Following assignments are here to silence compiler warnings. 347 *power = 0; 348 *exponent = 0; 349 UNREACHABLE(); 350 } 351 } 352 353 354 // Generates the digits of input number w. 355 // w is a floating-point number (DiyFp), consisting of a significand and an 356 // exponent. Its exponent is bounded by kMinimalTargetExponent and 357 // kMaximalTargetExponent. 358 // Hence -60 <= w.e() <= -32. 359 // 360 // Returns false if it fails, in which case the generated digits in the buffer 361 // should not be used. 362 // Preconditions: 363 // * low, w and high are correct up to 1 ulp (unit in the last place). That 364 // is, their error must be less than a unit of their last digits. 365 // * low.e() == w.e() == high.e() 366 // * low < w < high, and taking into account their error: low~ <= high~ 367 // * kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent 368 // Postconditions: returns false if procedure fails. 369 // otherwise: 370 // * buffer is not null-terminated, but len contains the number of digits. 371 // * buffer contains the shortest possible decimal digit-sequence 372 // such that LOW < buffer * 10^kappa < HIGH, where LOW and HIGH are the 373 // correct values of low and high (without their error). 374 // * if more than one decimal representation gives the minimal number of 375 // decimal digits then the one closest to W (where W is the correct value 376 // of w) is chosen. 377 // Remark: this procedure takes into account the imprecision of its input 378 // numbers. If the precision is not enough to guarantee all the postconditions 379 // then false is returned. This usually happens rarely (~0.5%). 380 // 381 // Say, for the sake of example, that 382 // w.e() == -48, and w.f() == 0x1234567890abcdef 383 // w's value can be computed by w.f() * 2^w.e() 384 // We can obtain w's integral digits by simply shifting w.f() by -w.e(). 385 // -> w's integral part is 0x1234 386 // w's fractional part is therefore 0x567890abcdef. 387 // Printing w's integral part is easy (simply print 0x1234 in decimal). 388 // In order to print its fraction we repeatedly multiply the fraction by 10 and 389 // get each digit. Example the first digit after the point would be computed by 390 // (0x567890abcdef * 10) >> 48. -> 3 391 // The whole thing becomes slightly more complicated because we want to stop 392 // once we have enough digits. That is, once the digits inside the buffer 393 // represent 'w' we can stop. Everything inside the interval low - high 394 // represents w. However we have to pay attention to low, high and w's 395 // imprecision. 396 static bool DigitGen(DiyFp low, 397 DiyFp w, 398 DiyFp high, 399 BufferReference<char> buffer, 400 int* length, 401 int* kappa) { 402 ASSERT(low.e() == w.e() && w.e() == high.e()); 403 ASSERT(low.f() + 1 <= high.f() - 1); 404 ASSERT(kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent); 405 // low, w and high are imprecise, but by less than one ulp (unit in the last 406 // place). 407 // If we remove (resp. add) 1 ulp from low (resp. high) we are certain that 408 // the new numbers are outside of the interval we want the final 409 // representation to lie in. 410 // Inversely adding (resp. removing) 1 ulp from low (resp. high) would yield 411 // numbers that are certain to lie in the interval. We will use this fact 412 // later on. 413 // We will now start by generating the digits within the uncertain 414 // interval. Later we will weed out representations that lie outside the safe 415 // interval and thus _might_ lie outside the correct interval. 416 uint64_t unit = 1; 417 DiyFp too_low = DiyFp(low.f() - unit, low.e()); 418 DiyFp too_high = DiyFp(high.f() + unit, high.e()); 419 // too_low and too_high are guaranteed to lie outside the interval we want the 420 // generated number in. 421 DiyFp unsafe_interval = DiyFp::Minus(too_high, too_low); 422 // We now cut the input number into two parts: the integral digits and the 423 // fractionals. We will not write any decimal separator though, but adapt 424 // kappa instead. 425 // Reminder: we are currently computing the digits (stored inside the buffer) 426 // such that: too_low < buffer * 10^kappa < too_high 427 // We use too_high for the digit_generation and stop as soon as possible. 428 // If we stop early we effectively round down. 429 DiyFp one = DiyFp(static_cast<uint64_t>(1) << -w.e(), w.e()); 430 // Division by one is a shift. 431 uint32_t integrals = static_cast<uint32_t>(too_high.f() >> -one.e()); 432 // Modulo by one is an and. 433 uint64_t fractionals = too_high.f() & (one.f() - 1); 434 uint32_t divisor; 435 int divisor_exponent; 436 BiggestPowerTen(integrals, DiyFp::kSignificandSize - (-one.e()), 437 &divisor, &divisor_exponent); 438 *kappa = divisor_exponent + 1; 439 *length = 0; 440 // Loop invariant: buffer = too_high / 10^kappa (integer division) 441 // The invariant holds for the first iteration: kappa has been initialized 442 // with the divisor exponent + 1. And the divisor is the biggest power of ten 443 // that is smaller than integrals. 444 while (*kappa > 0) { 445 int digit = integrals / divisor; 446 buffer[*length] = '0' + digit; 447 (*length)++; 448 integrals %= divisor; 449 (*kappa)--; 450 // Note that kappa now equals the exponent of the divisor and that the 451 // invariant thus holds again. 452 uint64_t rest = 453 (static_cast<uint64_t>(integrals) << -one.e()) + fractionals; 454 // Invariant: too_high = buffer * 10^kappa + DiyFp(rest, one.e()) 455 // Reminder: unsafe_interval.e() == one.e() 456 if (rest < unsafe_interval.f()) { 457 // Rounding down (by not emitting the remaining digits) yields a number 458 // that lies within the unsafe interval. 459 return RoundWeed(buffer, *length, DiyFp::Minus(too_high, w).f(), 460 unsafe_interval.f(), rest, 461 static_cast<uint64_t>(divisor) << -one.e(), unit); 462 } 463 divisor /= 10; 464 } 465 466 // The integrals have been generated. We are at the point of the decimal 467 // separator. In the following loop we simply multiply the remaining digits by 468 // 10 and divide by one. We just need to pay attention to multiply associated 469 // data (like the interval or 'unit'), too. 470 // Note that the multiplication by 10 does not overflow, because w.e >= -60 471 // and thus one.e >= -60. 472 ASSERT(one.e() >= -60); 473 ASSERT(fractionals < one.f()); 474 ASSERT(UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.f()); 475 while (true) { 476 fractionals *= 10; 477 unit *= 10; 478 unsafe_interval.set_f(unsafe_interval.f() * 10); 479 // Integer division by one. 480 int digit = static_cast<int>(fractionals >> -one.e()); 481 buffer[*length] = '0' + digit; 482 (*length)++; 483 fractionals &= one.f() - 1; // Modulo by one. 484 (*kappa)--; 485 if (fractionals < unsafe_interval.f()) { 486 return RoundWeed(buffer, *length, DiyFp::Minus(too_high, w).f() * unit, 487 unsafe_interval.f(), fractionals, one.f(), unit); 488 } 489 } 490 } 491 492 493 494 // Generates (at most) requested_digits digits of input number w. 495 // w is a floating-point number (DiyFp), consisting of a significand and an 496 // exponent. Its exponent is bounded by kMinimalTargetExponent and 497 // kMaximalTargetExponent. 498 // Hence -60 <= w.e() <= -32. 499 // 500 // Returns false if it fails, in which case the generated digits in the buffer 501 // should not be used. 502 // Preconditions: 503 // * w is correct up to 1 ulp (unit in the last place). That 504 // is, its error must be strictly less than a unit of its last digit. 505 // * kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent 506 // 507 // Postconditions: returns false if procedure fails. 508 // otherwise: 509 // * buffer is not null-terminated, but length contains the number of 510 // digits. 511 // * the representation in buffer is the most precise representation of 512 // requested_digits digits. 513 // * buffer contains at most requested_digits digits of w. If there are less 514 // than requested_digits digits then some trailing '0's have been removed. 515 // * kappa is such that 516 // w = buffer * 10^kappa + eps with |eps| < 10^kappa / 2. 517 // 518 // Remark: This procedure takes into account the imprecision of its input 519 // numbers. If the precision is not enough to guarantee all the postconditions 520 // then false is returned. This usually happens rarely, but the failure-rate 521 // increases with higher requested_digits. 522 static bool DigitGenCounted(DiyFp w, 523 int requested_digits, 524 BufferReference<char> buffer, 525 int* length, 526 int* kappa) { 527 ASSERT(kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent); 528 ASSERT(kMinimalTargetExponent >= -60); 529 ASSERT(kMaximalTargetExponent <= -32); 530 // w is assumed to have an error less than 1 unit. Whenever w is scaled we 531 // also scale its error. 532 uint64_t w_error = 1; 533 // We cut the input number into two parts: the integral digits and the 534 // fractional digits. We don't emit any decimal separator, but adapt kappa 535 // instead. Example: instead of writing "1.2" we put "12" into the buffer and 536 // increase kappa by 1. 537 DiyFp one = DiyFp(static_cast<uint64_t>(1) << -w.e(), w.e()); 538 // Division by one is a shift. 539 uint32_t integrals = static_cast<uint32_t>(w.f() >> -one.e()); 540 // Modulo by one is an and. 541 uint64_t fractionals = w.f() & (one.f() - 1); 542 uint32_t divisor; 543 int divisor_exponent; 544 BiggestPowerTen(integrals, DiyFp::kSignificandSize - (-one.e()), 545 &divisor, &divisor_exponent); 546 *kappa = divisor_exponent + 1; 547 *length = 0; 548 549 // Loop invariant: buffer = w / 10^kappa (integer division) 550 // The invariant holds for the first iteration: kappa has been initialized 551 // with the divisor exponent + 1. And the divisor is the biggest power of ten 552 // that is smaller than 'integrals'. 553 while (*kappa > 0) { 554 int digit = integrals / divisor; 555 buffer[*length] = '0' + digit; 556 (*length)++; 557 requested_digits--; 558 integrals %= divisor; 559 (*kappa)--; 560 // Note that kappa now equals the exponent of the divisor and that the 561 // invariant thus holds again. 562 if (requested_digits == 0) break; 563 divisor /= 10; 564 } 565 566 if (requested_digits == 0) { 567 uint64_t rest = 568 (static_cast<uint64_t>(integrals) << -one.e()) + fractionals; 569 return RoundWeedCounted(buffer, *length, rest, 570 static_cast<uint64_t>(divisor) << -one.e(), w_error, 571 kappa); 572 } 573 574 // The integrals have been generated. We are at the point of the decimal 575 // separator. In the following loop we simply multiply the remaining digits by 576 // 10 and divide by one. We just need to pay attention to multiply associated 577 // data (the 'unit'), too. 578 // Note that the multiplication by 10 does not overflow, because w.e >= -60 579 // and thus one.e >= -60. 580 ASSERT(one.e() >= -60); 581 ASSERT(fractionals < one.f()); 582 ASSERT(UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.f()); 583 while (requested_digits > 0 && fractionals > w_error) { 584 fractionals *= 10; 585 w_error *= 10; 586 // Integer division by one. 587 int digit = static_cast<int>(fractionals >> -one.e()); 588 buffer[*length] = '0' + digit; 589 (*length)++; 590 requested_digits--; 591 fractionals &= one.f() - 1; // Modulo by one. 592 (*kappa)--; 593 } 594 if (requested_digits != 0) return false; 595 return RoundWeedCounted(buffer, *length, fractionals, one.f(), w_error, 596 kappa); 597 } 598 599 600 // Provides a decimal representation of v. 601 // Returns true if it succeeds, otherwise the result cannot be trusted. 602 // There will be *length digits inside the buffer (not null-terminated). 603 // If the function returns true then 604 // v == (double) (buffer * 10^decimal_exponent). 605 // The digits in the buffer are the shortest representation possible: no 606 // 0.09999999999999999 instead of 0.1. The shorter representation will even be 607 // chosen even if the longer one would be closer to v. 608 // The last digit will be closest to the actual v. That is, even if several 609 // digits might correctly yield 'v' when read again, the closest will be 610 // computed. 611 static bool Grisu3(double v, 612 BufferReference<char> buffer, 613 int* length, 614 int* decimal_exponent) { 615 DiyFp w = Double(v).AsNormalizedDiyFp(); 616 // boundary_minus and boundary_plus are the boundaries between v and its 617 // closest floating-point neighbors. Any number strictly between 618 // boundary_minus and boundary_plus will round to v when convert to a double. 619 // Grisu3 will never output representations that lie exactly on a boundary. 620 DiyFp boundary_minus, boundary_plus; 621 Double(v).NormalizedBoundaries(&boundary_minus, &boundary_plus); 622 ASSERT(boundary_plus.e() == w.e()); 623 DiyFp ten_mk; // Cached power of ten: 10^-k 624 int mk; // -k 625 int ten_mk_minimal_binary_exponent = 626 kMinimalTargetExponent - (w.e() + DiyFp::kSignificandSize); 627 int ten_mk_maximal_binary_exponent = 628 kMaximalTargetExponent - (w.e() + DiyFp::kSignificandSize); 629 PowersOfTenCache::GetCachedPowerForBinaryExponentRange( 630 ten_mk_minimal_binary_exponent, 631 ten_mk_maximal_binary_exponent, 632 &ten_mk, &mk); 633 ASSERT((kMinimalTargetExponent <= w.e() + ten_mk.e() + 634 DiyFp::kSignificandSize) && 635 (kMaximalTargetExponent >= w.e() + ten_mk.e() + 636 DiyFp::kSignificandSize)); 637 // Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a 638 // 64 bit significand and ten_mk is thus only precise up to 64 bits. 639 640 // The DiyFp::Times procedure rounds its result, and ten_mk is approximated 641 // too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now 642 // off by a small amount. 643 // In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w. 644 // In other words: let f = scaled_w.f() and e = scaled_w.e(), then 645 // (f-1) * 2^e < w*10^k < (f+1) * 2^e 646 DiyFp scaled_w = DiyFp::Times(w, ten_mk); 647 ASSERT(scaled_w.e() == 648 boundary_plus.e() + ten_mk.e() + DiyFp::kSignificandSize); 649 // In theory it would be possible to avoid some recomputations by computing 650 // the difference between w and boundary_minus/plus (a power of 2) and to 651 // compute scaled_boundary_minus/plus by subtracting/adding from 652 // scaled_w. However the code becomes much less readable and the speed 653 // enhancements are not terriffic. 654 DiyFp scaled_boundary_minus = DiyFp::Times(boundary_minus, ten_mk); 655 DiyFp scaled_boundary_plus = DiyFp::Times(boundary_plus, ten_mk); 656 657 // DigitGen will generate the digits of scaled_w. Therefore we have 658 // v == (double) (scaled_w * 10^-mk). 659 // Set decimal_exponent == -mk and pass it to DigitGen. If scaled_w is not an 660 // integer than it will be updated. For instance if scaled_w == 1.23 then 661 // the buffer will be filled with "123" und the decimal_exponent will be 662 // decreased by 2. 663 int kappa; 664 bool result = DigitGen(scaled_boundary_minus, scaled_w, scaled_boundary_plus, 665 buffer, length, &kappa); 666 *decimal_exponent = -mk + kappa; 667 return result; 668 } 669 670 671 // The "counted" version of grisu3 (see above) only generates requested_digits 672 // number of digits. This version does not generate the shortest representation, 673 // and with enough requested digits 0.1 will at some point print as 0.9999999... 674 // Grisu3 is too imprecise for real halfway cases (1.5 will not work) and 675 // therefore the rounding strategy for halfway cases is irrelevant. 676 static bool Grisu3Counted(double v, 677 int requested_digits, 678 BufferReference<char> buffer, 679 int* length, 680 int* decimal_exponent) { 681 DiyFp w = Double(v).AsNormalizedDiyFp(); 682 DiyFp ten_mk; // Cached power of ten: 10^-k 683 int mk; // -k 684 int ten_mk_minimal_binary_exponent = 685 kMinimalTargetExponent - (w.e() + DiyFp::kSignificandSize); 686 int ten_mk_maximal_binary_exponent = 687 kMaximalTargetExponent - (w.e() + DiyFp::kSignificandSize); 688 PowersOfTenCache::GetCachedPowerForBinaryExponentRange( 689 ten_mk_minimal_binary_exponent, 690 ten_mk_maximal_binary_exponent, 691 &ten_mk, &mk); 692 ASSERT((kMinimalTargetExponent <= w.e() + ten_mk.e() + 693 DiyFp::kSignificandSize) && 694 (kMaximalTargetExponent >= w.e() + ten_mk.e() + 695 DiyFp::kSignificandSize)); 696 // Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a 697 // 64 bit significand and ten_mk is thus only precise up to 64 bits. 698 699 // The DiyFp::Times procedure rounds its result, and ten_mk is approximated 700 // too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now 701 // off by a small amount. 702 // In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w. 703 // In other words: let f = scaled_w.f() and e = scaled_w.e(), then 704 // (f-1) * 2^e < w*10^k < (f+1) * 2^e 705 DiyFp scaled_w = DiyFp::Times(w, ten_mk); 706 707 // We now have (double) (scaled_w * 10^-mk). 708 // DigitGen will generate the first requested_digits digits of scaled_w and 709 // return together with a kappa such that scaled_w ~= buffer * 10^kappa. (It 710 // will not always be exactly the same since DigitGenCounted only produces a 711 // limited number of digits.) 712 int kappa; 713 bool result = DigitGenCounted(scaled_w, requested_digits, 714 buffer, length, &kappa); 715 *decimal_exponent = -mk + kappa; 716 return result; 717 } 718 719 720 bool FastDtoa(double v, 721 FastDtoaMode mode, 722 int requested_digits, 723 BufferReference<char> buffer, 724 int* length, 725 int* decimal_point) { 726 ASSERT(v > 0); 727 ASSERT(!Double(v).IsSpecial()); 728 729 bool result = false; 730 int decimal_exponent = 0; 731 switch (mode) { 732 case FAST_DTOA_SHORTEST: 733 result = Grisu3(v, buffer, length, &decimal_exponent); 734 break; 735 case FAST_DTOA_PRECISION: 736 result = Grisu3Counted(v, requested_digits, 737 buffer, length, &decimal_exponent); 738 break; 739 default: 740 UNREACHABLE(); 741 } 742 if (result) { 743 *decimal_point = *length + decimal_exponent; 744 buffer[*length] = '\0'; 745 } 746 return result; 747 } 748 749} // namespace double_conversion 750 751} // namespace WTF 752