Debian Codegraph @

rhino/src/org/mozilla/javascript/v8dtoa/FastDtoa.java

raw symbols SCIP
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 // Ported to Java from Mozilla's version of V8-dtoa by Hannes Wallnoefer.
29 // The original revision was 67d1049b0bf9 from the mozilla-central tree.
30
31 package org.mozilla.javascript.v8dtoa;
32
33 public class FastDtoa {
34
35 // FastDtoa will produce at most kFastDtoaMaximalLength digits.
36 static final int kFastDtoaMaximalLength = 17;
37
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.
45 static final int minimal_target_exponent = -60;
46 static final int maximal_target_exponent = -32;
47
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 // * 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 boolean roundWeed(FastDtoaBuilder buffer,
64 long distance_too_high_w,
65 long unsafe_interval,
66 long rest,
67 long ten_kappa,
68 long unit) {
69 long small_distance = distance_too_high_w - unit;
70 long big_distance = distance_too_high_w + unit;
71 // Let w_low = too_high - big_distance, and
72 // w_high = too_high - small_distance.
73 // Note: w_low < w < w_high
74 //
75 // The real w (* unit) must lie somewhere inside the interval
76 // ]w_low; w_low[ (often written as "(w_low; w_low)")
77
78 // Basically the buffer currently contains a number in the unsafe interval
79 // ]too_low; too_high[ with too_low < w < too_high
80 //
81 // too_high - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
82 // ^v 1 unit ^ ^ ^ ^
83 // boundary_high --------------------- . . . .
84 // ^v 1 unit . . . .
85 // - - - - - - - - - - - - - - - - - - - + - - + - - - - - - . .
86 // . . ^ . .
87 // . big_distance . . .
88 // . . . . rest
89 // small_distance . . . .
90 // v . . . .
91 // w_high - - - - - - - - - - - - - - - - - - . . . .
92 // ^v 1 unit . . . .
93 // w ---------------------------------------- . . . .
94 // ^v 1 unit v . . .
95 // w_low - - - - - - - - - - - - - - - - - - - - - . . .
96 // . . v
97 // buffer --------------------------------------------------+-------+--------
98 // . .
99 // safe_interval .
100 // v .
101 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - .
102 // ^v 1 unit .
103 // boundary_low ------------------------- unsafe_interval
104 // ^v 1 unit v
105 // too_low - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
106 //
107 //
108 // Note that the value of buffer could lie anywhere inside the range too_low
109 // to too_high.
110 //
111 // boundary_low, boundary_high and w are approximations of the real boundaries
112 // and v (the input number). They are guaranteed to be precise up to one unit.
113 // In fact the error is guaranteed to be strictly less than one unit.
114 //
115 // Anything that lies outside the unsafe interval is guaranteed not to round
116 // to v when read again.
117 // Anything that lies inside the safe interval is guaranteed to round to v
118 // when read again.
119 // If the number inside the buffer lies inside the unsafe interval but not
120 // inside the safe interval then we simply do not know and bail out (returning
121 // false).
122 //
123 // Similarly we have to take into account the imprecision of 'w' when rounding
124 // the buffer. If we have two potential representations we need to make sure
125 // that the chosen one is closer to w_low and w_high since v can be anywhere
126 // between them.
127 //
128 // By generating the digits of too_high we got the largest (closest to
129 // too_high) buffer that is still in the unsafe interval. In the case where
130 // w_high < buffer < too_high we try to decrement the buffer.
131 // This way the buffer approaches (rounds towards) w.
132 // There are 3 conditions that stop the decrementation process:
133 // 1) the buffer is already below w_high
134 // 2) decrementing the buffer would make it leave the unsafe interval
135 // 3) decrementing the buffer would yield a number below w_high and farther
136 // away than the current number. In other words:
137 // (buffer{-1} < w_high) && w_high - buffer{-1} > buffer - w_high
138 // Instead of using the buffer directly we use its distance to too_high.
139 // Conceptually rest ~= too_high - buffer
140 while (rest < small_distance && // Negated condition 1
141 unsafe_interval - rest >= ten_kappa && // Negated condition 2
142 (rest + ten_kappa < small_distance || // buffer{-1} > w_high
143 small_distance - rest >= rest + ten_kappa - small_distance)) {
144 buffer.decreaseLast();
145 rest += ten_kappa;
146 }
147
148 // We have approached w+ as much as possible. We now test if approaching w-
149 // would require changing the buffer. If yes, then we have two possible
150 // representations close to w, but we cannot decide which one is closer.
151 if (rest < big_distance &&
152 unsafe_interval - rest >= ten_kappa &&
153 (rest + ten_kappa < big_distance ||
154 big_distance - rest > rest + ten_kappa - big_distance)) {
155 return false;
156 }
157
158 // Weeding test.
159 // The safe interval is [too_low + 2 ulp; too_high - 2 ulp]
160 // Since too_low = too_high - unsafe_interval this is equivalent to
161 // [too_high - unsafe_interval + 4 ulp; too_high - 2 ulp]
162 // Conceptually we have: rest ~= too_high - buffer
163 return (2 * unit <= rest) && (rest <= unsafe_interval - 4 * unit);
164 }
165
166
167
168 static final int kTen4 = 10000;
169 static final int kTen5 = 100000;
170 static final int kTen6 = 1000000;
171 static final int kTen7 = 10000000;
172 static final int kTen8 = 100000000;
173 static final int kTen9 = 1000000000;
174
175 // Returns the biggest power of ten that is less than or equal than the given
176 // number. We furthermore receive the maximum number of bits 'number' has.
177 // If number_bits == 0 then 0^-1 is returned
178 // The number of bits must be <= 32.
179 // Precondition: (1 << number_bits) <= number < (1 << (number_bits + 1)).
180 static long biggestPowerTen(int number,
181 int number_bits) {
182 int power, exponent;
183 switch (number_bits) {
184 case 32:
185 case 31:
186 case 30:
187 if (kTen9 <= number) {
188 power = kTen9;
189 exponent = 9;
190 break;
191 } // else fallthrough
192 case 29:
193 case 28:
194 case 27:
195 if (kTen8 <= number) {
196 power = kTen8;
197 exponent = 8;
198 break;
199 } // else fallthrough
200 case 26:
201 case 25:
202 case 24:
203 if (kTen7 <= number) {
204 power = kTen7;
205 exponent = 7;
206 break;
207 } // else fallthrough
208 case 23:
209 case 22:
210 case 21:
211 case 20:
212 if (kTen6 <= number) {
213 power = kTen6;
214 exponent = 6;
215 break;
216 } // else fallthrough
217 case 19:
218 case 18:
219 case 17:
220 if (kTen5 <= number) {
221 power = kTen5;
222 exponent = 5;
223 break;
224 } // else fallthrough
225 case 16:
226 case 15:
227 case 14:
228 if (kTen4 <= number) {
229 power = kTen4;
230 exponent = 4;
231 break;
232 } // else fallthrough
233 case 13:
234 case 12:
235 case 11:
236 case 10:
237 if (1000 <= number) {
238 power = 1000;
239 exponent = 3;
240 break;
241 } // else fallthrough
242 case 9:
243 case 8:
244 case 7:
245 if (100 <= number) {
246 power = 100;
247 exponent = 2;
248 break;
249 } // else fallthrough
250 case 6:
251 case 5:
252 case 4:
253 if (10 <= number) {
254 power = 10;
255 exponent = 1;
256 break;
257 } // else fallthrough
258 case 3:
259 case 2:
260 case 1:
261 if (1 <= number) {
262 power = 1;
263 exponent = 0;
264 break;
265 } // else fallthrough
266 case 0:
267 power = 0;
268 exponent = -1;
269 break;
270 default:
271 // Following assignments are here to silence compiler warnings.
272 power = 0;
273 exponent = 0;
274 // UNREACHABLE();
275 }
276 return ((long)power << 32) | (0xffffffffL & exponent);
277 }
278
279 private static boolean uint64_lte(long a, long b) {
280 // less-or-equal for unsigned int64 in java-style...
281 return (a == b) || ((a < b) ^ (a < 0) ^ (b < 0));
282 }
283
284 // Generates the digits of input number w.
285 // w is a floating-point number (DiyFp), consisting of a significand and an
286 // exponent. Its exponent is bounded by minimal_target_exponent and
287 // maximal_target_exponent.
288 // Hence -60 <= w.e() <= -32.
289 //
290 // Returns false if it fails, in which case the generated digits in the buffer
291 // should not be used.
292 // Preconditions:
293 // * low, w and high are correct up to 1 ulp (unit in the last place). That
294 // is, their error must be less that a unit of their last digits.
295 // * low.e() == w.e() == high.e()
296 // * low < w < high, and taking into account their error: low~ <= high~
297 // * minimal_target_exponent <= w.e() <= maximal_target_exponent
298 // Postconditions: returns false if procedure fails.
299 // otherwise:
300 // * buffer is not null-terminated, but len contains the number of digits.
301 // * buffer contains the shortest possible decimal digit-sequence
302 // such that LOW < buffer * 10^kappa < HIGH, where LOW and HIGH are the
303 // correct values of low and high (without their error).
304 // * if more than one decimal representation gives the minimal number of
305 // decimal digits then the one closest to W (where W is the correct value
306 // of w) is chosen.
307 // Remark: this procedure takes into account the imprecision of its input
308 // numbers. If the precision is not enough to guarantee all the postconditions
309 // then false is returned. This usually happens rarely (~0.5%).
310 //
311 // Say, for the sake of example, that
312 // w.e() == -48, and w.f() == 0x1234567890abcdef
313 // w's value can be computed by w.f() * 2^w.e()
314 // We can obtain w's integral digits by simply shifting w.f() by -w.e().
315 // -> w's integral part is 0x1234
316 // w's fractional part is therefore 0x567890abcdef.
317 // Printing w's integral part is easy (simply print 0x1234 in decimal).
318 // In order to print its fraction we repeatedly multiply the fraction by 10 and
319 // get each digit. Example the first digit after the point would be computed by
320 // (0x567890abcdef * 10) >> 48. -> 3
321 // The whole thing becomes slightly more complicated because we want to stop
322 // once we have enough digits. That is, once the digits inside the buffer
323 // represent 'w' we can stop. Everything inside the interval low - high
324 // represents w. However we have to pay attention to low, high and w's
325 // imprecision.
326 static boolean digitGen(DiyFp low,
327 DiyFp w,
328 DiyFp high,
329 FastDtoaBuilder buffer,
330 int mk) {
331 assert(low.e() == w.e() && w.e() == high.e());
332 assert uint64_lte(low.f() + 1, high.f() - 1);
333 assert(minimal_target_exponent <= w.e() && w.e() <= maximal_target_exponent);
334 // low, w and high are imprecise, but by less than one ulp (unit in the last
335 // place).
336 // If we remove (resp. add) 1 ulp from low (resp. high) we are certain that
337 // the new numbers are outside of the interval we want the final
338 // representation to lie in.
339 // Inversely adding (resp. removing) 1 ulp from low (resp. high) would yield
340 // numbers that are certain to lie in the interval. We will use this fact
341 // later on.
342 // We will now start by generating the digits within the uncertain
343 // interval. Later we will weed out representations that lie outside the safe
344 // interval and thus _might_ lie outside the correct interval.
345 long unit = 1;
346 DiyFp too_low = new DiyFp(low.f() - unit, low.e());
347 DiyFp too_high = new DiyFp(high.f() + unit, high.e());
348 // too_low and too_high are guaranteed to lie outside the interval we want the
349 // generated number in.
350 DiyFp unsafe_interval = DiyFp.minus(too_high, too_low);
351 // We now cut the input number into two parts: the integral digits and the
352 // fractionals. We will not write any decimal separator though, but adapt
353 // kappa instead.
354 // Reminder: we are currently computing the digits (stored inside the buffer)
355 // such that: too_low < buffer * 10^kappa < too_high
356 // We use too_high for the digit_generation and stop as soon as possible.
357 // If we stop early we effectively round down.
358 DiyFp one = new DiyFp(1L << -w.e(), w.e());
359 // Division by one is a shift.
360 int integrals = (int)((too_high.f() >>> -one.e()) & 0xffffffffL);
361 // Modulo by one is an and.
362 long fractionals = too_high.f() & (one.f() - 1);
363 long result = biggestPowerTen(integrals, DiyFp.kSignificandSize - (-one.e()));
364 int divider = (int) ((result >>> 32) & 0xffffffffL);
365 int divider_exponent = (int) (result & 0xffffffffL);
366 int kappa = divider_exponent + 1;
367 // Loop invariant: buffer = too_high / 10^kappa (integer division)
368 // The invariant holds for the first iteration: kappa has been initialized
369 // with the divider exponent + 1. And the divider is the biggest power of ten
370 // that is smaller than integrals.
371 while (kappa > 0) {
372 int digit = integrals / divider;
373 buffer.append((char) ('0' + digit));
374 integrals %= divider;
375 kappa--;
376 // Note that kappa now equals the exponent of the divider and that the
377 // invariant thus holds again.
378 long rest =
379 ((long)integrals << -one.e()) + fractionals;
380 // Invariant: too_high = buffer * 10^kappa + DiyFp(rest, one.e())
381 // Reminder: unsafe_interval.e() == one.e()
382 if (rest < unsafe_interval.f()) {
383 // Rounding down (by not emitting the remaining digits) yields a number
384 // that lies within the unsafe interval.
385 buffer.point = buffer.end - mk + kappa;
386 return roundWeed(buffer, DiyFp.minus(too_high, w).f(),
387 unsafe_interval.f(), rest,
388 (long)divider << -one.e(), unit);
389 }
390 divider /= 10;
391 }
392
393 // The integrals have been generated. We are at the point of the decimal
394 // separator. In the following loop we simply multiply the remaining digits by
395 // 10 and divide by one. We just need to pay attention to multiply associated
396 // data (like the interval or 'unit'), too.
397 // Instead of multiplying by 10 we multiply by 5 (cheaper operation) and
398 // increase its (imaginary) exponent. At the same time we decrease the
399 // divider's (one's) exponent and shift its significand.
400 // Basically, if fractionals was a DiyFp (with fractionals.e == one.e):
401 // fractionals.f *= 10;
402 // fractionals.f >>= 1; fractionals.e++; // value remains unchanged.
403 // one.f >>= 1; one.e++; // value remains unchanged.
404 // and we have again fractionals.e == one.e which allows us to divide
405 // fractionals.f() by one.f()
406 // We simply combine the *= 10 and the >>= 1.
407 while (true) {
408 fractionals *= 5;
409 unit *= 5;
410 unsafe_interval.setF(unsafe_interval.f() * 5);
411 unsafe_interval.setE(unsafe_interval.e() + 1); // Will be optimized out.
412 one.setF(one.f() >>> 1);
413 one.setE(one.e() + 1);
414 // Integer division by one.
415 int digit = (int)((fractionals >>> -one.e()) & 0xffffffffL);
416 buffer.append((char) ('0' + digit));
417 fractionals &= one.f() - 1; // Modulo by one.
418 kappa--;
419 if (fractionals < unsafe_interval.f()) {
420 buffer.point = buffer.end - mk + kappa;
421 return roundWeed(buffer, DiyFp.minus(too_high, w).f() * unit,
422 unsafe_interval.f(), fractionals, one.f(), unit);
423 }
424 }
425 }
426
427
428 // Provides a decimal representation of v.
429 // Returns true if it succeeds, otherwise the result cannot be trusted.
430 // There will be *length digits inside the buffer (not null-terminated).
431 // If the function returns true then
432 // v == (double) (buffer * 10^decimal_exponent).
433 // The digits in the buffer are the shortest representation possible: no
434 // 0.09999999999999999 instead of 0.1. The shorter representation will even be
435 // chosen even if the longer one would be closer to v.
436 // The last digit will be closest to the actual v. That is, even if several
437 // digits might correctly yield 'v' when read again, the closest will be
438 // computed.
439 static boolean grisu3(double v, FastDtoaBuilder buffer) {
440 long bits = Double.doubleToLongBits(v);
441 DiyFp w = DoubleHelper.asNormalizedDiyFp(bits);
442 // boundary_minus and boundary_plus are the boundaries between v and its
443 // closest floating-point neighbors. Any number strictly between
444 // boundary_minus and boundary_plus will round to v when convert to a double.
445 // Grisu3 will never output representations that lie exactly on a boundary.
446 DiyFp boundary_minus = new DiyFp(), boundary_plus = new DiyFp();
447 DoubleHelper.normalizedBoundaries(bits, boundary_minus, boundary_plus);
448 assert(boundary_plus.e() == w.e());
449 DiyFp ten_mk = new DiyFp(); // Cached power of ten: 10^-k
450 int mk = CachedPowers.getCachedPower(w.e() + DiyFp.kSignificandSize,
451 minimal_target_exponent, maximal_target_exponent, ten_mk);
452 assert(minimal_target_exponent <= w.e() + ten_mk.e() +
453 DiyFp.kSignificandSize &&
454 maximal_target_exponent >= w.e() + ten_mk.e() +
455 DiyFp.kSignificandSize);
456 // Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a
457 // 64 bit significand and ten_mk is thus only precise up to 64 bits.
458
459 // The DiyFp::Times procedure rounds its result, and ten_mk is approximated
460 // too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now
461 // off by a small amount.
462 // In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w.
463 // In other words: let f = scaled_w.f() and e = scaled_w.e(), then
464 // (f-1) * 2^e < w*10^k < (f+1) * 2^e
465 DiyFp scaled_w = DiyFp.times(w, ten_mk);
466 assert(scaled_w.e() ==
467 boundary_plus.e() + ten_mk.e() + DiyFp.kSignificandSize);
468 // In theory it would be possible to avoid some recomputations by computing
469 // the difference between w and boundary_minus/plus (a power of 2) and to
470 // compute scaled_boundary_minus/plus by subtracting/adding from
471 // scaled_w. However the code becomes much less readable and the speed
472 // enhancements are not terriffic.
473 DiyFp scaled_boundary_minus = DiyFp.times(boundary_minus, ten_mk);
474 DiyFp scaled_boundary_plus = DiyFp.times(boundary_plus, ten_mk);
475
476 // DigitGen will generate the digits of scaled_w. Therefore we have
477 // v == (double) (scaled_w * 10^-mk).
478 // Set decimal_exponent == -mk and pass it to DigitGen. If scaled_w is not an
479 // integer than it will be updated. For instance if scaled_w == 1.23 then
480 // the buffer will be filled with "123" und the decimal_exponent will be
481 // decreased by 2.
482 return digitGen(scaled_boundary_minus, scaled_w, scaled_boundary_plus,
483 buffer, mk);
484 }
485
486
487 public static boolean dtoa(double v, FastDtoaBuilder buffer) {
488 assert(v > 0);
489 assert(!Double.isNaN(v));
490 assert(!Double.isInfinite(v));
491
492 return grisu3(v, buffer);
493 }
494
495 public static String numberToString(double v) {
496 FastDtoaBuilder buffer = new FastDtoaBuilder();
497 return numberToString(v, buffer) ? buffer.format() : null;
498 }
499
500 public static boolean numberToString(double v, FastDtoaBuilder buffer) {
501 buffer.reset();
502 if (v < 0) {
503 buffer.append('-');
504 v = -v;
505 }
506 return dtoa(v, buffer);
507 }
508
509 }