您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

555 行
20 KiB

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