Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(660)

Side by Side Diff: runtime/third_party/double-conversion/src/fast-dtoa.cc

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

Powered by Google App Engine
This is Rietveld 408576698