strtod.h 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. // Tencent is pleased to support the open source community by making RapidJSON available.
  2. //
  3. // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
  4. //
  5. // Licensed under the MIT License (the "License"); you may not use this file except
  6. // in compliance with the License. You may obtain a copy of the License at
  7. //
  8. // http://opensource.org/licenses/MIT
  9. //
  10. // Unless required by applicable law or agreed to in writing, software distributed
  11. // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  12. // CONDITIONS OF ANY KIND, either express or implied. See the License for the
  13. // specific language governing permissions and limitations under the License.
  14. #ifndef RAPIDJSON_STRTOD_
  15. #define RAPIDJSON_STRTOD_
  16. #include "ieee754.h"
  17. #include "biginteger.h"
  18. #include "diyfp.h"
  19. #include "pow10.h"
  20. RAPIDJSON_NAMESPACE_BEGIN
  21. namespace internal {
  22. inline double FastPath(double significand, int exp) {
  23. if (exp < -308)
  24. return 0.0;
  25. else if (exp >= 0)
  26. return significand * internal::Pow10(exp);
  27. else
  28. return significand / internal::Pow10(-exp);
  29. }
  30. inline double StrtodNormalPrecision(double d, int p) {
  31. if (p < -308) {
  32. // Prevent expSum < -308, making Pow10(p) = 0
  33. d = FastPath(d, -308);
  34. d = FastPath(d, p + 308);
  35. }
  36. else
  37. d = FastPath(d, p);
  38. return d;
  39. }
  40. template <typename T>
  41. inline T Min3(T a, T b, T c) {
  42. T m = a;
  43. if (m > b) m = b;
  44. if (m > c) m = c;
  45. return m;
  46. }
  47. inline int CheckWithinHalfULP(double b, const BigInteger& d, int dExp) {
  48. const Double db(b);
  49. const uint64_t bInt = db.IntegerSignificand();
  50. const int bExp = db.IntegerExponent();
  51. const int hExp = bExp - 1;
  52. int dS_Exp2 = 0, dS_Exp5 = 0, bS_Exp2 = 0, bS_Exp5 = 0, hS_Exp2 = 0, hS_Exp5 = 0;
  53. // Adjust for decimal exponent
  54. if (dExp >= 0) {
  55. dS_Exp2 += dExp;
  56. dS_Exp5 += dExp;
  57. }
  58. else {
  59. bS_Exp2 -= dExp;
  60. bS_Exp5 -= dExp;
  61. hS_Exp2 -= dExp;
  62. hS_Exp5 -= dExp;
  63. }
  64. // Adjust for binary exponent
  65. if (bExp >= 0)
  66. bS_Exp2 += bExp;
  67. else {
  68. dS_Exp2 -= bExp;
  69. hS_Exp2 -= bExp;
  70. }
  71. // Adjust for half ulp exponent
  72. if (hExp >= 0)
  73. hS_Exp2 += hExp;
  74. else {
  75. dS_Exp2 -= hExp;
  76. bS_Exp2 -= hExp;
  77. }
  78. // Remove common power of two factor from all three scaled values
  79. int common_Exp2 = Min3(dS_Exp2, bS_Exp2, hS_Exp2);
  80. dS_Exp2 -= common_Exp2;
  81. bS_Exp2 -= common_Exp2;
  82. hS_Exp2 -= common_Exp2;
  83. BigInteger dS = d;
  84. dS.MultiplyPow5(static_cast<unsigned>(dS_Exp5)) <<= static_cast<unsigned>(dS_Exp2);
  85. BigInteger bS(bInt);
  86. bS.MultiplyPow5(static_cast<unsigned>(bS_Exp5)) <<= static_cast<unsigned>(bS_Exp2);
  87. BigInteger hS(1);
  88. hS.MultiplyPow5(static_cast<unsigned>(hS_Exp5)) <<= static_cast<unsigned>(hS_Exp2);
  89. BigInteger delta(0);
  90. dS.Difference(bS, &delta);
  91. return delta.Compare(hS);
  92. }
  93. inline bool StrtodFast(double d, int p, double* result) {
  94. // Use fast path for string-to-double conversion if possible
  95. // see http://www.exploringbinary.com/fast-path-decimal-to-floating-point-conversion/
  96. if (p > 22 && p < 22 + 16) {
  97. // Fast Path Cases In Disguise
  98. d *= internal::Pow10(p - 22);
  99. p = 22;
  100. }
  101. if (p >= -22 && p <= 22 && d <= 9007199254740991.0) { // 2^53 - 1
  102. *result = FastPath(d, p);
  103. return true;
  104. }
  105. else
  106. return false;
  107. }
  108. // Compute an approximation and see if it is within 1/2 ULP
  109. inline bool StrtodDiyFp(const char* decimals, size_t length, size_t decimalPosition, int exp, double* result) {
  110. uint64_t significand = 0;
  111. size_t i = 0; // 2^64 - 1 = 18446744073709551615, 1844674407370955161 = 0x1999999999999999
  112. for (; i < length; i++) {
  113. if (significand > RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) ||
  114. (significand == RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) && decimals[i] > '5'))
  115. break;
  116. significand = significand * 10u + static_cast<unsigned>(decimals[i] - '0');
  117. }
  118. if (i < length && decimals[i] >= '5') // Rounding
  119. significand++;
  120. size_t remaining = length - i;
  121. const int kUlpShift = 3;
  122. const int kUlp = 1 << kUlpShift;
  123. int64_t error = (remaining == 0) ? 0 : kUlp / 2;
  124. DiyFp v(significand, 0);
  125. v = v.Normalize();
  126. error <<= -v.e;
  127. const int dExp = static_cast<int>(decimalPosition) - static_cast<int>(i) + exp;
  128. int actualExp;
  129. DiyFp cachedPower = GetCachedPower10(dExp, &actualExp);
  130. if (actualExp != dExp) {
  131. static const DiyFp kPow10[] = {
  132. DiyFp(RAPIDJSON_UINT64_C2(0xa0000000, 00000000), -60), // 10^1
  133. DiyFp(RAPIDJSON_UINT64_C2(0xc8000000, 00000000), -57), // 10^2
  134. DiyFp(RAPIDJSON_UINT64_C2(0xfa000000, 00000000), -54), // 10^3
  135. DiyFp(RAPIDJSON_UINT64_C2(0x9c400000, 00000000), -50), // 10^4
  136. DiyFp(RAPIDJSON_UINT64_C2(0xc3500000, 00000000), -47), // 10^5
  137. DiyFp(RAPIDJSON_UINT64_C2(0xf4240000, 00000000), -44), // 10^6
  138. DiyFp(RAPIDJSON_UINT64_C2(0x98968000, 00000000), -40) // 10^7
  139. };
  140. int adjustment = dExp - actualExp - 1;
  141. RAPIDJSON_ASSERT(adjustment >= 0 && adjustment < 7);
  142. v = v * kPow10[adjustment];
  143. if (length + static_cast<unsigned>(adjustment)> 19u) // has more digits than decimal digits in 64-bit
  144. error += kUlp / 2;
  145. }
  146. v = v * cachedPower;
  147. error += kUlp + (error == 0 ? 0 : 1);
  148. const int oldExp = v.e;
  149. v = v.Normalize();
  150. error <<= oldExp - v.e;
  151. const int effectiveSignificandSize = Double::EffectiveSignificandSize(64 + v.e);
  152. int precisionSize = 64 - effectiveSignificandSize;
  153. if (precisionSize + kUlpShift >= 64) {
  154. int scaleExp = (precisionSize + kUlpShift) - 63;
  155. v.f >>= scaleExp;
  156. v.e += scaleExp;
  157. error = (error >> scaleExp) + 1 + kUlp;
  158. precisionSize -= scaleExp;
  159. }
  160. DiyFp rounded(v.f >> precisionSize, v.e + precisionSize);
  161. const uint64_t precisionBits = (v.f & ((uint64_t(1) << precisionSize) - 1)) * kUlp;
  162. const uint64_t halfWay = (uint64_t(1) << (precisionSize - 1)) * kUlp;
  163. if (precisionBits >= halfWay + static_cast<unsigned>(error)) {
  164. rounded.f++;
  165. if (rounded.f & (DiyFp::kDpHiddenBit << 1)) { // rounding overflows mantissa (issue #340)
  166. rounded.f >>= 1;
  167. rounded.e++;
  168. }
  169. }
  170. *result = rounded.ToDouble();
  171. return halfWay - static_cast<unsigned>(error) >= precisionBits || precisionBits >= halfWay + static_cast<unsigned>(error);
  172. }
  173. inline double StrtodBigInteger(double approx, const char* decimals, size_t length, size_t decimalPosition, int exp) {
  174. const BigInteger dInt(decimals, length);
  175. const int dExp = static_cast<int>(decimalPosition) - static_cast<int>(length) + exp;
  176. Double a(approx);
  177. int cmp = CheckWithinHalfULP(a.Value(), dInt, dExp);
  178. if (cmp < 0)
  179. return a.Value(); // within half ULP
  180. else if (cmp == 0) {
  181. // Round towards even
  182. if (a.Significand() & 1)
  183. return a.NextPositiveDouble();
  184. else
  185. return a.Value();
  186. }
  187. else // adjustment
  188. return a.NextPositiveDouble();
  189. }
  190. inline double StrtodFullPrecision(double d, int p, const char* decimals, size_t length, size_t decimalPosition, int exp) {
  191. RAPIDJSON_ASSERT(d >= 0.0);
  192. RAPIDJSON_ASSERT(length >= 1);
  193. double result;
  194. if (StrtodFast(d, p, &result))
  195. return result;
  196. // Trim leading zeros
  197. while (*decimals == '0' && length > 1) {
  198. length--;
  199. decimals++;
  200. decimalPosition--;
  201. }
  202. // Trim trailing zeros
  203. while (decimals[length - 1] == '0' && length > 1) {
  204. length--;
  205. decimalPosition--;
  206. exp++;
  207. }
  208. // Trim right-most digits
  209. const int kMaxDecimalDigit = 780;
  210. if (static_cast<int>(length) > kMaxDecimalDigit) {
  211. int delta = (static_cast<int>(length) - kMaxDecimalDigit);
  212. exp += delta;
  213. decimalPosition -= static_cast<unsigned>(delta);
  214. length = kMaxDecimalDigit;
  215. }
  216. // If too small, underflow to zero
  217. if (int(length) + exp < -324)
  218. return 0.0;
  219. if (StrtodDiyFp(decimals, length, decimalPosition, exp, &result))
  220. return result;
  221. // Use approximation from StrtodDiyFp and make adjustment with BigInteger comparison
  222. return StrtodBigInteger(result, decimals, length, decimalPosition, exp);
  223. }
  224. } // namespace internal
  225. RAPIDJSON_NAMESPACE_END
  226. #endif // RAPIDJSON_STRTOD_