strtod.h
Go to the documentation of this file.
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 
15 #ifndef RAPIDJSON_STRTOD_
16 #define RAPIDJSON_STRTOD_
17 
18 #include "ieee754.h"
19 #include "biginteger.h"
20 #include "diyfp.h"
21 #include "pow10.h"
22 #include <climits>
23 #include <limits>
24 
26 namespace internal
27 {
28 inline double FastPath(double significand, int exp)
29 {
30  if (exp < -308)
31  return 0.0;
32  else if (exp >= 0)
33  return significand * internal::Pow10(exp);
34  else
35  return significand / internal::Pow10(-exp);
36 }
37 
38 inline double StrtodNormalPrecision(double d, int p)
39 {
40  if (p < -308)
41  {
42  // Prevent expSum < -308, making Pow10(p) = 0
43  d = FastPath(d, -308);
44  d = FastPath(d, p + 308);
45  }
46  else
47  d = FastPath(d, p);
48  return d;
49 }
50 
51 template <typename T>
52 inline T Min3(T a, T b, T c)
53 {
54  T m = a;
55  if (m > b)
56  m = b;
57  if (m > c)
58  m = c;
59  return m;
60 }
61 
62 inline int CheckWithinHalfULP(double b, const BigInteger& d, int dExp)
63 {
64  const Double db(b);
65  const uint64_t bInt = db.IntegerSignificand();
66  const int bExp = db.IntegerExponent();
67  const int hExp = bExp - 1;
68 
69  int dS_Exp2 = 0, dS_Exp5 = 0, bS_Exp2 = 0, bS_Exp5 = 0, hS_Exp2 = 0, hS_Exp5 = 0;
70 
71  // Adjust for decimal exponent
72  if (dExp >= 0)
73  {
74  dS_Exp2 += dExp;
75  dS_Exp5 += dExp;
76  }
77  else
78  {
79  bS_Exp2 -= dExp;
80  bS_Exp5 -= dExp;
81  hS_Exp2 -= dExp;
82  hS_Exp5 -= dExp;
83  }
84 
85  // Adjust for binary exponent
86  if (bExp >= 0)
87  bS_Exp2 += bExp;
88  else
89  {
90  dS_Exp2 -= bExp;
91  hS_Exp2 -= bExp;
92  }
93 
94  // Adjust for half ulp exponent
95  if (hExp >= 0)
96  hS_Exp2 += hExp;
97  else
98  {
99  dS_Exp2 -= hExp;
100  bS_Exp2 -= hExp;
101  }
102 
103  // Remove common power of two factor from all three scaled values
104  int common_Exp2 = Min3(dS_Exp2, bS_Exp2, hS_Exp2);
105  dS_Exp2 -= common_Exp2;
106  bS_Exp2 -= common_Exp2;
107  hS_Exp2 -= common_Exp2;
108 
109  BigInteger dS = d;
110  dS.MultiplyPow5(static_cast<unsigned>(dS_Exp5)) <<= static_cast<unsigned>(dS_Exp2);
111 
112  BigInteger bS(bInt);
113  bS.MultiplyPow5(static_cast<unsigned>(bS_Exp5)) <<= static_cast<unsigned>(bS_Exp2);
114 
115  BigInteger hS(1);
116  hS.MultiplyPow5(static_cast<unsigned>(hS_Exp5)) <<= static_cast<unsigned>(hS_Exp2);
117 
118  BigInteger delta(0);
119  dS.Difference(bS, &delta);
120 
121  return delta.Compare(hS);
122 }
123 
124 inline bool StrtodFast(double d, int p, double* result)
125 {
126  // Use fast path for string-to-double conversion if possible
127  // see http://www.exploringbinary.com/fast-path-decimal-to-floating-point-conversion/
128  if (p > 22 && p < 22 + 16)
129  {
130  // Fast Path Cases In Disguise
131  d *= internal::Pow10(p - 22);
132  p = 22;
133  }
134 
135  if (p >= -22 && p <= 22 && d <= 9007199254740991.0)
136  { // 2^53 - 1
137  *result = FastPath(d, p);
138  return true;
139  }
140  else
141  return false;
142 }
143 
144 // Compute an approximation and see if it is within 1/2 ULP
145 inline bool StrtodDiyFp(const char* decimals, int dLen, int dExp, double* result)
146 {
147  uint64_t significand = 0;
148  int i = 0; // 2^64 - 1 = 18446744073709551615, 1844674407370955161 = 0x1999999999999999
149  for (; i < dLen; i++)
150  {
151  if (significand > RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) ||
152  (significand == RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) && decimals[i] > '5'))
153  break;
154  significand = significand * 10u + static_cast<unsigned>(decimals[i] - '0');
155  }
156 
157  if (i < dLen && decimals[i] >= '5') // Rounding
158  significand++;
159 
160  int remaining = dLen - i;
161  const int kUlpShift = 3;
162  const int kUlp = 1 << kUlpShift;
163  int64_t error = (remaining == 0) ? 0 : kUlp / 2;
164 
165  DiyFp v(significand, 0);
166  v = v.Normalize();
167  error <<= -v.e;
168 
169  dExp += remaining;
170 
171  int actualExp;
172  DiyFp cachedPower = GetCachedPower10(dExp, &actualExp);
173  if (actualExp != dExp)
174  {
175  static const DiyFp kPow10[] = {
176  DiyFp(RAPIDJSON_UINT64_C2(0xa0000000, 0x00000000), -60), // 10^1
177  DiyFp(RAPIDJSON_UINT64_C2(0xc8000000, 0x00000000), -57), // 10^2
178  DiyFp(RAPIDJSON_UINT64_C2(0xfa000000, 0x00000000), -54), // 10^3
179  DiyFp(RAPIDJSON_UINT64_C2(0x9c400000, 0x00000000), -50), // 10^4
180  DiyFp(RAPIDJSON_UINT64_C2(0xc3500000, 0x00000000), -47), // 10^5
181  DiyFp(RAPIDJSON_UINT64_C2(0xf4240000, 0x00000000), -44), // 10^6
182  DiyFp(RAPIDJSON_UINT64_C2(0x98968000, 0x00000000), -40) // 10^7
183  };
184  int adjustment = dExp - actualExp;
185  RAPIDJSON_ASSERT(adjustment >= 1 && adjustment < 8);
186  v = v * kPow10[adjustment - 1];
187  if (dLen + adjustment > 19) // has more digits than decimal digits in 64-bit
188  error += kUlp / 2;
189  }
190 
191  v = v * cachedPower;
192 
193  error += kUlp + (error == 0 ? 0 : 1);
194 
195  const int oldExp = v.e;
196  v = v.Normalize();
197  error <<= oldExp - v.e;
198 
199  const int effectiveSignificandSize = Double::EffectiveSignificandSize(64 + v.e);
200  int precisionSize = 64 - effectiveSignificandSize;
201  if (precisionSize + kUlpShift >= 64)
202  {
203  int scaleExp = (precisionSize + kUlpShift) - 63;
204  v.f >>= scaleExp;
205  v.e += scaleExp;
206  error = (error >> scaleExp) + 1 + kUlp;
207  precisionSize -= scaleExp;
208  }
209 
210  DiyFp rounded(v.f >> precisionSize, v.e + precisionSize);
211  const uint64_t precisionBits = (v.f & ((uint64_t(1) << precisionSize) - 1)) * kUlp;
212  const uint64_t halfWay = (uint64_t(1) << (precisionSize - 1)) * kUlp;
213  if (precisionBits >= halfWay + static_cast<unsigned>(error))
214  {
215  rounded.f++;
216  if (rounded.f & (DiyFp::kDpHiddenBit << 1))
217  { // rounding overflows mantissa (issue #340)
218  rounded.f >>= 1;
219  rounded.e++;
220  }
221  }
222 
223  *result = rounded.ToDouble();
224 
225  return halfWay - static_cast<unsigned>(error) >= precisionBits ||
226  precisionBits >= halfWay + static_cast<unsigned>(error);
227 }
228 
229 inline double StrtodBigInteger(double approx, const char* decimals, int dLen, int dExp)
230 {
231  RAPIDJSON_ASSERT(dLen >= 0);
232  const BigInteger dInt(decimals, static_cast<unsigned>(dLen));
233  Double a(approx);
234  int cmp = CheckWithinHalfULP(a.Value(), dInt, dExp);
235  if (cmp < 0)
236  return a.Value(); // within half ULP
237  else if (cmp == 0)
238  {
239  // Round towards even
240  if (a.Significand() & 1)
241  return a.NextPositiveDouble();
242  else
243  return a.Value();
244  }
245  else // adjustment
246  return a.NextPositiveDouble();
247 }
248 
249 inline double StrtodFullPrecision(double d, int p, const char* decimals, size_t length, size_t decimalPosition, int exp)
250 {
251  RAPIDJSON_ASSERT(d >= 0.0);
252  RAPIDJSON_ASSERT(length >= 1);
253 
254  double result = 0.0;
255  if (StrtodFast(d, p, &result))
256  return result;
257 
258  RAPIDJSON_ASSERT(length <= INT_MAX);
259  int dLen = static_cast<int>(length);
260 
261  RAPIDJSON_ASSERT(length >= decimalPosition);
262  RAPIDJSON_ASSERT(length - decimalPosition <= INT_MAX);
263  int dExpAdjust = static_cast<int>(length - decimalPosition);
264 
265  RAPIDJSON_ASSERT(exp >= INT_MIN + dExpAdjust);
266  int dExp = exp - dExpAdjust;
267 
268  // Make sure length+dExp does not overflow
269  RAPIDJSON_ASSERT(dExp <= INT_MAX - dLen);
270 
271  // Trim leading zeros
272  while (dLen > 0 && *decimals == '0')
273  {
274  dLen--;
275  decimals++;
276  }
277 
278  // Trim trailing zeros
279  while (dLen > 0 && decimals[dLen - 1] == '0')
280  {
281  dLen--;
282  dExp++;
283  }
284 
285  if (dLen == 0)
286  { // Buffer only contains zeros.
287  return 0.0;
288  }
289 
290  // Trim right-most digits
291  const int kMaxDecimalDigit = 767 + 1;
292  if (dLen > kMaxDecimalDigit)
293  {
294  dExp += dLen - kMaxDecimalDigit;
295  dLen = kMaxDecimalDigit;
296  }
297 
298  // If too small, underflow to zero.
299  // Any x <= 10^-324 is interpreted as zero.
300  if (dLen + dExp <= -324)
301  return 0.0;
302 
303  // If too large, overflow to infinity.
304  // Any x >= 10^309 is interpreted as +infinity.
305  if (dLen + dExp > 309)
306  return std::numeric_limits<double>::infinity();
307 
308  if (StrtodDiyFp(decimals, dLen, dExp, &result))
309  return result;
310 
311  // Use approximation from StrtodDiyFp and make adjustment with BigInteger comparison
312  return StrtodBigInteger(result, decimals, dLen, dExp);
313 }
314 
315 } // namespace internal
317 
318 #endif // RAPIDJSON_STRTOD_
double StrtodFullPrecision(double d, int p, const char *decimals, size_t length, size_t decimalPosition, int exp)
Definition: strtod.h:249
#define RAPIDJSON_ASSERT(x)
Assertion.
Definition: rapidjson.h:416
#define RAPIDJSON_UINT64_C2(high32, low32)
Construct a 64-bit literal by a pair of 32-bit integer.
Definition: rapidjson.h:294
#define RAPIDJSON_NAMESPACE_END
provide custom rapidjson namespace (closing expression)
Definition: rapidjson.h:126
uint64_t Significand() const
Definition: ieee754.h:55
DiyFp GetCachedPower10(int exp, int *outExp)
Definition: diyfp.h:269
int Compare(const BigInteger &rhs) const
Definition: biginteger.h:248
static int EffectiveSignificandSize(int order)
Definition: ieee754.h:98
#define RAPIDJSON_NAMESPACE_BEGIN
provide custom rapidjson namespace (opening expression)
Definition: rapidjson.h:121
DiyFp Normalize() const
Definition: diyfp.h:113
double Value() const
Definition: ieee754.h:36
double NextPositiveDouble() const
Definition: ieee754.h:45
bool StrtodFast(double d, int p, double *result)
Definition: strtod.h:124
double StrtodNormalPrecision(double d, int p)
Definition: strtod.h:38
int CheckWithinHalfULP(double b, const BigInteger &d, int dExp)
Definition: strtod.h:62
double ToDouble() const
Definition: diyfp.h:157
bool StrtodDiyFp(const char *decimals, int dLen, int dExp, double *result)
Definition: strtod.h:145
unsigned __int64 uint64_t
Definition: stdint.h:136
uint64_t f
Definition: diyfp.h:191
uint64_t IntegerSignificand() const
Definition: ieee754.h:85
const GenericPointer< typename T::ValueType > T2 T::AllocatorType & a
Definition: pointer.h:1422
double Pow10(int n)
Computes integer powers of 10 in double (10.0^n).
Definition: pow10.h:28
int IntegerExponent() const
Definition: ieee754.h:89
signed __int64 int64_t
Definition: stdint.h:135
double StrtodBigInteger(double approx, const char *decimals, int dLen, int dExp)
Definition: strtod.h:229
T Min3(T a, T b, T c)
Definition: strtod.h:52
BigInteger & MultiplyPow5(unsigned exp)
Definition: biginteger.h:187
static const uint64_t kDpHiddenBit
Definition: diyfp.h:189
double FastPath(double significand, int exp)
Definition: strtod.h:28
bool Difference(const BigInteger &rhs, BigInteger *out) const
Definition: biginteger.h:214


xbot_talker
Author(s): wangxiaoyun
autogenerated on Sat Oct 10 2020 03:27:54