mfbt/double-conversion/fast-dtoa.cc

Tue, 06 Jan 2015 21:39:09 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Tue, 06 Jan 2015 21:39:09 +0100
branch
TOR_BUG_9701
changeset 8
97036ab72558
permissions
-rw-r--r--

Conditionally force memory storage according to privacy.thirdparty.isolate;
This solves Tor bug #9701, complying with disk avoidance documented in
https://www.torproject.org/projects/torbrowser/design/#disk-avoidance.

michael@0 1 // Copyright 2012 the V8 project authors. All rights reserved.
michael@0 2 // Redistribution and use in source and binary forms, with or without
michael@0 3 // modification, are permitted provided that the following conditions are
michael@0 4 // met:
michael@0 5 //
michael@0 6 // * Redistributions of source code must retain the above copyright
michael@0 7 // notice, this list of conditions and the following disclaimer.
michael@0 8 // * Redistributions in binary form must reproduce the above
michael@0 9 // copyright notice, this list of conditions and the following
michael@0 10 // disclaimer in the documentation and/or other materials provided
michael@0 11 // with the distribution.
michael@0 12 // * Neither the name of Google Inc. nor the names of its
michael@0 13 // contributors may be used to endorse or promote products derived
michael@0 14 // from this software without specific prior written permission.
michael@0 15 //
michael@0 16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
michael@0 17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
michael@0 18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
michael@0 19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
michael@0 20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
michael@0 21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
michael@0 22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
michael@0 23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
michael@0 24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
michael@0 25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
michael@0 26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
michael@0 27
michael@0 28 #include "fast-dtoa.h"
michael@0 29
michael@0 30 #include "cached-powers.h"
michael@0 31 #include "diy-fp.h"
michael@0 32 #include "ieee.h"
michael@0 33
michael@0 34 namespace double_conversion {
michael@0 35
michael@0 36 // The minimal and maximal target exponent define the range of w's binary
michael@0 37 // exponent, where 'w' is the result of multiplying the input by a cached power
michael@0 38 // of ten.
michael@0 39 //
michael@0 40 // A different range might be chosen on a different platform, to optimize digit
michael@0 41 // generation, but a smaller range requires more powers of ten to be cached.
michael@0 42 static const int kMinimalTargetExponent = -60;
michael@0 43 static const int kMaximalTargetExponent = -32;
michael@0 44
michael@0 45
michael@0 46 // Adjusts the last digit of the generated number, and screens out generated
michael@0 47 // solutions that may be inaccurate. A solution may be inaccurate if it is
michael@0 48 // outside the safe interval, or if we cannot prove that it is closer to the
michael@0 49 // input than a neighboring representation of the same length.
michael@0 50 //
michael@0 51 // Input: * buffer containing the digits of too_high / 10^kappa
michael@0 52 // * the buffer's length
michael@0 53 // * distance_too_high_w == (too_high - w).f() * unit
michael@0 54 // * unsafe_interval == (too_high - too_low).f() * unit
michael@0 55 // * rest = (too_high - buffer * 10^kappa).f() * unit
michael@0 56 // * ten_kappa = 10^kappa * unit
michael@0 57 // * unit = the common multiplier
michael@0 58 // Output: returns true if the buffer is guaranteed to contain the closest
michael@0 59 // representable number to the input.
michael@0 60 // Modifies the generated digits in the buffer to approach (round towards) w.
michael@0 61 static bool RoundWeed(Vector<char> buffer,
michael@0 62 int length,
michael@0 63 uint64_t distance_too_high_w,
michael@0 64 uint64_t unsafe_interval,
michael@0 65 uint64_t rest,
michael@0 66 uint64_t ten_kappa,
michael@0 67 uint64_t unit) {
michael@0 68 uint64_t small_distance = distance_too_high_w - unit;
michael@0 69 uint64_t big_distance = distance_too_high_w + unit;
michael@0 70 // Let w_low = too_high - big_distance, and
michael@0 71 // w_high = too_high - small_distance.
michael@0 72 // Note: w_low < w < w_high
michael@0 73 //
michael@0 74 // The real w (* unit) must lie somewhere inside the interval
michael@0 75 // ]w_low; w_high[ (often written as "(w_low; w_high)")
michael@0 76
michael@0 77 // Basically the buffer currently contains a number in the unsafe interval
michael@0 78 // ]too_low; too_high[ with too_low < w < too_high
michael@0 79 //
michael@0 80 // too_high - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
michael@0 81 // ^v 1 unit ^ ^ ^ ^
michael@0 82 // boundary_high --------------------- . . . .
michael@0 83 // ^v 1 unit . . . .
michael@0 84 // - - - - - - - - - - - - - - - - - - - + - - + - - - - - - . .
michael@0 85 // . . ^ . .
michael@0 86 // . big_distance . . .
michael@0 87 // . . . . rest
michael@0 88 // small_distance . . . .
michael@0 89 // v . . . .
michael@0 90 // w_high - - - - - - - - - - - - - - - - - - . . . .
michael@0 91 // ^v 1 unit . . . .
michael@0 92 // w ---------------------------------------- . . . .
michael@0 93 // ^v 1 unit v . . .
michael@0 94 // w_low - - - - - - - - - - - - - - - - - - - - - . . .
michael@0 95 // . . v
michael@0 96 // buffer --------------------------------------------------+-------+--------
michael@0 97 // . .
michael@0 98 // safe_interval .
michael@0 99 // v .
michael@0 100 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - .
michael@0 101 // ^v 1 unit .
michael@0 102 // boundary_low ------------------------- unsafe_interval
michael@0 103 // ^v 1 unit v
michael@0 104 // too_low - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
michael@0 105 //
michael@0 106 //
michael@0 107 // Note that the value of buffer could lie anywhere inside the range too_low
michael@0 108 // to too_high.
michael@0 109 //
michael@0 110 // boundary_low, boundary_high and w are approximations of the real boundaries
michael@0 111 // and v (the input number). They are guaranteed to be precise up to one unit.
michael@0 112 // In fact the error is guaranteed to be strictly less than one unit.
michael@0 113 //
michael@0 114 // Anything that lies outside the unsafe interval is guaranteed not to round
michael@0 115 // to v when read again.
michael@0 116 // Anything that lies inside the safe interval is guaranteed to round to v
michael@0 117 // when read again.
michael@0 118 // If the number inside the buffer lies inside the unsafe interval but not
michael@0 119 // inside the safe interval then we simply do not know and bail out (returning
michael@0 120 // false).
michael@0 121 //
michael@0 122 // Similarly we have to take into account the imprecision of 'w' when finding
michael@0 123 // the closest representation of 'w'. If we have two potential
michael@0 124 // representations, and one is closer to both w_low and w_high, then we know
michael@0 125 // it is closer to the actual value v.
michael@0 126 //
michael@0 127 // By generating the digits of too_high we got the largest (closest to
michael@0 128 // too_high) buffer that is still in the unsafe interval. In the case where
michael@0 129 // w_high < buffer < too_high we try to decrement the buffer.
michael@0 130 // This way the buffer approaches (rounds towards) w.
michael@0 131 // There are 3 conditions that stop the decrementation process:
michael@0 132 // 1) the buffer is already below w_high
michael@0 133 // 2) decrementing the buffer would make it leave the unsafe interval
michael@0 134 // 3) decrementing the buffer would yield a number below w_high and farther
michael@0 135 // away than the current number. In other words:
michael@0 136 // (buffer{-1} < w_high) && w_high - buffer{-1} > buffer - w_high
michael@0 137 // Instead of using the buffer directly we use its distance to too_high.
michael@0 138 // Conceptually rest ~= too_high - buffer
michael@0 139 // We need to do the following tests in this order to avoid over- and
michael@0 140 // underflows.
michael@0 141 ASSERT(rest <= unsafe_interval);
michael@0 142 while (rest < small_distance && // Negated condition 1
michael@0 143 unsafe_interval - rest >= ten_kappa && // Negated condition 2
michael@0 144 (rest + ten_kappa < small_distance || // buffer{-1} > w_high
michael@0 145 small_distance - rest >= rest + ten_kappa - small_distance)) {
michael@0 146 buffer[length - 1]--;
michael@0 147 rest += ten_kappa;
michael@0 148 }
michael@0 149
michael@0 150 // We have approached w+ as much as possible. We now test if approaching w-
michael@0 151 // would require changing the buffer. If yes, then we have two possible
michael@0 152 // representations close to w, but we cannot decide which one is closer.
michael@0 153 if (rest < big_distance &&
michael@0 154 unsafe_interval - rest >= ten_kappa &&
michael@0 155 (rest + ten_kappa < big_distance ||
michael@0 156 big_distance - rest > rest + ten_kappa - big_distance)) {
michael@0 157 return false;
michael@0 158 }
michael@0 159
michael@0 160 // Weeding test.
michael@0 161 // The safe interval is [too_low + 2 ulp; too_high - 2 ulp]
michael@0 162 // Since too_low = too_high - unsafe_interval this is equivalent to
michael@0 163 // [too_high - unsafe_interval + 4 ulp; too_high - 2 ulp]
michael@0 164 // Conceptually we have: rest ~= too_high - buffer
michael@0 165 return (2 * unit <= rest) && (rest <= unsafe_interval - 4 * unit);
michael@0 166 }
michael@0 167
michael@0 168
michael@0 169 // Rounds the buffer upwards if the result is closer to v by possibly adding
michael@0 170 // 1 to the buffer. If the precision of the calculation is not sufficient to
michael@0 171 // round correctly, return false.
michael@0 172 // The rounding might shift the whole buffer in which case the kappa is
michael@0 173 // adjusted. For example "99", kappa = 3 might become "10", kappa = 4.
michael@0 174 //
michael@0 175 // If 2*rest > ten_kappa then the buffer needs to be round up.
michael@0 176 // rest can have an error of +/- 1 unit. This function accounts for the
michael@0 177 // imprecision and returns false, if the rounding direction cannot be
michael@0 178 // unambiguously determined.
michael@0 179 //
michael@0 180 // Precondition: rest < ten_kappa.
michael@0 181 static bool RoundWeedCounted(Vector<char> buffer,
michael@0 182 int length,
michael@0 183 uint64_t rest,
michael@0 184 uint64_t ten_kappa,
michael@0 185 uint64_t unit,
michael@0 186 int* kappa) {
michael@0 187 ASSERT(rest < ten_kappa);
michael@0 188 // The following tests are done in a specific order to avoid overflows. They
michael@0 189 // will work correctly with any uint64 values of rest < ten_kappa and unit.
michael@0 190 //
michael@0 191 // If the unit is too big, then we don't know which way to round. For example
michael@0 192 // a unit of 50 means that the real number lies within rest +/- 50. If
michael@0 193 // 10^kappa == 40 then there is no way to tell which way to round.
michael@0 194 if (unit >= ten_kappa) return false;
michael@0 195 // Even if unit is just half the size of 10^kappa we are already completely
michael@0 196 // lost. (And after the previous test we know that the expression will not
michael@0 197 // over/underflow.)
michael@0 198 if (ten_kappa - unit <= unit) return false;
michael@0 199 // If 2 * (rest + unit) <= 10^kappa we can safely round down.
michael@0 200 if ((ten_kappa - rest > rest) && (ten_kappa - 2 * rest >= 2 * unit)) {
michael@0 201 return true;
michael@0 202 }
michael@0 203 // If 2 * (rest - unit) >= 10^kappa, then we can safely round up.
michael@0 204 if ((rest > unit) && (ten_kappa - (rest - unit) <= (rest - unit))) {
michael@0 205 // Increment the last digit recursively until we find a non '9' digit.
michael@0 206 buffer[length - 1]++;
michael@0 207 for (int i = length - 1; i > 0; --i) {
michael@0 208 if (buffer[i] != '0' + 10) break;
michael@0 209 buffer[i] = '0';
michael@0 210 buffer[i - 1]++;
michael@0 211 }
michael@0 212 // If the first digit is now '0'+ 10 we had a buffer with all '9's. With the
michael@0 213 // exception of the first digit all digits are now '0'. Simply switch the
michael@0 214 // first digit to '1' and adjust the kappa. Example: "99" becomes "10" and
michael@0 215 // the power (the kappa) is increased.
michael@0 216 if (buffer[0] == '0' + 10) {
michael@0 217 buffer[0] = '1';
michael@0 218 (*kappa) += 1;
michael@0 219 }
michael@0 220 return true;
michael@0 221 }
michael@0 222 return false;
michael@0 223 }
michael@0 224
michael@0 225 // Returns the biggest power of ten that is less than or equal to the given
michael@0 226 // number. We furthermore receive the maximum number of bits 'number' has.
michael@0 227 //
michael@0 228 // Returns power == 10^(exponent_plus_one-1) such that
michael@0 229 // power <= number < power * 10.
michael@0 230 // If number_bits == 0 then 0^(0-1) is returned.
michael@0 231 // The number of bits must be <= 32.
michael@0 232 // Precondition: number < (1 << (number_bits + 1)).
michael@0 233
michael@0 234 // Inspired by the method for finding an integer log base 10 from here:
michael@0 235 // http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10
michael@0 236 static unsigned int const kSmallPowersOfTen[] =
michael@0 237 {0, 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
michael@0 238 1000000000};
michael@0 239
michael@0 240 static void BiggestPowerTen(uint32_t number,
michael@0 241 int number_bits,
michael@0 242 uint32_t* power,
michael@0 243 int* exponent_plus_one) {
michael@0 244 ASSERT(number < (1u << (number_bits + 1)));
michael@0 245 // 1233/4096 is approximately 1/lg(10).
michael@0 246 int exponent_plus_one_guess = ((number_bits + 1) * 1233 >> 12);
michael@0 247 // We increment to skip over the first entry in the kPowersOf10 table.
michael@0 248 // Note: kPowersOf10[i] == 10^(i-1).
michael@0 249 exponent_plus_one_guess++;
michael@0 250 // We don't have any guarantees that 2^number_bits <= number.
michael@0 251 // TODO(floitsch): can we change the 'while' into an 'if'? We definitely see
michael@0 252 // number < (2^number_bits - 1), but I haven't encountered
michael@0 253 // number < (2^number_bits - 2) yet.
michael@0 254 while (number < kSmallPowersOfTen[exponent_plus_one_guess]) {
michael@0 255 exponent_plus_one_guess--;
michael@0 256 }
michael@0 257 *power = kSmallPowersOfTen[exponent_plus_one_guess];
michael@0 258 *exponent_plus_one = exponent_plus_one_guess;
michael@0 259 }
michael@0 260
michael@0 261 // Generates the digits of input number w.
michael@0 262 // w is a floating-point number (DiyFp), consisting of a significand and an
michael@0 263 // exponent. Its exponent is bounded by kMinimalTargetExponent and
michael@0 264 // kMaximalTargetExponent.
michael@0 265 // Hence -60 <= w.e() <= -32.
michael@0 266 //
michael@0 267 // Returns false if it fails, in which case the generated digits in the buffer
michael@0 268 // should not be used.
michael@0 269 // Preconditions:
michael@0 270 // * low, w and high are correct up to 1 ulp (unit in the last place). That
michael@0 271 // is, their error must be less than a unit of their last digits.
michael@0 272 // * low.e() == w.e() == high.e()
michael@0 273 // * low < w < high, and taking into account their error: low~ <= high~
michael@0 274 // * kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent
michael@0 275 // Postconditions: returns false if procedure fails.
michael@0 276 // otherwise:
michael@0 277 // * buffer is not null-terminated, but len contains the number of digits.
michael@0 278 // * buffer contains the shortest possible decimal digit-sequence
michael@0 279 // such that LOW < buffer * 10^kappa < HIGH, where LOW and HIGH are the
michael@0 280 // correct values of low and high (without their error).
michael@0 281 // * if more than one decimal representation gives the minimal number of
michael@0 282 // decimal digits then the one closest to W (where W is the correct value
michael@0 283 // of w) is chosen.
michael@0 284 // Remark: this procedure takes into account the imprecision of its input
michael@0 285 // numbers. If the precision is not enough to guarantee all the postconditions
michael@0 286 // then false is returned. This usually happens rarely (~0.5%).
michael@0 287 //
michael@0 288 // Say, for the sake of example, that
michael@0 289 // w.e() == -48, and w.f() == 0x1234567890abcdef
michael@0 290 // w's value can be computed by w.f() * 2^w.e()
michael@0 291 // We can obtain w's integral digits by simply shifting w.f() by -w.e().
michael@0 292 // -> w's integral part is 0x1234
michael@0 293 // w's fractional part is therefore 0x567890abcdef.
michael@0 294 // Printing w's integral part is easy (simply print 0x1234 in decimal).
michael@0 295 // In order to print its fraction we repeatedly multiply the fraction by 10 and
michael@0 296 // get each digit. Example the first digit after the point would be computed by
michael@0 297 // (0x567890abcdef * 10) >> 48. -> 3
michael@0 298 // The whole thing becomes slightly more complicated because we want to stop
michael@0 299 // once we have enough digits. That is, once the digits inside the buffer
michael@0 300 // represent 'w' we can stop. Everything inside the interval low - high
michael@0 301 // represents w. However we have to pay attention to low, high and w's
michael@0 302 // imprecision.
michael@0 303 static bool DigitGen(DiyFp low,
michael@0 304 DiyFp w,
michael@0 305 DiyFp high,
michael@0 306 Vector<char> buffer,
michael@0 307 int* length,
michael@0 308 int* kappa) {
michael@0 309 ASSERT(low.e() == w.e() && w.e() == high.e());
michael@0 310 ASSERT(low.f() + 1 <= high.f() - 1);
michael@0 311 ASSERT(kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent);
michael@0 312 // low, w and high are imprecise, but by less than one ulp (unit in the last
michael@0 313 // place).
michael@0 314 // If we remove (resp. add) 1 ulp from low (resp. high) we are certain that
michael@0 315 // the new numbers are outside of the interval we want the final
michael@0 316 // representation to lie in.
michael@0 317 // Inversely adding (resp. removing) 1 ulp from low (resp. high) would yield
michael@0 318 // numbers that are certain to lie in the interval. We will use this fact
michael@0 319 // later on.
michael@0 320 // We will now start by generating the digits within the uncertain
michael@0 321 // interval. Later we will weed out representations that lie outside the safe
michael@0 322 // interval and thus _might_ lie outside the correct interval.
michael@0 323 uint64_t unit = 1;
michael@0 324 DiyFp too_low = DiyFp(low.f() - unit, low.e());
michael@0 325 DiyFp too_high = DiyFp(high.f() + unit, high.e());
michael@0 326 // too_low and too_high are guaranteed to lie outside the interval we want the
michael@0 327 // generated number in.
michael@0 328 DiyFp unsafe_interval = DiyFp::Minus(too_high, too_low);
michael@0 329 // We now cut the input number into two parts: the integral digits and the
michael@0 330 // fractionals. We will not write any decimal separator though, but adapt
michael@0 331 // kappa instead.
michael@0 332 // Reminder: we are currently computing the digits (stored inside the buffer)
michael@0 333 // such that: too_low < buffer * 10^kappa < too_high
michael@0 334 // We use too_high for the digit_generation and stop as soon as possible.
michael@0 335 // If we stop early we effectively round down.
michael@0 336 DiyFp one = DiyFp(static_cast<uint64_t>(1) << -w.e(), w.e());
michael@0 337 // Division by one is a shift.
michael@0 338 uint32_t integrals = static_cast<uint32_t>(too_high.f() >> -one.e());
michael@0 339 // Modulo by one is an and.
michael@0 340 uint64_t fractionals = too_high.f() & (one.f() - 1);
michael@0 341 uint32_t divisor;
michael@0 342 int divisor_exponent_plus_one;
michael@0 343 BiggestPowerTen(integrals, DiyFp::kSignificandSize - (-one.e()),
michael@0 344 &divisor, &divisor_exponent_plus_one);
michael@0 345 *kappa = divisor_exponent_plus_one;
michael@0 346 *length = 0;
michael@0 347 // Loop invariant: buffer = too_high / 10^kappa (integer division)
michael@0 348 // The invariant holds for the first iteration: kappa has been initialized
michael@0 349 // with the divisor exponent + 1. And the divisor is the biggest power of ten
michael@0 350 // that is smaller than integrals.
michael@0 351 while (*kappa > 0) {
michael@0 352 int digit = integrals / divisor;
michael@0 353 buffer[*length] = '0' + digit;
michael@0 354 (*length)++;
michael@0 355 integrals %= divisor;
michael@0 356 (*kappa)--;
michael@0 357 // Note that kappa now equals the exponent of the divisor and that the
michael@0 358 // invariant thus holds again.
michael@0 359 uint64_t rest =
michael@0 360 (static_cast<uint64_t>(integrals) << -one.e()) + fractionals;
michael@0 361 // Invariant: too_high = buffer * 10^kappa + DiyFp(rest, one.e())
michael@0 362 // Reminder: unsafe_interval.e() == one.e()
michael@0 363 if (rest < unsafe_interval.f()) {
michael@0 364 // Rounding down (by not emitting the remaining digits) yields a number
michael@0 365 // that lies within the unsafe interval.
michael@0 366 return RoundWeed(buffer, *length, DiyFp::Minus(too_high, w).f(),
michael@0 367 unsafe_interval.f(), rest,
michael@0 368 static_cast<uint64_t>(divisor) << -one.e(), unit);
michael@0 369 }
michael@0 370 divisor /= 10;
michael@0 371 }
michael@0 372
michael@0 373 // The integrals have been generated. We are at the point of the decimal
michael@0 374 // separator. In the following loop we simply multiply the remaining digits by
michael@0 375 // 10 and divide by one. We just need to pay attention to multiply associated
michael@0 376 // data (like the interval or 'unit'), too.
michael@0 377 // Note that the multiplication by 10 does not overflow, because w.e >= -60
michael@0 378 // and thus one.e >= -60.
michael@0 379 ASSERT(one.e() >= -60);
michael@0 380 ASSERT(fractionals < one.f());
michael@0 381 ASSERT(UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.f());
michael@0 382 while (true) {
michael@0 383 fractionals *= 10;
michael@0 384 unit *= 10;
michael@0 385 unsafe_interval.set_f(unsafe_interval.f() * 10);
michael@0 386 // Integer division by one.
michael@0 387 int digit = static_cast<int>(fractionals >> -one.e());
michael@0 388 buffer[*length] = '0' + digit;
michael@0 389 (*length)++;
michael@0 390 fractionals &= one.f() - 1; // Modulo by one.
michael@0 391 (*kappa)--;
michael@0 392 if (fractionals < unsafe_interval.f()) {
michael@0 393 return RoundWeed(buffer, *length, DiyFp::Minus(too_high, w).f() * unit,
michael@0 394 unsafe_interval.f(), fractionals, one.f(), unit);
michael@0 395 }
michael@0 396 }
michael@0 397 }
michael@0 398
michael@0 399
michael@0 400
michael@0 401 // Generates (at most) requested_digits digits of input number w.
michael@0 402 // w is a floating-point number (DiyFp), consisting of a significand and an
michael@0 403 // exponent. Its exponent is bounded by kMinimalTargetExponent and
michael@0 404 // kMaximalTargetExponent.
michael@0 405 // Hence -60 <= w.e() <= -32.
michael@0 406 //
michael@0 407 // Returns false if it fails, in which case the generated digits in the buffer
michael@0 408 // should not be used.
michael@0 409 // Preconditions:
michael@0 410 // * w is correct up to 1 ulp (unit in the last place). That
michael@0 411 // is, its error must be strictly less than a unit of its last digit.
michael@0 412 // * kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent
michael@0 413 //
michael@0 414 // Postconditions: returns false if procedure fails.
michael@0 415 // otherwise:
michael@0 416 // * buffer is not null-terminated, but length contains the number of
michael@0 417 // digits.
michael@0 418 // * the representation in buffer is the most precise representation of
michael@0 419 // requested_digits digits.
michael@0 420 // * buffer contains at most requested_digits digits of w. If there are less
michael@0 421 // than requested_digits digits then some trailing '0's have been removed.
michael@0 422 // * kappa is such that
michael@0 423 // w = buffer * 10^kappa + eps with |eps| < 10^kappa / 2.
michael@0 424 //
michael@0 425 // Remark: This procedure takes into account the imprecision of its input
michael@0 426 // numbers. If the precision is not enough to guarantee all the postconditions
michael@0 427 // then false is returned. This usually happens rarely, but the failure-rate
michael@0 428 // increases with higher requested_digits.
michael@0 429 static bool DigitGenCounted(DiyFp w,
michael@0 430 int requested_digits,
michael@0 431 Vector<char> buffer,
michael@0 432 int* length,
michael@0 433 int* kappa) {
michael@0 434 ASSERT(kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent);
michael@0 435 ASSERT(kMinimalTargetExponent >= -60);
michael@0 436 ASSERT(kMaximalTargetExponent <= -32);
michael@0 437 // w is assumed to have an error less than 1 unit. Whenever w is scaled we
michael@0 438 // also scale its error.
michael@0 439 uint64_t w_error = 1;
michael@0 440 // We cut the input number into two parts: the integral digits and the
michael@0 441 // fractional digits. We don't emit any decimal separator, but adapt kappa
michael@0 442 // instead. Example: instead of writing "1.2" we put "12" into the buffer and
michael@0 443 // increase kappa by 1.
michael@0 444 DiyFp one = DiyFp(static_cast<uint64_t>(1) << -w.e(), w.e());
michael@0 445 // Division by one is a shift.
michael@0 446 uint32_t integrals = static_cast<uint32_t>(w.f() >> -one.e());
michael@0 447 // Modulo by one is an and.
michael@0 448 uint64_t fractionals = w.f() & (one.f() - 1);
michael@0 449 uint32_t divisor;
michael@0 450 int divisor_exponent_plus_one;
michael@0 451 BiggestPowerTen(integrals, DiyFp::kSignificandSize - (-one.e()),
michael@0 452 &divisor, &divisor_exponent_plus_one);
michael@0 453 *kappa = divisor_exponent_plus_one;
michael@0 454 *length = 0;
michael@0 455
michael@0 456 // Loop invariant: buffer = w / 10^kappa (integer division)
michael@0 457 // The invariant holds for the first iteration: kappa has been initialized
michael@0 458 // with the divisor exponent + 1. And the divisor is the biggest power of ten
michael@0 459 // that is smaller than 'integrals'.
michael@0 460 while (*kappa > 0) {
michael@0 461 int digit = integrals / divisor;
michael@0 462 buffer[*length] = '0' + digit;
michael@0 463 (*length)++;
michael@0 464 requested_digits--;
michael@0 465 integrals %= divisor;
michael@0 466 (*kappa)--;
michael@0 467 // Note that kappa now equals the exponent of the divisor and that the
michael@0 468 // invariant thus holds again.
michael@0 469 if (requested_digits == 0) break;
michael@0 470 divisor /= 10;
michael@0 471 }
michael@0 472
michael@0 473 if (requested_digits == 0) {
michael@0 474 uint64_t rest =
michael@0 475 (static_cast<uint64_t>(integrals) << -one.e()) + fractionals;
michael@0 476 return RoundWeedCounted(buffer, *length, rest,
michael@0 477 static_cast<uint64_t>(divisor) << -one.e(), w_error,
michael@0 478 kappa);
michael@0 479 }
michael@0 480
michael@0 481 // The integrals have been generated. We are at the point of the decimal
michael@0 482 // separator. In the following loop we simply multiply the remaining digits by
michael@0 483 // 10 and divide by one. We just need to pay attention to multiply associated
michael@0 484 // data (the 'unit'), too.
michael@0 485 // Note that the multiplication by 10 does not overflow, because w.e >= -60
michael@0 486 // and thus one.e >= -60.
michael@0 487 ASSERT(one.e() >= -60);
michael@0 488 ASSERT(fractionals < one.f());
michael@0 489 ASSERT(UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.f());
michael@0 490 while (requested_digits > 0 && fractionals > w_error) {
michael@0 491 fractionals *= 10;
michael@0 492 w_error *= 10;
michael@0 493 // Integer division by one.
michael@0 494 int digit = static_cast<int>(fractionals >> -one.e());
michael@0 495 buffer[*length] = '0' + digit;
michael@0 496 (*length)++;
michael@0 497 requested_digits--;
michael@0 498 fractionals &= one.f() - 1; // Modulo by one.
michael@0 499 (*kappa)--;
michael@0 500 }
michael@0 501 if (requested_digits != 0) return false;
michael@0 502 return RoundWeedCounted(buffer, *length, fractionals, one.f(), w_error,
michael@0 503 kappa);
michael@0 504 }
michael@0 505
michael@0 506
michael@0 507 // Provides a decimal representation of v.
michael@0 508 // Returns true if it succeeds, otherwise the result cannot be trusted.
michael@0 509 // There will be *length digits inside the buffer (not null-terminated).
michael@0 510 // If the function returns true then
michael@0 511 // v == (double) (buffer * 10^decimal_exponent).
michael@0 512 // The digits in the buffer are the shortest representation possible: no
michael@0 513 // 0.09999999999999999 instead of 0.1. The shorter representation will even be
michael@0 514 // chosen even if the longer one would be closer to v.
michael@0 515 // The last digit will be closest to the actual v. That is, even if several
michael@0 516 // digits might correctly yield 'v' when read again, the closest will be
michael@0 517 // computed.
michael@0 518 static bool Grisu3(double v,
michael@0 519 FastDtoaMode mode,
michael@0 520 Vector<char> buffer,
michael@0 521 int* length,
michael@0 522 int* decimal_exponent) {
michael@0 523 DiyFp w = Double(v).AsNormalizedDiyFp();
michael@0 524 // boundary_minus and boundary_plus are the boundaries between v and its
michael@0 525 // closest floating-point neighbors. Any number strictly between
michael@0 526 // boundary_minus and boundary_plus will round to v when convert to a double.
michael@0 527 // Grisu3 will never output representations that lie exactly on a boundary.
michael@0 528 DiyFp boundary_minus, boundary_plus;
michael@0 529 if (mode == FAST_DTOA_SHORTEST) {
michael@0 530 Double(v).NormalizedBoundaries(&boundary_minus, &boundary_plus);
michael@0 531 } else {
michael@0 532 ASSERT(mode == FAST_DTOA_SHORTEST_SINGLE);
michael@0 533 float single_v = static_cast<float>(v);
michael@0 534 Single(single_v).NormalizedBoundaries(&boundary_minus, &boundary_plus);
michael@0 535 }
michael@0 536 ASSERT(boundary_plus.e() == w.e());
michael@0 537 DiyFp ten_mk; // Cached power of ten: 10^-k
michael@0 538 int mk; // -k
michael@0 539 int ten_mk_minimal_binary_exponent =
michael@0 540 kMinimalTargetExponent - (w.e() + DiyFp::kSignificandSize);
michael@0 541 int ten_mk_maximal_binary_exponent =
michael@0 542 kMaximalTargetExponent - (w.e() + DiyFp::kSignificandSize);
michael@0 543 PowersOfTenCache::GetCachedPowerForBinaryExponentRange(
michael@0 544 ten_mk_minimal_binary_exponent,
michael@0 545 ten_mk_maximal_binary_exponent,
michael@0 546 &ten_mk, &mk);
michael@0 547 ASSERT((kMinimalTargetExponent <= w.e() + ten_mk.e() +
michael@0 548 DiyFp::kSignificandSize) &&
michael@0 549 (kMaximalTargetExponent >= w.e() + ten_mk.e() +
michael@0 550 DiyFp::kSignificandSize));
michael@0 551 // Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a
michael@0 552 // 64 bit significand and ten_mk is thus only precise up to 64 bits.
michael@0 553
michael@0 554 // The DiyFp::Times procedure rounds its result, and ten_mk is approximated
michael@0 555 // too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now
michael@0 556 // off by a small amount.
michael@0 557 // In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w.
michael@0 558 // In other words: let f = scaled_w.f() and e = scaled_w.e(), then
michael@0 559 // (f-1) * 2^e < w*10^k < (f+1) * 2^e
michael@0 560 DiyFp scaled_w = DiyFp::Times(w, ten_mk);
michael@0 561 ASSERT(scaled_w.e() ==
michael@0 562 boundary_plus.e() + ten_mk.e() + DiyFp::kSignificandSize);
michael@0 563 // In theory it would be possible to avoid some recomputations by computing
michael@0 564 // the difference between w and boundary_minus/plus (a power of 2) and to
michael@0 565 // compute scaled_boundary_minus/plus by subtracting/adding from
michael@0 566 // scaled_w. However the code becomes much less readable and the speed
michael@0 567 // enhancements are not terriffic.
michael@0 568 DiyFp scaled_boundary_minus = DiyFp::Times(boundary_minus, ten_mk);
michael@0 569 DiyFp scaled_boundary_plus = DiyFp::Times(boundary_plus, ten_mk);
michael@0 570
michael@0 571 // DigitGen will generate the digits of scaled_w. Therefore we have
michael@0 572 // v == (double) (scaled_w * 10^-mk).
michael@0 573 // Set decimal_exponent == -mk and pass it to DigitGen. If scaled_w is not an
michael@0 574 // integer than it will be updated. For instance if scaled_w == 1.23 then
michael@0 575 // the buffer will be filled with "123" und the decimal_exponent will be
michael@0 576 // decreased by 2.
michael@0 577 int kappa;
michael@0 578 bool result = DigitGen(scaled_boundary_minus, scaled_w, scaled_boundary_plus,
michael@0 579 buffer, length, &kappa);
michael@0 580 *decimal_exponent = -mk + kappa;
michael@0 581 return result;
michael@0 582 }
michael@0 583
michael@0 584
michael@0 585 // The "counted" version of grisu3 (see above) only generates requested_digits
michael@0 586 // number of digits. This version does not generate the shortest representation,
michael@0 587 // and with enough requested digits 0.1 will at some point print as 0.9999999...
michael@0 588 // Grisu3 is too imprecise for real halfway cases (1.5 will not work) and
michael@0 589 // therefore the rounding strategy for halfway cases is irrelevant.
michael@0 590 static bool Grisu3Counted(double v,
michael@0 591 int requested_digits,
michael@0 592 Vector<char> buffer,
michael@0 593 int* length,
michael@0 594 int* decimal_exponent) {
michael@0 595 DiyFp w = Double(v).AsNormalizedDiyFp();
michael@0 596 DiyFp ten_mk; // Cached power of ten: 10^-k
michael@0 597 int mk; // -k
michael@0 598 int ten_mk_minimal_binary_exponent =
michael@0 599 kMinimalTargetExponent - (w.e() + DiyFp::kSignificandSize);
michael@0 600 int ten_mk_maximal_binary_exponent =
michael@0 601 kMaximalTargetExponent - (w.e() + DiyFp::kSignificandSize);
michael@0 602 PowersOfTenCache::GetCachedPowerForBinaryExponentRange(
michael@0 603 ten_mk_minimal_binary_exponent,
michael@0 604 ten_mk_maximal_binary_exponent,
michael@0 605 &ten_mk, &mk);
michael@0 606 ASSERT((kMinimalTargetExponent <= w.e() + ten_mk.e() +
michael@0 607 DiyFp::kSignificandSize) &&
michael@0 608 (kMaximalTargetExponent >= w.e() + ten_mk.e() +
michael@0 609 DiyFp::kSignificandSize));
michael@0 610 // Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a
michael@0 611 // 64 bit significand and ten_mk is thus only precise up to 64 bits.
michael@0 612
michael@0 613 // The DiyFp::Times procedure rounds its result, and ten_mk is approximated
michael@0 614 // too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now
michael@0 615 // off by a small amount.
michael@0 616 // In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w.
michael@0 617 // In other words: let f = scaled_w.f() and e = scaled_w.e(), then
michael@0 618 // (f-1) * 2^e < w*10^k < (f+1) * 2^e
michael@0 619 DiyFp scaled_w = DiyFp::Times(w, ten_mk);
michael@0 620
michael@0 621 // We now have (double) (scaled_w * 10^-mk).
michael@0 622 // DigitGen will generate the first requested_digits digits of scaled_w and
michael@0 623 // return together with a kappa such that scaled_w ~= buffer * 10^kappa. (It
michael@0 624 // will not always be exactly the same since DigitGenCounted only produces a
michael@0 625 // limited number of digits.)
michael@0 626 int kappa;
michael@0 627 bool result = DigitGenCounted(scaled_w, requested_digits,
michael@0 628 buffer, length, &kappa);
michael@0 629 *decimal_exponent = -mk + kappa;
michael@0 630 return result;
michael@0 631 }
michael@0 632
michael@0 633
michael@0 634 bool FastDtoa(double v,
michael@0 635 FastDtoaMode mode,
michael@0 636 int requested_digits,
michael@0 637 Vector<char> buffer,
michael@0 638 int* length,
michael@0 639 int* decimal_point) {
michael@0 640 ASSERT(v > 0);
michael@0 641 ASSERT(!Double(v).IsSpecial());
michael@0 642
michael@0 643 bool result = false;
michael@0 644 int decimal_exponent = 0;
michael@0 645 switch (mode) {
michael@0 646 case FAST_DTOA_SHORTEST:
michael@0 647 case FAST_DTOA_SHORTEST_SINGLE:
michael@0 648 result = Grisu3(v, mode, buffer, length, &decimal_exponent);
michael@0 649 break;
michael@0 650 case FAST_DTOA_PRECISION:
michael@0 651 result = Grisu3Counted(v, requested_digits,
michael@0 652 buffer, length, &decimal_exponent);
michael@0 653 break;
michael@0 654 default:
michael@0 655 UNREACHABLE();
michael@0 656 }
michael@0 657 if (result) {
michael@0 658 *decimal_point = *length + decimal_exponent;
michael@0 659 buffer[*length] = '\0';
michael@0 660 }
michael@0 661 return result;
michael@0 662 }
michael@0 663
michael@0 664 } // namespace double_conversion

mercurial