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