OLD | NEW |
| (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 "strtod.h" | |
29 | |
30 #include "bignum.h" | |
31 #include "cached-powers.h" | |
32 #include "double.h" | |
33 #include <stdarg.h> | |
34 #include <limits.h> | |
35 | |
36 namespace WTF { | |
37 | |
38 namespace double_conversion { | |
39 | |
40 // 2^53 = 9007199254740992. | |
41 // Any integer with at most 15 decimal digits will hence fit into a double | |
42 // (which has a 53bit significand) without loss of precision. | |
43 static const int kMaxExactDoubleIntegerDecimalDigits = 15; | |
44 // 2^64 = 18446744073709551616 > 10^19 | |
45 static const int kMaxUint64DecimalDigits = 19; | |
46 | |
47 // Max double: 1.7976931348623157 x 10^308 | |
48 // Min non-zero double: 4.9406564584124654 x 10^-324 | |
49 // Any x >= 10^309 is interpreted as +infinity. | |
50 // Any x <= 10^-324 is interpreted as 0. | |
51 // Note that 2.5e-324 (despite being smaller than the min double) will be re
ad | |
52 // as non-zero (equal to the min non-zero double). | |
53 static const int kMaxDecimalPower = 309; | |
54 static const int kMinDecimalPower = -324; | |
55 | |
56 // 2^64 = 18446744073709551616 | |
57 static const uint64_t kMaxUint64 = UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF); | |
58 | |
59 | |
60 static const double exact_powers_of_ten[] = { | |
61 1.0, // 10^0 | |
62 10.0, | |
63 100.0, | |
64 1000.0, | |
65 10000.0, | |
66 100000.0, | |
67 1000000.0, | |
68 10000000.0, | |
69 100000000.0, | |
70 1000000000.0, | |
71 10000000000.0, // 10^10 | |
72 100000000000.0, | |
73 1000000000000.0, | |
74 10000000000000.0, | |
75 100000000000000.0, | |
76 1000000000000000.0, | |
77 10000000000000000.0, | |
78 100000000000000000.0, | |
79 1000000000000000000.0, | |
80 10000000000000000000.0, | |
81 100000000000000000000.0, // 10^20 | |
82 1000000000000000000000.0, | |
83 // 10^22 = 0x21e19e0c9bab2400000 = 0x878678326eac9 * 2^22 | |
84 10000000000000000000000.0 | |
85 }; | |
86 static const int kExactPowersOfTenSize = ARRAY_SIZE(exact_powers_of_ten); | |
87 | |
88 // Maximum number of significant digits in the decimal representation. | |
89 // In fact the value is 772 (see conversions.cc), but to give us some margin | |
90 // we round up to 780. | |
91 static const int kMaxSignificantDecimalDigits = 780; | |
92 | |
93 static Vector<const char> TrimLeadingZeros(Vector<const char> buffer) { | |
94 for (int i = 0; i < buffer.length(); i++) { | |
95 if (buffer[i] != '0') { | |
96 return buffer.SubVector(i, buffer.length()); | |
97 } | |
98 } | |
99 return Vector<const char>(buffer.start(), 0); | |
100 } | |
101 | |
102 | |
103 static Vector<const char> TrimTrailingZeros(Vector<const char> buffer) { | |
104 for (int i = buffer.length() - 1; i >= 0; --i) { | |
105 if (buffer[i] != '0') { | |
106 return buffer.SubVector(0, i + 1); | |
107 } | |
108 } | |
109 return Vector<const char>(buffer.start(), 0); | |
110 } | |
111 | |
112 | |
113 static void TrimToMaxSignificantDigits(Vector<const char> buffer, | |
114 int exponent, | |
115 char* significant_buffer, | |
116 int* significant_exponent) { | |
117 for (int i = 0; i < kMaxSignificantDecimalDigits - 1; ++i) { | |
118 significant_buffer[i] = buffer[i]; | |
119 } | |
120 // The input buffer has been trimmed. Therefore the last digit must be | |
121 // different from '0'. | |
122 ASSERT(buffer[buffer.length() - 1] != '0'); | |
123 // Set the last digit to be non-zero. This is sufficient to guarantee | |
124 // correct rounding. | |
125 significant_buffer[kMaxSignificantDecimalDigits - 1] = '1'; | |
126 *significant_exponent = | |
127 exponent + (buffer.length() - kMaxSignificantDecimalDigits); | |
128 } | |
129 | |
130 // Reads digits from the buffer and converts them to a uint64. | |
131 // Reads in as many digits as fit into a uint64. | |
132 // When the string starts with "1844674407370955161" no further digit is rea
d. | |
133 // Since 2^64 = 18446744073709551616 it would still be possible read another | |
134 // digit if it was less or equal than 6, but this would complicate the code. | |
135 static uint64_t ReadUint64(Vector<const char> buffer, | |
136 int* number_of_read_digits) { | |
137 uint64_t result = 0; | |
138 int i = 0; | |
139 while (i < buffer.length() && result <= (kMaxUint64 / 10 - 1)) { | |
140 int digit = buffer[i++] - '0'; | |
141 ASSERT(0 <= digit && digit <= 9); | |
142 result = 10 * result + digit; | |
143 } | |
144 *number_of_read_digits = i; | |
145 return result; | |
146 } | |
147 | |
148 | |
149 // Reads a DiyFp from the buffer. | |
150 // The returned DiyFp is not necessarily normalized. | |
151 // If remaining_decimals is zero then the returned DiyFp is accurate. | |
152 // Otherwise it has been rounded and has error of at most 1/2 ulp. | |
153 static void ReadDiyFp(Vector<const char> buffer, | |
154 DiyFp* result, | |
155 int* remaining_decimals) { | |
156 int read_digits; | |
157 uint64_t significand = ReadUint64(buffer, &read_digits); | |
158 if (buffer.length() == read_digits) { | |
159 *result = DiyFp(significand, 0); | |
160 *remaining_decimals = 0; | |
161 } else { | |
162 // Round the significand. | |
163 if (buffer[read_digits] >= '5') { | |
164 significand++; | |
165 } | |
166 // Compute the binary exponent. | |
167 int exponent = 0; | |
168 *result = DiyFp(significand, exponent); | |
169 *remaining_decimals = buffer.length() - read_digits; | |
170 } | |
171 } | |
172 | |
173 | |
174 static bool DoubleStrtod(Vector<const char> trimmed, | |
175 int exponent, | |
176 double* result) { | |
177 #if !defined(DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS) | |
178 // On x86 the floating-point stack can be 64 or 80 bits wide. If it is | |
179 // 80 bits wide (as is the case on Linux) then double-rounding occurs an
d the | |
180 // result is not accurate. | |
181 // We know that Windows32 uses 64 bits and is therefore accurate. | |
182 // Note that the ARM simulator is compiled for 32bits. It therefore exhi
bits | |
183 // the same problem. | |
184 return false; | |
185 #endif | |
186 if (trimmed.length() <= kMaxExactDoubleIntegerDecimalDigits) { | |
187 int read_digits; | |
188 // The trimmed input fits into a double. | |
189 // If the 10^exponent (resp. 10^-exponent) fits into a double too th
en we | |
190 // can compute the result-double simply by multiplying (resp. dividi
ng) the | |
191 // two numbers. | |
192 // This is possible because IEEE guarantees that floating-point oper
ations | |
193 // return the best possible approximation. | |
194 if (exponent < 0 && -exponent < kExactPowersOfTenSize) { | |
195 // 10^-exponent fits into a double. | |
196 *result = static_cast<double>(ReadUint64(trimmed, &read_digits))
; | |
197 ASSERT(read_digits == trimmed.length()); | |
198 *result /= exact_powers_of_ten[-exponent]; | |
199 return true; | |
200 } | |
201 if (0 <= exponent && exponent < kExactPowersOfTenSize) { | |
202 // 10^exponent fits into a double. | |
203 *result = static_cast<double>(ReadUint64(trimmed, &read_digits))
; | |
204 ASSERT(read_digits == trimmed.length()); | |
205 *result *= exact_powers_of_ten[exponent]; | |
206 return true; | |
207 } | |
208 int remaining_digits = | |
209 kMaxExactDoubleIntegerDecimalDigits - trimmed.length(); | |
210 if ((0 <= exponent) && | |
211 (exponent - remaining_digits < kExactPowersOfTenSize)) { | |
212 // The trimmed string was short and we can multiply it with | |
213 // 10^remaining_digits. As a result the remaining exponent now f
its | |
214 // into a double too. | |
215 *result = static_cast<double>(ReadUint64(trimmed, &read_digits))
; | |
216 ASSERT(read_digits == trimmed.length()); | |
217 *result *= exact_powers_of_ten[remaining_digits]; | |
218 *result *= exact_powers_of_ten[exponent - remaining_digits]; | |
219 return true; | |
220 } | |
221 } | |
222 return false; | |
223 } | |
224 | |
225 | |
226 // Returns 10^exponent as an exact DiyFp. | |
227 // The given exponent must be in the range [1; kDecimalExponentDistance[. | |
228 static DiyFp AdjustmentPowerOfTen(int exponent) { | |
229 ASSERT(0 < exponent); | |
230 ASSERT(exponent < PowersOfTenCache::kDecimalExponentDistance); | |
231 // Simply hardcode the remaining powers for the given decimal exponent | |
232 // distance. | |
233 ASSERT(PowersOfTenCache::kDecimalExponentDistance == 8); | |
234 switch (exponent) { | |
235 case 1: return DiyFp(UINT64_2PART_C(0xa0000000, 00000000), -60); | |
236 case 2: return DiyFp(UINT64_2PART_C(0xc8000000, 00000000), -57); | |
237 case 3: return DiyFp(UINT64_2PART_C(0xfa000000, 00000000), -54); | |
238 case 4: return DiyFp(UINT64_2PART_C(0x9c400000, 00000000), -50); | |
239 case 5: return DiyFp(UINT64_2PART_C(0xc3500000, 00000000), -47); | |
240 case 6: return DiyFp(UINT64_2PART_C(0xf4240000, 00000000), -44); | |
241 case 7: return DiyFp(UINT64_2PART_C(0x98968000, 00000000), -40); | |
242 default: | |
243 UNREACHABLE(); | |
244 return DiyFp(0, 0); | |
245 } | |
246 } | |
247 | |
248 | |
249 // If the function returns true then the result is the correct double. | |
250 // Otherwise it is either the correct double or the double that is just belo
w | |
251 // the correct double. | |
252 static bool DiyFpStrtod(Vector<const char> buffer, | |
253 int exponent, | |
254 double* result) { | |
255 DiyFp input; | |
256 int remaining_decimals; | |
257 ReadDiyFp(buffer, &input, &remaining_decimals); | |
258 // Since we may have dropped some digits the input is not accurate. | |
259 // If remaining_decimals is different than 0 than the error is at most | |
260 // .5 ulp (unit in the last place). | |
261 // We don't want to deal with fractions and therefore keep a common | |
262 // denominator. | |
263 const int kDenominatorLog = 3; | |
264 const int kDenominator = 1 << kDenominatorLog; | |
265 // Move the remaining decimals into the exponent. | |
266 exponent += remaining_decimals; | |
267 int64_t error = (remaining_decimals == 0 ? 0 : kDenominator / 2); | |
268 | |
269 int old_e = input.e(); | |
270 input.Normalize(); | |
271 error <<= old_e - input.e(); | |
272 | |
273 ASSERT(exponent <= PowersOfTenCache::kMaxDecimalExponent); | |
274 if (exponent < PowersOfTenCache::kMinDecimalExponent) { | |
275 *result = 0.0; | |
276 return true; | |
277 } | |
278 DiyFp cached_power; | |
279 int cached_decimal_exponent; | |
280 PowersOfTenCache::GetCachedPowerForDecimalExponent(exponent, | |
281 &cached_power, | |
282 &cached_decimal_expon
ent); | |
283 | |
284 if (cached_decimal_exponent != exponent) { | |
285 int adjustment_exponent = exponent - cached_decimal_exponent; | |
286 DiyFp adjustment_power = AdjustmentPowerOfTen(adjustment_exponent); | |
287 input.Multiply(adjustment_power); | |
288 if (kMaxUint64DecimalDigits - buffer.length() >= adjustment_exponent
) { | |
289 // The product of input with the adjustment power fits into a 64
bit | |
290 // integer. | |
291 ASSERT(DiyFp::kSignificandSize == 64); | |
292 } else { | |
293 // The adjustment power is exact. There is hence only an error o
f 0.5. | |
294 error += kDenominator / 2; | |
295 } | |
296 } | |
297 | |
298 input.Multiply(cached_power); | |
299 // The error introduced by a multiplication of a*b equals | |
300 // error_a + error_b + error_a*error_b/2^64 + 0.5 | |
301 // Substituting a with 'input' and b with 'cached_power' we have | |
302 // error_b = 0.5 (all cached powers have an error of less than 0.5 ul
p), | |
303 // error_ab = 0 or 1 / kDenominator > error_a*error_b/ 2^64 | |
304 int error_b = kDenominator / 2; | |
305 int error_ab = (error == 0 ? 0 : 1); // We round up to 1. | |
306 int fixed_error = kDenominator / 2; | |
307 error += error_b + error_ab + fixed_error; | |
308 | |
309 old_e = input.e(); | |
310 input.Normalize(); | |
311 error <<= old_e - input.e(); | |
312 | |
313 // See if the double's significand changes if we add/subtract the error. | |
314 int order_of_magnitude = DiyFp::kSignificandSize + input.e(); | |
315 int effective_significand_size = | |
316 Double::SignificandSizeForOrderOfMagnitude(order_of_magnitude); | |
317 int precision_digits_count = | |
318 DiyFp::kSignificandSize - effective_significand_size; | |
319 if (precision_digits_count + kDenominatorLog >= DiyFp::kSignificandSize)
{ | |
320 // This can only happen for very small denormals. In this case the | |
321 // half-way multiplied by the denominator exceeds the range of an ui
nt64. | |
322 // Simply shift everything to the right. | |
323 int shift_amount = (precision_digits_count + kDenominatorLog) - | |
324 DiyFp::kSignificandSize + 1; | |
325 input.set_f(input.f() >> shift_amount); | |
326 input.set_e(input.e() + shift_amount); | |
327 // We add 1 for the lost precision of error, and kDenominator for | |
328 // the lost precision of input.f(). | |
329 error = (error >> shift_amount) + 1 + kDenominator; | |
330 precision_digits_count -= shift_amount; | |
331 } | |
332 // We use uint64_ts now. This only works if the DiyFp uses uint64_ts too
. | |
333 ASSERT(DiyFp::kSignificandSize == 64); | |
334 ASSERT(precision_digits_count < 64); | |
335 uint64_t one64 = 1; | |
336 uint64_t precision_bits_mask = (one64 << precision_digits_count) - 1; | |
337 uint64_t precision_bits = input.f() & precision_bits_mask; | |
338 uint64_t half_way = one64 << (precision_digits_count - 1); | |
339 precision_bits *= kDenominator; | |
340 half_way *= kDenominator; | |
341 DiyFp rounded_input(input.f() >> precision_digits_count, | |
342 input.e() + precision_digits_count); | |
343 if (precision_bits >= half_way + error) { | |
344 rounded_input.set_f(rounded_input.f() + 1); | |
345 } | |
346 // If the last_bits are too close to the half-way case than we are too | |
347 // inaccurate and round down. In this case we return false so that we ca
n | |
348 // fall back to a more precise algorithm. | |
349 | |
350 *result = Double(rounded_input).value(); | |
351 if (half_way - error < precision_bits && precision_bits < half_way + err
or) { | |
352 // Too imprecise. The caller will have to fall back to a slower vers
ion. | |
353 // However the returned number is guaranteed to be either the correc
t | |
354 // double, or the next-lower double. | |
355 return false; | |
356 } else { | |
357 return true; | |
358 } | |
359 } | |
360 | |
361 | |
362 // Returns the correct double for the buffer*10^exponent. | |
363 // The variable guess should be a close guess that is either the correct dou
ble | |
364 // or its lower neighbor (the nearest double less than the correct one). | |
365 // Preconditions: | |
366 // buffer.length() + exponent <= kMaxDecimalPower + 1 | |
367 // buffer.length() + exponent > kMinDecimalPower | |
368 // buffer.length() <= kMaxDecimalSignificantDigits | |
369 static double BignumStrtod(Vector<const char> buffer, | |
370 int exponent, | |
371 double guess) { | |
372 if (guess == Double::Infinity()) { | |
373 return guess; | |
374 } | |
375 | |
376 DiyFp upper_boundary = Double(guess).UpperBoundary(); | |
377 | |
378 ASSERT(buffer.length() + exponent <= kMaxDecimalPower + 1); | |
379 ASSERT(buffer.length() + exponent > kMinDecimalPower); | |
380 ASSERT(buffer.length() <= kMaxSignificantDecimalDigits); | |
381 // Make sure that the Bignum will be able to hold all our numbers. | |
382 // Our Bignum implementation has a separate field for exponents. Shifts
will | |
383 // consume at most one bigit (< 64 bits). | |
384 // ln(10) == 3.3219... | |
385 ASSERT(((kMaxDecimalPower + 1) * 333 / 100) < Bignum::kMaxSignificantBit
s); | |
386 Bignum input; | |
387 Bignum boundary; | |
388 input.AssignDecimalString(buffer); | |
389 boundary.AssignUInt64(upper_boundary.f()); | |
390 if (exponent >= 0) { | |
391 input.MultiplyByPowerOfTen(exponent); | |
392 } else { | |
393 boundary.MultiplyByPowerOfTen(-exponent); | |
394 } | |
395 if (upper_boundary.e() > 0) { | |
396 boundary.ShiftLeft(upper_boundary.e()); | |
397 } else { | |
398 input.ShiftLeft(-upper_boundary.e()); | |
399 } | |
400 int comparison = Bignum::Compare(input, boundary); | |
401 if (comparison < 0) { | |
402 return guess; | |
403 } else if (comparison > 0) { | |
404 return Double(guess).NextDouble(); | |
405 } else if ((Double(guess).Significand() & 1) == 0) { | |
406 // Round towards even. | |
407 return guess; | |
408 } else { | |
409 return Double(guess).NextDouble(); | |
410 } | |
411 } | |
412 | |
413 | |
414 double Strtod(Vector<const char> buffer, int exponent) { | |
415 Vector<const char> left_trimmed = TrimLeadingZeros(buffer); | |
416 Vector<const char> trimmed = TrimTrailingZeros(left_trimmed); | |
417 exponent += left_trimmed.length() - trimmed.length(); | |
418 if (trimmed.length() == 0) return 0.0; | |
419 if (trimmed.length() > kMaxSignificantDecimalDigits) { | |
420 char significant_buffer[kMaxSignificantDecimalDigits]; | |
421 int significant_exponent; | |
422 TrimToMaxSignificantDigits(trimmed, exponent, | |
423 significant_buffer, &significant_exponent
); | |
424 return Strtod(Vector<const char>(significant_buffer, | |
425 kMaxSignificantDecimalDigits), | |
426 significant_exponent); | |
427 } | |
428 if (exponent + trimmed.length() - 1 >= kMaxDecimalPower) { | |
429 return Double::Infinity(); | |
430 } | |
431 if (exponent + trimmed.length() <= kMinDecimalPower) { | |
432 return 0.0; | |
433 } | |
434 | |
435 double guess; | |
436 if (DoubleStrtod(trimmed, exponent, &guess) || | |
437 DiyFpStrtod(trimmed, exponent, &guess)) { | |
438 return guess; | |
439 } | |
440 return BignumStrtod(trimmed, exponent, guess); | |
441 } | |
442 | |
443 } // namespace double_conversion | |
444 | |
445 } // namespace WTF | |
OLD | NEW |