Debian Codegraph @

generic/tclStrToD.c

raw
1 /*
2 * tclStrToD.c --
3 *
4 * This file contains a collection of procedures for managing conversions
5 * to/from floating-point in Tcl. They include TclParseNumber, which
6 * parses numbers from strings; TclDoubleDigits, which formats numbers
7 * into strings of digits, and procedures for interconversion among
8 * 'double' and 'mp_int' types.
9 *
10 * Copyright (c) 2005 Kevin B. Kenny. All rights reserved.
11 *
12 * See the file "license.terms" for information on usage and redistribution of
13 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
14 */
15
16 #include "tclInt.h"
17 #include "tommath.h"
18 #include <float.h>
19 #include <math.h>
20
21 #ifdef _WIN32
22 #define copysign _copysign
23 #endif
24
25 /*
26 * Define KILL_OCTAL to suppress interpretation of numbers with leading zero
27 * as octal. (Ceterum censeo: numeros octonarios delendos esse.)
28 */
29
30 #undef KILL_OCTAL
31
32 /*
33 * This code supports (at least hypothetically), IBM, Cray, VAX and IEEE-754
34 * floating point; of these, only IEEE-754 can represent NaN. IEEE-754 can be
35 * uniquely determined by radix and by the widths of significand and exponent.
36 */
37
38 #if (FLT_RADIX == 2) && (DBL_MANT_DIG == 53) && (DBL_MAX_EXP == 1024)
39 # define IEEE_FLOATING_POINT
40 #endif
41
42 /*
43 * Rounding controls. (Thanks a lot, Intel!)
44 */
45
46 #ifdef __i386
47 /*
48 * gcc on x86 needs access to rounding controls, because of a questionable
49 * feature where it retains intermediate results as IEEE 'long double' values
50 * somewhat unpredictably. It is tempting to include fpu_control.h, but that
51 * file exists only on Linux; it is missing on Cygwin and MinGW. Most gcc-isms
52 * and ix86-isms are factored out here.
53 */
54 # if defined(__GNUC__)
55 typedef unsigned int fpu_control_t __attribute__ ((__mode__ (__HI__)));
56
57 # define _FPU_GETCW(cw) __asm__ __volatile__ ("fnstcw %0" : "=m" (*&cw))
58 # define _FPU_SETCW(cw) __asm__ __volatile__ ("fldcw %0" : : "m" (*&cw))
59 # define FPU_IEEE_ROUNDING 0x027F
60 # define ADJUST_FPU_CONTROL_WORD
61 # define TCL_IEEE_DOUBLE_ROUNDING_DECL \
62 fpu_control_t roundTo53Bits = FPU_IEEE_ROUNDING; \
63 fpu_control_t oldRoundingMode;
64 # define TCL_IEEE_DOUBLE_ROUNDING \
65 _FPU_GETCW(oldRoundingMode); \
66 _FPU_SETCW(roundTo53Bits)
67 # define TCL_DEFAULT_DOUBLE_ROUNDING \
68 _FPU_SETCW(oldRoundingMode)
69
70 /*
71 * Sun ProC needs sunmath for rounding control on x86 like gcc above.
72 */
73 # elif defined(__sun)
74 # include <sunmath.h>
75 # define TCL_IEEE_DOUBLE_ROUNDING_DECL
76 # define TCL_IEEE_DOUBLE_ROUNDING \
77 ieee_flags("set","precision","double",NULL)
78 # define TCL_DEFAULT_DOUBLE_ROUNDING \
79 ieee_flags("clear","precision",NULL,NULL)
80
81 # endif
82 #endif
83 /*
84 * Other platforms are assumed to always operate in full IEEE mode, so we make
85 * the macros to go in and out of that mode do nothing.
86 */
87 #ifndef TCL_IEEE_DOUBLE_ROUNDING /* !__i386 || (!__GNUC__ && !__sun) */
88 # define TCL_IEEE_DOUBLE_ROUNDING_DECL
89 # define TCL_IEEE_DOUBLE_ROUNDING ((void) 0)
90 # define TCL_DEFAULT_DOUBLE_ROUNDING ((void) 0)
91 #endif
92
93 /*
94 * MIPS floating-point units need special settings in control registers to use
95 * gradual underflow as we expect. This fix is for the MIPSpro compiler.
96 */
97
98 #if defined(__sgi) && defined(_COMPILER_VERSION)
99 #include <sys/fpu.h>
100 #endif
101
102 /*
103 * HP's PA_RISC architecture uses 7ff4000000000000 to represent a quiet NaN.
104 * Everyone else uses 7ff8000000000000. (Why, HP, why?)
105 */
106
107 #ifdef __hppa
108 # define NAN_START 0x7FF4
109 # define NAN_MASK (((Tcl_WideUInt) 1) << 50)
110 #else
111 # define NAN_START 0x7FF8
112 # define NAN_MASK (((Tcl_WideUInt) 1) << 51)
113 #endif
114
115 /*
116 * Constants used by this file (most of which are only ever calculated at
117 * runtime).
118 */
119
120 /* Magic constants */
121
122 #define LOG10_2 0.3010299956639812
123 #define TWO_OVER_3LOG10 0.28952965460216784
124 #define LOG10_3HALVES_PLUS_FUDGE 0.1760912590558
125
126 /*
127 * Definitions of the parts of an IEEE754-format floating point number.
128 */
129
130 #define SIGN_BIT 0x80000000
131 /* Mask for the sign bit in the first word of
132 * a double. */
133 #define EXP_MASK 0x7FF00000
134 /* Mask for the exponent field in the first
135 * word of a double. */
136 #define EXP_SHIFT 20 /* Shift count to make the exponent an
137 * integer. */
138 #define HIDDEN_BIT (((Tcl_WideUInt) 0x00100000) << 32)
139 /* Hidden 1 bit for the significand. */
140 #define HI_ORDER_SIG_MASK 0x000FFFFF
141 /* Mask for the high-order part of the
142 * significand in the first word of a
143 * double. */
144 #define SIG_MASK (((Tcl_WideUInt) HI_ORDER_SIG_MASK << 32) \
145 | 0xFFFFFFFF)
146 /* Mask for the 52-bit significand. */
147 #define FP_PRECISION 53 /* Number of bits of significand plus the
148 * hidden bit. */
149 #define EXPONENT_BIAS 0x3FF /* Bias of the exponent 0. */
150
151 /*
152 * Derived quantities.
153 */
154
155 #define TEN_PMAX 22 /* floor(FP_PRECISION*log(2)/log(5)) */
156 #define QUICK_MAX 14 /* floor((FP_PRECISION-1)*log(2)/log(10))-1 */
157 #define BLETCH 0x10 /* Highest power of two that is greater than
158 * DBL_MAX_10_EXP, divided by 16. */
159 #define DIGIT_GROUP 8 /* floor(MP_DIGIT_BIT*log(2)/log(10)) */
160
161 /*
162 * Union used to dismantle floating point numbers.
163 */
164
165 typedef union Double {
166 struct {
167 #ifdef WORDS_BIGENDIAN
168 int word0;
169 int word1;
170 #else
171 int word1;
172 int word0;
173 #endif
174 } w;
175 double d;
176 Tcl_WideUInt q;
177 } Double;
178
179 static int maxpow10_wide; /* The powers of ten that can be represented
180 * exactly as wide integers. */
181 static Tcl_WideUInt *pow10_wide;
182 #define MAXPOW 22
183 static double pow10vals[MAXPOW+1];
184 /* The powers of ten that can be represented
185 * exactly as IEEE754 doubles. */
186 static int mmaxpow; /* Largest power of ten that can be
187 * represented exactly in a 'double'. */
188 static int log10_DIGIT_MAX; /* The number of decimal digits that fit in an
189 * mp_digit. */
190 static int log2FLT_RADIX; /* Logarithm of the floating point radix. */
191 static int mantBits; /* Number of bits in a double's significand */
192 static mp_int pow5[9]; /* Table of powers of 5**(2**n), up to
193 * 5**256 */
194 static double tiny = 0.0; /* The smallest representable double. */
195 static int maxDigits; /* The maximum number of digits to the left of
196 * the decimal point of a double. */
197 static int minDigits; /* The maximum number of digits to the right
198 * of the decimal point in a double. */
199 static const double pow_10_2_n[] = { /* Inexact higher powers of ten. */
200 1.0,
201 100.0,
202 10000.0,
203 1.0e+8,
204 1.0e+16,
205 1.0e+32,
206 1.0e+64,
207 1.0e+128,
208 1.0e+256
209 };
210
211 static int n770_fp; /* Flag is 1 on Nokia N770 floating point.
212 * Nokia's floating point has the words
213 * reversed: if big-endian is 7654 3210,
214 * and little-endian is 0123 4567,
215 * then Nokia's FP is 4567 0123;
216 * little-endian within the 32-bit words but
217 * big-endian between them. */
218
219 /*
220 * Table of powers of 5 that are small enough to fit in an mp_digit.
221 */
222
223 static const mp_digit dpow5[13] = {
224 1, 5, 25, 125,
225 625, 3125, 15625, 78125,
226 390625, 1953125, 9765625, 48828125,
227 244140625
228 };
229
230 /*
231 * Table of powers: pow5_13[n] = 5**(13*2**(n+1))
232 */
233
234 static mp_int pow5_13[5]; /* Table of powers: 5**13, 5**26, 5**52,
235 * 5**104, 5**208 */
236 static const double tens[] = {
237 1e00, 1e01, 1e02, 1e03, 1e04, 1e05, 1e06, 1e07, 1e08, 1e09,
238 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
239 1e20, 1e21, 1e22
240 };
241
242 static const int itens [] = {
243 1,
244 10,
245 100,
246 1000,
247 10000,
248 100000,
249 1000000,
250 10000000,
251 100000000
252 };
253
254 static const double bigtens[] = {
255 1e016, 1e032, 1e064, 1e128, 1e256
256 };
257 #define N_BIGTENS 5
258
259 static const int log2pow5[27] = {
260 01, 3, 5, 7, 10, 12, 14, 17, 19, 21,
261 24, 26, 28, 31, 33, 35, 38, 40, 42, 45,
262 47, 49, 52, 54, 56, 59, 61
263 };
264 #define N_LOG2POW5 27
265
266 static const Tcl_WideUInt wuipow5[] = {
267 (Tcl_WideUInt) 1U, /* 5**0 */
268 (Tcl_WideUInt) 5U,
269 (Tcl_WideUInt) 25U,
270 (Tcl_WideUInt) 125U,
271 (Tcl_WideUInt) 625U,
272 (Tcl_WideUInt) 3125U, /* 5**5 */
273 (Tcl_WideUInt) 3125U*5U,
274 (Tcl_WideUInt) 3125U*25U,
275 (Tcl_WideUInt) 3125U*125U,
276 (Tcl_WideUInt) 3125U*625U,
277 (Tcl_WideUInt) 3125U*3125U, /* 5**10 */
278 (Tcl_WideUInt) 3125U*3125U*5U,
279 (Tcl_WideUInt) 3125U*3125U*25U,
280 (Tcl_WideUInt) 3125U*3125U*125U,
281 (Tcl_WideUInt) 3125U*3125U*625U,
282 (Tcl_WideUInt) 3125U*3125U*3125U, /* 5**15 */
283 (Tcl_WideUInt) 3125U*3125U*3125U*5U,
284 (Tcl_WideUInt) 3125U*3125U*3125U*25U,
285 (Tcl_WideUInt) 3125U*3125U*3125U*125U,
286 (Tcl_WideUInt) 3125U*3125U*3125U*625U,
287 (Tcl_WideUInt) 3125U*3125U*3125U*3125U, /* 5**20 */
288 (Tcl_WideUInt) 3125U*3125U*3125U*3125U*5U,
289 (Tcl_WideUInt) 3125U*3125U*3125U*3125U*25U,
290 (Tcl_WideUInt) 3125U*3125U*3125U*3125U*125U,
291 (Tcl_WideUInt) 3125U*3125U*3125U*3125U*625U,
292 (Tcl_WideUInt) 3125U*3125U*3125U*3125U*3125U, /* 5**25 */
293 (Tcl_WideUInt) 3125U*3125U*3125U*3125U*3125U*5U,
294 (Tcl_WideUInt) 3125U*3125U*3125U*3125U*3125U*25U /* 5**27 */
295 };
296
297 /*
298 * Static functions defined in this file.
299 */
300
301 static int AccumulateDecimalDigit(unsigned, int,
302 Tcl_WideUInt *, mp_int *, int);
303 static double MakeHighPrecisionDouble(int signum,
304 mp_int *significand, int nSigDigs, int exponent);
305 static double MakeLowPrecisionDouble(int signum,
306 Tcl_WideUInt significand, int nSigDigs,
307 int exponent);
308 #ifdef IEEE_FLOATING_POINT
309 static double MakeNaN(int signum, Tcl_WideUInt tag);
310 #endif
311 static double RefineApproximation(double approx,
312 mp_int *exactSignificand, int exponent);
313 static void MulPow5(mp_int *, unsigned, mp_int *);
314 static int NormalizeRightward(Tcl_WideUInt *);
315 static int RequiredPrecision(Tcl_WideUInt);
316 static void DoubleToExpAndSig(double, Tcl_WideUInt *, int *,
317 int *);
318 static void TakeAbsoluteValue(Double *, int *);
319 static char * FormatInfAndNaN(Double *, int *, char **);
320 static char * FormatZero(int *, char **);
321 static int ApproximateLog10(Tcl_WideUInt, int, int);
322 static int BetterLog10(double, int, int *);
323 static void ComputeScale(int, int, int *, int *, int *, int *);
324 static void SetPrecisionLimits(int, int, int *, int *, int *,
325 int *);
326 static char * BumpUp(char *, char *, int *);
327 static int AdjustRange(double *, int);
328 static char * ShorteningQuickFormat(double, int, int, double,
329 char *, int *);
330 static char * StrictQuickFormat(double, int, int, double,
331 char *, int *);
332 static char * QuickConversion(double, int, int, int, int, int, int,
333 int *, char **);
334 static void CastOutPowersOf2(int *, int *, int *);
335 static char * ShorteningInt64Conversion(Double *, int, Tcl_WideUInt,
336 int, int, int, int, int, int, int, int, int,
337 int, int, int *, char **);
338 static char * StrictInt64Conversion(Tcl_WideUInt,
339 int, int, int, int, int, int,
340 int, int, int *, char **);
341 static int ShouldBankerRoundUpPowD(mp_int *, int, int);
342 static int ShouldBankerRoundUpToNextPowD(mp_int *, mp_int *,
343 int, int, int, mp_int *);
344 static char * ShorteningBignumConversionPowD(Double *dPtr,
345 int convType, Tcl_WideUInt bw, int b2, int b5,
346 int m2plus, int m2minus, int m5,
347 int sd, int k, int len,
348 int ilim, int ilim1, int *decpt,
349 char **endPtr);
350 static char * StrictBignumConversionPowD(
351 Tcl_WideUInt bw, int b2, int b5,
352 int sd, int k, int len,
353 int ilim, int ilim1, int *decpt,
354 char **endPtr);
355 static int ShouldBankerRoundUp(mp_int *, mp_int *, int);
356 static int ShouldBankerRoundUpToNext(mp_int *, mp_int *,
357 mp_int *, int, int, mp_int *);
358 static char * ShorteningBignumConversion(Double *dPtr, int convType,
359 Tcl_WideUInt bw, int b2,
360 int m2plus, int m2minus,
361 int s2, int s5, int k, int len,
362 int ilim, int ilim1, int *decpt,
363 char **endPtr);
364 static char * StrictBignumConversion(
365 Tcl_WideUInt bw, int b2,
366 int s2, int s5, int k, int len,
367 int ilim, int ilim1, int *decpt,
368 char **endPtr);
369 static double BignumToBiasedFrExp(const mp_int *big, int *machexp);
370 static double Pow10TimesFrExp(int exponent, double fraction,
371 int *machexp);
372 static double SafeLdExp(double fraction, int exponent);
373 #ifdef IEEE_FLOATING_POINT
374 static Tcl_WideUInt Nokia770Twiddle(Tcl_WideUInt w);
375 #endif
376
377 /*
378 *----------------------------------------------------------------------
379 *
380 * TclParseNumber --
381 *
382 * Scans bytes, interpreted as characters in Tcl's internal encoding, and
383 * parses the longest prefix that is the string representation of a
384 * number in a format recognized by Tcl.
385 *
386 * The arguments bytes, numBytes, and objPtr are the inputs which
387 * determine the string to be parsed. If bytes is non-NULL, it points to
388 * the first byte to be scanned. If bytes is NULL, then objPtr must be
389 * non-NULL, and the string representation of objPtr will be scanned
390 * (generated first, if necessary). The numBytes argument determines the
391 * number of bytes to be scanned. If numBytes is negative, the first NUL
392 * byte encountered will terminate the scan. If numBytes is non-negative,
393 * then no more than numBytes bytes will be scanned.
394 *
395 * The argument flags is an input that controls the numeric formats
396 * recognized by the parser. The flag bits are:
397 *
398 * - TCL_PARSE_INTEGER_ONLY: accept only integer values; reject
399 * strings that denote floating point values (or accept only the
400 * leading portion of them that are integer values).
401 * - TCL_PARSE_SCAN_PREFIXES: ignore the prefixes 0b and 0o that are
402 * not part of the [scan] command's vocabulary. Use only in
403 * combination with TCL_PARSE_INTEGER_ONLY.
404 * - TCL_PARSE_BINARY_ONLY: parse only in the binary format, whether
405 * or not a prefix is present that would lead to binary parsing.
406 * Use only in combination with TCL_PARSE_INTEGER_ONLY.
407 * - TCL_PARSE_OCTAL_ONLY: parse only in the octal format, whether
408 * or not a prefix is present that would lead to octal parsing.
409 * Use only in combination with TCL_PARSE_INTEGER_ONLY.
410 * - TCL_PARSE_HEXADECIMAL_ONLY: parse only in the hexadecimal format,
411 * whether or not a prefix is present that would lead to
412 * hexadecimal parsing. Use only in combination with
413 * TCL_PARSE_INTEGER_ONLY.
414 * - TCL_PARSE_DECIMAL_ONLY: parse only in the decimal format, no
415 * matter whether a 0 prefix would normally force a different
416 * base.
417 * - TCL_PARSE_NO_WHITESPACE: reject any leading/trailing whitespace
418 *
419 * The arguments interp and expected are inputs that control error
420 * message generation. If interp is NULL, no error message will be
421 * generated. If interp is non-NULL, then expected must also be non-NULL.
422 * When TCL_ERROR is returned, an error message will be left in the
423 * result of interp, and the expected argument will appear in the error
424 * message as the thing TclParseNumber expected, but failed to find in
425 * the string.
426 *
427 * The arguments objPtr and endPtrPtr as well as the return code are the
428 * outputs.
429 *
430 * When the parser cannot find any prefix of the string that matches a
431 * format it is looking for, TCL_ERROR is returned and an error message
432 * may be generated and returned as described above. The contents of
433 * objPtr will not be changed. If endPtrPtr is non-NULL, a pointer to the
434 * character in the string that terminated the scan will be written to
435 * *endPtrPtr.
436 *
437 * When the parser determines that the entire string matches a format it
438 * is looking for, TCL_OK is returned, and if objPtr is non-NULL, then
439 * the internal rep and Tcl_ObjType of objPtr are set to the "canonical"
440 * numeric value that matches the scanned string. If endPtrPtr is not
441 * NULL, a pointer to the end of the string will be written to *endPtrPtr
442 * (that is, either bytes+numBytes or a pointer to a terminating NUL
443 * byte).
444 *
445 * When the parser determines that a partial string matches a format it
446 * is looking for, the value of endPtrPtr determines what happens:
447 *
448 * - If endPtrPtr is NULL, then TCL_ERROR is returned, with error message
449 * generation as above.
450 *
451 * - If endPtrPtr is non-NULL, then TCL_OK is returned and objPtr
452 * internals are set as above. Also, a pointer to the first
453 * character following the parsed numeric string is written to
454 * *endPtrPtr.
455 *
456 * In some cases where the string being scanned is the string rep of
457 * objPtr, this routine can leave objPtr in an inconsistent state where
458 * its string rep and its internal rep do not agree. In these cases the
459 * internal rep will be in agreement with only some substring of the
460 * string rep. This might happen if the caller passes in a non-NULL bytes
461 * value that points somewhere into the string rep. It might happen if
462 * the caller passes in a numBytes value that limits the scan to only a
463 * prefix of the string rep. Or it might happen if a non-NULL value of
464 * endPtrPtr permits a TCL_OK return from only a partial string match. It
465 * is the responsibility of the caller to detect and correct such
466 * inconsistencies when they can and do arise.
467 *
468 * Results:
469 * Returns a standard Tcl result.
470 *
471 * Side effects:
472 * The string representaton of objPtr may be generated.
473 *
474 * The internal representation and Tcl_ObjType of objPtr may be changed.
475 * This may involve allocation and/or freeing of memory.
476 *
477 *----------------------------------------------------------------------
478 */
479
480 int
481 TclParseNumber(
482 Tcl_Interp *interp, /* Used for error reporting. May be NULL. */
483 Tcl_Obj *objPtr, /* Object to receive the internal rep. */
484 const char *expected, /* Description of the type of number the
485 * caller expects to be able to parse
486 * ("integer", "boolean value", etc.). */
487 const char *bytes, /* Pointer to the start of the string to
488 * scan. */
489 int numBytes, /* Maximum number of bytes to scan, see
490 * above. */
491 const char **endPtrPtr, /* Place to store pointer to the character
492 * that terminated the scan. */
493 int flags) /* Flags governing the parse. */
494 {
495 enum State {
496 INITIAL, SIGNUM, ZERO, ZERO_X,
497 ZERO_O, ZERO_B, BINARY,
498 HEXADECIMAL, OCTAL, BAD_OCTAL, DECIMAL,
499 LEADING_RADIX_POINT, FRACTION,
500 EXPONENT_START, EXPONENT_SIGNUM, EXPONENT,
501 sI, sIN, sINF, sINFI, sINFIN, sINFINI, sINFINIT, sINFINITY
502 #ifdef IEEE_FLOATING_POINT
503 , sN, sNA, sNAN, sNANPAREN, sNANHEX, sNANFINISH
504 #endif
505 } state = INITIAL;
506 enum State acceptState = INITIAL;
507
508 int signum = 0; /* Sign of the number being parsed. */
509 Tcl_WideUInt significandWide = 0;
510 /* Significand of the number being parsed (if
511 * no overflow). */
512 mp_int significandBig; /* Significand of the number being parsed (if
513 * it overflows significandWide). */
514 int significandOverflow = 0;/* Flag==1 iff significandBig is used. */
515 Tcl_WideUInt octalSignificandWide = 0;
516 /* Significand of an octal number; needed
517 * because we don't know whether a number with
518 * a leading zero is octal or decimal until
519 * we've scanned forward to a '.' or 'e'. */
520 mp_int octalSignificandBig; /* Significand of octal number once
521 * octalSignificandWide overflows. */
522 int octalSignificandOverflow = 0;
523 /* Flag==1 if octalSignificandBig is used. */
524 int numSigDigs = 0; /* Number of significant digits in the decimal
525 * significand. */
526 int numTrailZeros = 0; /* Number of trailing zeroes at the current
527 * point in the parse. */
528 int numDigitsAfterDp = 0; /* Number of digits scanned after the decimal
529 * point. */
530 int exponentSignum = 0; /* Signum of the exponent of a floating point
531 * number. */
532 int exponent = 0; /* Exponent of a floating point number. */
533 const char *p; /* Pointer to next character to scan. */
534 size_t len; /* Number of characters remaining after p. */
535 const char *acceptPoint; /* Pointer to position after last character in
536 * an acceptable number. */
537 size_t acceptLen; /* Number of characters following that
538 * point. */
539 int status = TCL_OK; /* Status to return to caller. */
540 char d = 0; /* Last hexadecimal digit scanned; initialized
541 * to avoid a compiler warning. */
542 int shift = 0; /* Amount to shift when accumulating binary */
543 int explicitOctal = 0;
544
545 #define MOST_BITS (UWIDE_MAX >> 1)
546
547 /*
548 * Initialize bytes to start of the object's string rep if the caller
549 * didn't pass anything else.
550 */
551
552 if (bytes == NULL) {
553 bytes = TclGetString(objPtr);
554 }
555
556 p = bytes;
557 len = numBytes;
558 acceptPoint = p;
559 acceptLen = len;
560 while (1) {
561 char c = len ? *p : '\0';
562 switch (state) {
563
564 case INITIAL:
565 /*
566 * Initial state. Acceptable characters are +, -, digits, period,
567 * I, N, and whitespace.
568 */
569
570 if (TclIsSpaceProcM(c)) {
571 if (flags & TCL_PARSE_NO_WHITESPACE) {
572 goto endgame;
573 }
574 break;
575 } else if (c == '+') {
576 state = SIGNUM;
577 break;
578 } else if (c == '-') {
579 signum = 1;
580 state = SIGNUM;
581 break;
582 }
583 /* FALLTHROUGH */
584
585 case SIGNUM:
586 /*
587 * Scanned a leading + or -. Acceptable characters are digits,
588 * period, I, and N.
589 */
590
591 if (c == '0') {
592 if (flags & TCL_PARSE_DECIMAL_ONLY) {
593 state = DECIMAL;
594 } else {
595 state = ZERO;
596 }
597 break;
598 } else if (flags & TCL_PARSE_HEXADECIMAL_ONLY) {
599 goto zerox;
600 } else if (flags & TCL_PARSE_BINARY_ONLY) {
601 goto zerob;
602 } else if (flags & TCL_PARSE_OCTAL_ONLY) {
603 goto zeroo;
604 } else if (isdigit(UCHAR(c))) {
605 significandWide = c - '0';
606 numSigDigs = 1;
607 state = DECIMAL;
608 break;
609 } else if (flags & TCL_PARSE_INTEGER_ONLY) {
610 goto endgame;
611 } else if (c == '.') {
612 state = LEADING_RADIX_POINT;
613 break;
614 } else if (c == 'I' || c == 'i') {
615 state = sI;
616 break;
617 #ifdef IEEE_FLOATING_POINT
618 } else if (c == 'N' || c == 'n') {
619 state = sN;
620 break;
621 #endif
622 }
623 goto endgame;
624
625 case ZERO:
626 /*
627 * Scanned a leading zero (perhaps with a + or -). Acceptable
628 * inputs are digits, period, X, b, and E. If 8 or 9 is
629 * encountered, the number can't be octal. This state and the
630 * OCTAL state differ only in whether they recognize 'X' and 'b'.
631 */
632
633 acceptState = state;
634 acceptPoint = p;
635 acceptLen = len;
636 if (c == 'x' || c == 'X') {
637 if (flags & (TCL_PARSE_OCTAL_ONLY|TCL_PARSE_BINARY_ONLY)) {
638 goto endgame;
639 }
640 state = ZERO_X;
641 break;
642 }
643 if (flags & TCL_PARSE_HEXADECIMAL_ONLY) {
644 goto zerox;
645 }
646 if (flags & TCL_PARSE_SCAN_PREFIXES) {
647 goto zeroo;
648 }
649 if (c == 'b' || c == 'B') {
650 if (flags & TCL_PARSE_OCTAL_ONLY) {
651 goto endgame;
652 }
653 state = ZERO_B;
654 break;
655 }
656 if (flags & TCL_PARSE_BINARY_ONLY) {
657 goto zerob;
658 }
659 if (c == 'o' || c == 'O') {
660 explicitOctal = 1;
661 state = ZERO_O;
662 break;
663 }
664 #ifdef KILL_OCTAL
665 goto decimal;
666 #endif
667 /* FALLTHROUGH */
668
669 case OCTAL:
670 /*
671 * Scanned an optional + or -, followed by a string of octal
672 * digits. Acceptable inputs are more digits, period, or E. If 8
673 * or 9 is encountered, commit to floating point.
674 */
675
676 acceptState = state;
677 acceptPoint = p;
678 acceptLen = len;
679 /* FALLTHROUGH */
680 case ZERO_O:
681 zeroo:
682 if (c == '0') {
683 numTrailZeros++;
684 state = OCTAL;
685 break;
686 } else if (c >= '1' && c <= '7') {
687 if (objPtr != NULL) {
688 shift = 3 * (numTrailZeros + 1);
689 significandOverflow = AccumulateDecimalDigit(
690 (unsigned)(c-'0'), numTrailZeros,
691 &significandWide, &significandBig,
692 significandOverflow);
693
694 if (!octalSignificandOverflow) {
695 /*
696 * Shifting by as many or more bits than are in the
697 * value being shifted is undefined behavior. Check
698 * for too large shifts first.
699 */
700
701 if ((octalSignificandWide != 0)
702 && (((size_t)shift >=
703 CHAR_BIT*sizeof(Tcl_WideUInt))
704 || (octalSignificandWide >
705 (UWIDE_MAX >> shift)))) {
706 octalSignificandOverflow = 1;
707 TclBNInitBignumFromWideUInt(&octalSignificandBig,
708 octalSignificandWide);
709 }
710 }
711 if (!octalSignificandOverflow) {
712 /*
713 * When the significand is 0, it is possible for the
714 * amount to be shifted to equal or exceed the width
715 * of the significand. Do not shift when the
716 * significand is 0 to avoid undefined behavior.
717 */
718
719 if (octalSignificandWide != 0) {
720 octalSignificandWide <<= shift;
721 }
722 octalSignificandWide += c - '0';
723 } else {
724 mp_mul_2d(&octalSignificandBig, shift,
725 &octalSignificandBig);
726 mp_add_d(&octalSignificandBig, (mp_digit)(c - '0'),
727 &octalSignificandBig);
728 }
729 }
730 if (numSigDigs != 0) {
731 numSigDigs += numTrailZeros+1;
732 } else {
733 numSigDigs = 1;
734 }
735 numTrailZeros = 0;
736 state = OCTAL;
737 break;
738 }
739 /* FALLTHROUGH */
740
741 case BAD_OCTAL:
742 if (explicitOctal) {
743 /*
744 * No forgiveness for bad digits in explicitly octal numbers.
745 */
746
747 goto endgame;
748 }
749 if (flags & TCL_PARSE_INTEGER_ONLY) {
750 /*
751 * No seeking floating point when parsing only integer.
752 */
753
754 goto endgame;
755 }
756 #ifndef KILL_OCTAL
757
758 /*
759 * Scanned a number with a leading zero that contains an 8, 9,
760 * radix point or E. This is an invalid octal number, but might
761 * still be floating point.
762 */
763
764 if (c == '0') {
765 numTrailZeros++;
766 state = BAD_OCTAL;
767 break;
768 } else if (isdigit(UCHAR(c))) {
769 if (objPtr != NULL) {
770 significandOverflow = AccumulateDecimalDigit(
771 (unsigned)(c-'0'), numTrailZeros,
772 &significandWide, &significandBig,
773 significandOverflow);
774 }
775 if (numSigDigs != 0) {
776 numSigDigs += (numTrailZeros + 1);
777 } else {
778 numSigDigs = 1;
779 }
780 numTrailZeros = 0;
781 state = BAD_OCTAL;
782 break;
783 } else if (c == '.') {
784 state = FRACTION;
785 break;
786 } else if (c == 'E' || c == 'e') {
787 state = EXPONENT_START;
788 break;
789 }
790 #endif
791 goto endgame;
792
793 /*
794 * Scanned 0x. If state is HEXADECIMAL, scanned at least one
795 * character following the 0x. The only acceptable inputs are
796 * hexadecimal digits.
797 */
798
799 case HEXADECIMAL:
800 acceptState = state;
801 acceptPoint = p;
802 acceptLen = len;
803 /* FALLTHROUGH */
804
805 case ZERO_X:
806 zerox:
807 if (c == '0') {
808 numTrailZeros++;
809 state = HEXADECIMAL;
810 break;
811 } else if (isdigit(UCHAR(c))) {
812 d = (c-'0');
813 } else if (c >= 'A' && c <= 'F') {
814 d = (c-'A'+10);
815 } else if (c >= 'a' && c <= 'f') {
816 d = (c-'a'+10);
817 } else {
818 goto endgame;
819 }
820 if (objPtr != NULL) {
821 shift = 4 * (numTrailZeros + 1);
822 if (!significandOverflow) {
823 /*
824 * Shifting by as many or more bits than are in the
825 * value being shifted is undefined behavior. Check
826 * for too large shifts first.
827 */
828
829 if (significandWide != 0 &&
830 ((size_t)shift >= CHAR_BIT*sizeof(Tcl_WideUInt) ||
831 significandWide > (UWIDE_MAX >> shift))) {
832 significandOverflow = 1;
833 TclBNInitBignumFromWideUInt(&significandBig,
834 significandWide);
835 }
836 }
837 if (!significandOverflow) {
838 /*
839 * When the significand is 0, it is possible for the
840 * amount to be shifted to equal or exceed the width
841 * of the significand. Do not shift when the
842 * significand is 0 to avoid undefined behavior.
843 */
844
845 if (significandWide != 0) {
846 significandWide <<= shift;
847 }
848 significandWide += d;
849 } else {
850 mp_mul_2d(&significandBig, shift, &significandBig);
851 mp_add_d(&significandBig, (mp_digit) d, &significandBig);
852 }
853 }
854 numTrailZeros = 0;
855 state = HEXADECIMAL;
856 break;
857
858 case BINARY:
859 acceptState = state;
860 acceptPoint = p;
861 acceptLen = len;
862 /* FALLTHRU */
863 case ZERO_B:
864 zerob:
865 if (c == '0') {
866 numTrailZeros++;
867 state = BINARY;
868 break;
869 } else if (c != '1') {
870 goto endgame;
871 }
872 if (objPtr != NULL) {
873 shift = numTrailZeros + 1;
874 if (!significandOverflow) {
875 /*
876 * Shifting by as many or more bits than are in the
877 * value being shifted is undefined behavior. Check
878 * for too large shifts first.
879 */
880
881 if (significandWide != 0 &&
882 ((size_t)shift >= CHAR_BIT*sizeof(Tcl_WideUInt) ||
883 significandWide > (UWIDE_MAX >> shift))) {
884 significandOverflow = 1;
885 TclBNInitBignumFromWideUInt(&significandBig,
886 significandWide);
887 }
888 }
889 if (!significandOverflow) {
890 /*
891 * When the significand is 0, it is possible for the
892 * amount to be shifted to equal or exceed the width
893 * of the significand. Do not shift when the
894 * significand is 0 to avoid undefined behavior.
895 */
896
897 if (significandWide != 0) {
898 significandWide <<= shift;
899 }
900 significandWide += 1;
901 } else {
902 mp_mul_2d(&significandBig, shift, &significandBig);
903 mp_add_d(&significandBig, (mp_digit) 1, &significandBig);
904 }
905 }
906 numTrailZeros = 0;
907 state = BINARY;
908 break;
909
910 case DECIMAL:
911 /*
912 * Scanned an optional + or - followed by a string of decimal
913 * digits.
914 */
915
916 #ifdef KILL_OCTAL
917 decimal:
918 #endif
919 acceptState = state;
920 acceptPoint = p;
921 acceptLen = len;
922 if (c == '0') {
923 numTrailZeros++;
924 state = DECIMAL;
925 break;
926 } else if (isdigit(UCHAR(c))) {
927 if (objPtr != NULL) {
928 significandOverflow = AccumulateDecimalDigit(
929 (unsigned)(c - '0'), numTrailZeros,
930 &significandWide, &significandBig,
931 significandOverflow);
932 }
933 numSigDigs += numTrailZeros+1;
934 numTrailZeros = 0;
935 state = DECIMAL;
936 break;
937 } else if (flags & TCL_PARSE_INTEGER_ONLY) {
938 goto endgame;
939 } else if (c == '.') {
940 state = FRACTION;
941 break;
942 } else if (c == 'E' || c == 'e') {
943 state = EXPONENT_START;
944 break;
945 }
946 goto endgame;
947
948 /*
949 * Found a decimal point. If no digits have yet been scanned, E is
950 * not allowed; otherwise, it introduces the exponent. If at least
951 * one digit has been found, we have a possible complete number.
952 */
953
954 case FRACTION:
955 acceptState = state;
956 acceptPoint = p;
957 acceptLen = len;
958 if (c == 'E' || c=='e') {
959 state = EXPONENT_START;
960 break;
961 }
962 /* FALLTHROUGH */
963
964 case LEADING_RADIX_POINT:
965 if (c == '0') {
966 numDigitsAfterDp++;
967 numTrailZeros++;
968 state = FRACTION;
969 break;
970 } else if (isdigit(UCHAR(c))) {
971 numDigitsAfterDp++;
972 if (objPtr != NULL) {
973 significandOverflow = AccumulateDecimalDigit(
974 (unsigned)(c-'0'), numTrailZeros,
975 &significandWide, &significandBig,
976 significandOverflow);
977 }
978 if (numSigDigs != 0) {
979 numSigDigs += numTrailZeros+1;
980 } else {
981 numSigDigs = 1;
982 }
983 numTrailZeros = 0;
984 state = FRACTION;
985 break;
986 }
987 goto endgame;
988
989 case EXPONENT_START:
990 /*
991 * Scanned the E at the start of an exponent. Make sure a legal
992 * character follows before using the C library strtol routine,
993 * which allows whitespace.
994 */
995
996 if (c == '+') {
997 state = EXPONENT_SIGNUM;
998 break;
999 } else if (c == '-') {
1000 exponentSignum = 1;
1001 state = EXPONENT_SIGNUM;
1002 break;
1003 }
1004 /* FALLTHROUGH */
1005
1006 case EXPONENT_SIGNUM:
1007 /*
1008 * Found the E at the start of the exponent, followed by a sign
1009 * character.
1010 */
1011
1012 if (isdigit(UCHAR(c))) {
1013 exponent = c - '0';
1014 state = EXPONENT;
1015 break;
1016 }
1017 goto endgame;
1018
1019 case EXPONENT:
1020 /*
1021 * Found an exponent with at least one digit. Accumulate it,
1022 * making sure to hard-pin it to INT_MAX on overflow.
1023 */
1024
1025 acceptState = state;
1026 acceptPoint = p;
1027 acceptLen = len;
1028 if (isdigit(UCHAR(c))) {
1029 if (exponent < (INT_MAX - 9) / 10) {
1030 exponent = 10 * exponent + (c - '0');
1031 } else {
1032 exponent = INT_MAX;
1033 }
1034 state = EXPONENT;
1035 break;
1036 }
1037 goto endgame;
1038
1039 /*
1040 * Parse out INFINITY by simply spelling it out. INF is accepted
1041 * as an abbreviation; other prefices are not.
1042 */
1043
1044 case sI:
1045 if (c == 'n' || c == 'N') {
1046 state = sIN;
1047 break;
1048 }
1049 goto endgame;
1050 case sIN:
1051 if (c == 'f' || c == 'F') {
1052 state = sINF;
1053 break;
1054 }
1055 goto endgame;
1056 case sINF:
1057 acceptState = state;
1058 acceptPoint = p;
1059 acceptLen = len;
1060 if (c == 'i' || c == 'I') {
1061 state = sINFI;
1062 break;
1063 }
1064 goto endgame;
1065 case sINFI:
1066 if (c == 'n' || c == 'N') {
1067 state = sINFIN;
1068 break;
1069 }
1070 goto endgame;
1071 case sINFIN:
1072 if (c == 'i' || c == 'I') {
1073 state = sINFINI;
1074 break;
1075 }
1076 goto endgame;
1077 case sINFINI:
1078 if (c == 't' || c == 'T') {
1079 state = sINFINIT;
1080 break;
1081 }
1082 goto endgame;
1083 case sINFINIT:
1084 if (c == 'y' || c == 'Y') {
1085 state = sINFINITY;
1086 break;
1087 }
1088 goto endgame;
1089
1090 /*
1091 * Parse NaN's.
1092 */
1093 #ifdef IEEE_FLOATING_POINT
1094 case sN:
1095 if (c == 'a' || c == 'A') {
1096 state = sNA;
1097 break;
1098 }
1099 goto endgame;
1100 case sNA:
1101 if (c == 'n' || c == 'N') {
1102 state = sNAN;
1103 break;
1104 }
1105 goto endgame;
1106 case sNAN:
1107 acceptState = state;
1108 acceptPoint = p;
1109 acceptLen = len;
1110 if (c == '(') {
1111 state = sNANPAREN;
1112 break;
1113 }
1114 goto endgame;
1115
1116 /*
1117 * Parse NaN(hexdigits)
1118 */
1119 case sNANHEX:
1120 if (c == ')') {
1121 state = sNANFINISH;
1122 break;
1123 }
1124 /* FALLTHROUGH */
1125 case sNANPAREN:
1126 if (TclIsSpaceProcM(c)) {
1127 break;
1128 }
1129 if (numSigDigs < 13) {
1130 if (c >= '0' && c <= '9') {
1131 d = c - '0';
1132 } else if (c >= 'a' && c <= 'f') {
1133 d = 10 + c - 'a';
1134 } else if (c >= 'A' && c <= 'F') {
1135 d = 10 + c - 'A';
1136 } else {
1137 goto endgame;
1138 }
1139 numSigDigs++;
1140 significandWide = (significandWide << 4) + d;
1141 state = sNANHEX;
1142 break;
1143 }
1144 goto endgame;
1145 case sNANFINISH:
1146 #endif
1147
1148 case sINFINITY:
1149 acceptState = state;
1150 acceptPoint = p;
1151 acceptLen = len;
1152 goto endgame;
1153 }
1154 p++;
1155 len--;
1156 }
1157
1158 endgame:
1159 if (acceptState == INITIAL) {
1160 /*
1161 * No numeric string at all found.
1162 */
1163
1164 status = TCL_ERROR;
1165 if (endPtrPtr != NULL) {
1166 *endPtrPtr = p;
1167 }
1168 } else {
1169 /*
1170 * Back up to the last accepting state in the lexer.
1171 */
1172
1173 p = acceptPoint;
1174 len = acceptLen;
1175
1176 if (!(flags & TCL_PARSE_NO_WHITESPACE)) {
1177 /*
1178 * Accept trailing whitespace.
1179 */
1180
1181 while (len != 0 && TclIsSpaceProcM(*p)) {
1182 p++;
1183 len--;
1184 }
1185 }
1186 if (endPtrPtr == NULL) {
1187 if ((len != 0) && ((numBytes > 0) || (*p != '\0'))) {
1188 status = TCL_ERROR;
1189 }
1190 } else {
1191 *endPtrPtr = p;
1192 }
1193 }
1194
1195 /*
1196 * Generate and store the appropriate internal rep.
1197 */
1198
1199 if (status == TCL_OK && objPtr != NULL) {
1200 TclFreeIntRep(objPtr);
1201 switch (acceptState) {
1202 case SIGNUM:
1203 case BAD_OCTAL:
1204 case ZERO_X:
1205 case ZERO_O:
1206 case ZERO_B:
1207 case LEADING_RADIX_POINT:
1208 case EXPONENT_START:
1209 case EXPONENT_SIGNUM:
1210 case sI:
1211 case sIN:
1212 case sINFI:
1213 case sINFIN:
1214 case sINFINI:
1215 case sINFINIT:
1216 #ifdef IEEE_FLOATING_POINT
1217 case sN:
1218 case sNA:
1219 case sNANPAREN:
1220 case sNANHEX:
1221 #endif
1222 Tcl_Panic("TclParseNumber: bad acceptState %d parsing '%s'",
1223 acceptState, bytes);
1224 case BINARY:
1225 shift = numTrailZeros;
1226 if (!significandOverflow && significandWide != 0 &&
1227 ((size_t)shift >= CHAR_BIT*sizeof(Tcl_WideUInt) ||
1228 significandWide > (MOST_BITS + signum) >> shift)) {
1229 significandOverflow = 1;
1230 TclBNInitBignumFromWideUInt(&significandBig, significandWide);
1231 }
1232 if (shift) {
1233 if (!significandOverflow) {
1234 /*
1235 * When the significand is 0, it is possible for the
1236 * amount to be shifted to equal or exceed the width
1237 * of the significand. Do not shift when the
1238 * significand is 0 to avoid undefined behavior.
1239 */
1240 if (significandWide != 0) {
1241 significandWide <<= shift;
1242 }
1243 } else {
1244 mp_mul_2d(&significandBig, shift, &significandBig);
1245 }
1246 }
1247 goto returnInteger;
1248
1249 case HEXADECIMAL:
1250 /*
1251 * Returning a hex integer. Final scaling step.
1252 */
1253
1254 shift = 4 * numTrailZeros;
1255 if (!significandOverflow && significandWide !=0 &&
1256 ((size_t)shift >= CHAR_BIT*sizeof(Tcl_WideUInt) ||
1257 significandWide > (MOST_BITS + signum) >> shift)) {
1258 significandOverflow = 1;
1259 TclBNInitBignumFromWideUInt(&significandBig, significandWide);
1260 }
1261 if (shift) {
1262 if (!significandOverflow) {
1263 /*
1264 * When the significand is 0, it is possible for the
1265 * amount to be shifted to equal or exceed the width
1266 * of the significand. Do not shift when the
1267 * significand is 0 to avoid undefined behavior.
1268 */
1269 if (significandWide != 0) {
1270 significandWide <<= shift;
1271 }
1272 } else {
1273 mp_mul_2d(&significandBig, shift, &significandBig);
1274 }
1275 }
1276 goto returnInteger;
1277
1278 case OCTAL:
1279 /*
1280 * Returning an octal integer. Final scaling step.
1281 */
1282
1283 shift = 3 * numTrailZeros;
1284 if (!octalSignificandOverflow && octalSignificandWide != 0 &&
1285 ((size_t)shift >= CHAR_BIT*sizeof(Tcl_WideUInt) ||
1286 octalSignificandWide > (MOST_BITS + signum) >> shift)) {
1287 octalSignificandOverflow = 1;
1288 TclBNInitBignumFromWideUInt(&octalSignificandBig,
1289 octalSignificandWide);
1290 }
1291 if (shift) {
1292 if (!octalSignificandOverflow) {
1293 /*
1294 * When the significand is 0, it is possible for the
1295 * amount to be shifted to equal or exceed the width
1296 * of the significand. Do not shift when the
1297 * significand is 0 to avoid undefined behavior.
1298 */
1299 if (octalSignificandWide != 0) {
1300 octalSignificandWide <<= shift;
1301 }
1302 } else {
1303 mp_mul_2d(&octalSignificandBig, shift,
1304 &octalSignificandBig);
1305 }
1306 }
1307 if (!octalSignificandOverflow) {
1308 if (octalSignificandWide >
1309 (Tcl_WideUInt)(((~(unsigned long)0) >> 1) + signum)) {
1310 #ifndef TCL_WIDE_INT_IS_LONG
1311 if (octalSignificandWide <= (MOST_BITS + signum)) {
1312 objPtr->typePtr = &tclWideIntType;
1313 if (signum) {
1314 objPtr->internalRep.wideValue =
1315 (Tcl_WideInt)(-octalSignificandWide);
1316 } else {
1317 objPtr->internalRep.wideValue =
1318 (Tcl_WideInt)octalSignificandWide;
1319 }
1320 break;
1321 }
1322 #endif
1323 TclBNInitBignumFromWideUInt(&octalSignificandBig,
1324 octalSignificandWide);
1325 octalSignificandOverflow = 1;
1326 } else {
1327 objPtr->typePtr = &tclIntType;
1328 if (signum) {
1329 objPtr->internalRep.longValue =
1330 (long) (-octalSignificandWide);
1331 } else {
1332 objPtr->internalRep.longValue =
1333 (long) octalSignificandWide;
1334 }
1335 }
1336 }
1337 if (octalSignificandOverflow) {
1338 if (signum) {
1339 (void)mp_neg(&octalSignificandBig, &octalSignificandBig);
1340 }
1341 TclSetBignumInternalRep(objPtr, &octalSignificandBig);
1342 }
1343 break;
1344
1345 case ZERO:
1346 case DECIMAL:
1347 significandOverflow = AccumulateDecimalDigit(0, numTrailZeros-1,
1348 &significandWide, &significandBig, significandOverflow);
1349 if (!significandOverflow && (significandWide > MOST_BITS+signum)) {
1350 significandOverflow = 1;
1351 TclBNInitBignumFromWideUInt(&significandBig, significandWide);
1352 }
1353 returnInteger:
1354 if (!significandOverflow) {
1355 if (significandWide >
1356 (Tcl_WideUInt)(((~(unsigned long)0) >> 1) + signum)) {
1357 #ifndef TCL_WIDE_INT_IS_LONG
1358 if (significandWide <= MOST_BITS+signum) {
1359 objPtr->typePtr = &tclWideIntType;
1360 if (signum) {
1361 objPtr->internalRep.wideValue =
1362 (Tcl_WideInt)(-significandWide);
1363 } else {
1364 objPtr->internalRep.wideValue =
1365 (Tcl_WideInt)significandWide;
1366 }
1367 break;
1368 }
1369 #endif
1370 TclBNInitBignumFromWideUInt(&significandBig,
1371 significandWide);
1372 significandOverflow = 1;
1373 } else {
1374 objPtr->typePtr = &tclIntType;
1375 if (signum) {
1376 objPtr->internalRep.longValue =
1377 (long) (-significandWide);
1378 } else {
1379 objPtr->internalRep.longValue =
1380 (long) significandWide;
1381 }
1382 }
1383 }
1384 if (significandOverflow) {
1385 if (signum) {
1386 (void)mp_neg(&significandBig, &significandBig);
1387 }
1388 TclSetBignumInternalRep(objPtr, &significandBig);
1389 }
1390 break;
1391
1392 case FRACTION:
1393 case EXPONENT:
1394
1395 /*
1396 * Here, we're parsing a floating-point number. 'significandWide'
1397 * or 'significandBig' contains the exact significand, according
1398 * to whether 'significandOverflow' is set. The desired floating
1399 * point value is significand * 10**k, where
1400 * k = numTrailZeros+exponent-numDigitsAfterDp.
1401 */
1402
1403 objPtr->typePtr = &tclDoubleType;
1404 if (exponentSignum) {
1405 /*
1406 * At this point exponent>=0, so the following calculation
1407 * cannot underflow.
1408 */
1409 exponent = -exponent;
1410 }
1411
1412 /*
1413 * Adjust the exponent for the number of trailing zeros that
1414 * have not been accumulated, and the number of digits after
1415 * the decimal point. Pin any overflow to INT_MAX/INT_MIN
1416 * respectively.
1417 */
1418
1419 if (exponent >= 0) {
1420 if (exponent - numDigitsAfterDp > INT_MAX - numTrailZeros) {
1421 exponent = INT_MAX;
1422 } else {
1423 exponent = exponent - numDigitsAfterDp + numTrailZeros;
1424 }
1425 } else {
1426 if (exponent + numTrailZeros < INT_MIN + numDigitsAfterDp) {
1427 exponent = INT_MIN;
1428 } else {
1429 exponent = exponent + numTrailZeros - numDigitsAfterDp;
1430 }
1431 }
1432
1433 /*
1434 * The desired number is now significandWide * 10**exponent
1435 * or significandBig * 10**exponent, depending on whether
1436 * the significand has overflowed a wide int.
1437 */
1438 if (!significandOverflow) {
1439 objPtr->internalRep.doubleValue = MakeLowPrecisionDouble(
1440 signum, significandWide, numSigDigs, exponent);
1441 } else {
1442 objPtr->internalRep.doubleValue = MakeHighPrecisionDouble(
1443 signum, &significandBig, numSigDigs, exponent);
1444 }
1445 break;
1446
1447 case sINF:
1448 case sINFINITY:
1449 if (signum) {
1450 objPtr->internalRep.doubleValue = -HUGE_VAL;
1451 } else {
1452 objPtr->internalRep.doubleValue = HUGE_VAL;
1453 }
1454 objPtr->typePtr = &tclDoubleType;
1455 break;
1456
1457 #ifdef IEEE_FLOATING_POINT
1458 case sNAN:
1459 case sNANFINISH:
1460 objPtr->internalRep.doubleValue = MakeNaN(signum, significandWide);
1461 objPtr->typePtr = &tclDoubleType;
1462 break;
1463 #endif
1464 case INITIAL:
1465 /* This case only to silence compiler warning. */
1466 Tcl_Panic("TclParseNumber: state INITIAL can't happen here");
1467 }
1468 }
1469
1470 /*
1471 * Format an error message when an invalid number is encountered.
1472 */
1473
1474 if (status != TCL_OK) {
1475 if (interp != NULL) {
1476 Tcl_Obj *msg = Tcl_ObjPrintf("expected %s but got \"",
1477 expected);
1478
1479 Tcl_AppendLimitedToObj(msg, bytes, numBytes, 50, "");
1480 Tcl_AppendToObj(msg, "\"", -1);
1481 if (state == BAD_OCTAL) {
1482 Tcl_AppendToObj(msg, " (looks like invalid octal number)", -1);
1483 }
1484 Tcl_SetObjResult(interp, msg);
1485 Tcl_SetErrorCode(interp, "TCL", "VALUE", "NUMBER", (char *)NULL);
1486 }
1487 }
1488
1489 /*
1490 * Free memory.
1491 */
1492
1493 if (octalSignificandOverflow) {
1494 mp_clear(&octalSignificandBig);
1495 }
1496 if (significandOverflow) {
1497 mp_clear(&significandBig);
1498 }
1499 return status;
1500 }
1501
1502 /*
1503 *----------------------------------------------------------------------
1504 *
1505 * AccumulateDecimalDigit --
1506 *
1507 * Consume a decimal digit in a number being scanned.
1508 *
1509 * Results:
1510 * Returns 1 if the number has overflowed to a bignum, 0 if it still fits
1511 * in a wide integer.
1512 *
1513 * Side effects:
1514 * Updates either the wide or bignum representation.
1515 *
1516 *----------------------------------------------------------------------
1517 */
1518
1519 static int
1520 AccumulateDecimalDigit(
1521 unsigned digit, /* Digit being scanned. */
1522 int numZeros, /* Count of zero digits preceding the digit
1523 * being scanned. */
1524 Tcl_WideUInt *wideRepPtr, /* Representation of the partial number as a
1525 * wide integer. */
1526 mp_int *bignumRepPtr, /* Representation of the partial number as a
1527 * bignum. */
1528 int bignumFlag) /* Flag == 1 if the number overflowed previous
1529 * to this digit. */
1530 {
1531 int i, n;
1532 Tcl_WideUInt w;
1533
1534 /*
1535 * Try wide multiplication first.
1536 */
1537
1538 if (!bignumFlag) {
1539 w = *wideRepPtr;
1540 if (w == 0) {
1541 /*
1542 * There's no need to multiply if the multiplicand is zero.
1543 */
1544
1545 *wideRepPtr = digit;
1546 return 0;
1547 } else if (numZeros >= maxpow10_wide
1548 || w > (UWIDE_MAX-digit)/pow10_wide[numZeros+1]) {
1549 /*
1550 * Wide multiplication will overflow. Expand the number to a
1551 * bignum and fall through into the bignum case.
1552 */
1553
1554 TclBNInitBignumFromWideUInt(bignumRepPtr, w);
1555 } else {
1556 /*
1557 * Wide multiplication.
1558 */
1559
1560 *wideRepPtr = w * pow10_wide[numZeros+1] + digit;
1561 return 0;
1562 }
1563 }
1564
1565 /*
1566 * Bignum multiplication.
1567 */
1568
1569 if (numZeros < log10_DIGIT_MAX) {
1570 /*
1571 * Up to about 8 zeros - single digit multiplication.
1572 */
1573
1574 mp_mul_d(bignumRepPtr, (mp_digit) pow10_wide[numZeros+1],
1575 bignumRepPtr);
1576 mp_add_d(bignumRepPtr, (mp_digit) digit, bignumRepPtr);
1577 } else {
1578 /*
1579 * More than single digit multiplication. Multiply by the appropriate
1580 * small powers of 5, and then shift. Large strings of zeroes are
1581 * eaten 256 at a time; this is less efficient than it could be, but
1582 * seems implausible. We presume that MP_DIGIT_BIT is at least 27. The
1583 * first multiplication, by up to 10**7, is done with a one-DIGIT
1584 * multiply (this presumes that MP_DIGIT_BIT >= 24).
1585 */
1586
1587 n = numZeros + 1;
1588 mp_mul_d(bignumRepPtr, (mp_digit) pow10_wide[n&0x7], bignumRepPtr);
1589 for (i=3; i<=7; ++i) {
1590 if (n & (1 << i)) {
1591 mp_mul(bignumRepPtr, pow5+i, bignumRepPtr);
1592 }
1593 }
1594 while (n >= 256) {
1595 mp_mul(bignumRepPtr, pow5+8, bignumRepPtr);
1596 n -= 256;
1597 }
1598 mp_mul_2d(bignumRepPtr, (int)(numZeros+1)&~0x7, bignumRepPtr);
1599 mp_add_d(bignumRepPtr, (mp_digit) digit, bignumRepPtr);
1600 }
1601
1602 return 1;
1603 }
1604
1605 /*
1606 *----------------------------------------------------------------------
1607 *
1608 * MakeLowPrecisionDouble --
1609 *
1610 * Makes the double precision number, signum*significand*10**exponent.
1611 *
1612 * Results:
1613 * Returns the constructed number.
1614 *
1615 * Common cases, where there are few enough digits that the number can be
1616 * represented with at most roundoff, are handled specially here. If the
1617 * number requires more than one rounded operation to compute, the code
1618 * promotes the significand to a bignum and calls MakeHighPrecisionDouble
1619 * to do it instead.
1620 *
1621 *----------------------------------------------------------------------
1622 */
1623
1624 static double
1625 MakeLowPrecisionDouble(
1626 int signum, /* 1 if the number is negative, 0 otherwise */
1627 Tcl_WideUInt significand, /* Significand of the number */
1628 int numSigDigs, /* Number of digits in the significand */
1629 int exponent) /* Power of ten */
1630 {
1631 TCL_IEEE_DOUBLE_ROUNDING_DECL
1632
1633 mp_int significandBig; /* Significand expressed as a bignum. */
1634
1635 /*
1636 * With gcc on x86, the floating point rounding mode is double-extended.
1637 * This causes the result of double-precision calculations to be rounded
1638 * twice: once to the precision of double-extended and then again to the
1639 * precision of double. Double-rounding introduces gratuitous errors of 1
1640 * ulp, so we need to change rounding mode to 53-bits. We also make
1641 * 'retval' volatile, so that it doesn't get promoted to a register.
1642 */
1643 volatile double retval; /* Value of the number. */
1644
1645 /*
1646 * Test for zero significand, which requires explicit construction
1647 * of -0.0. (Unary minus returns a positive zero.)
1648 */
1649 if (significand == 0) {
1650 return copysign(0.0, -signum);
1651 }
1652
1653 /*
1654 * Set the FP control word for 53 bits, WARNING: It must be reset
1655 * before returning.
1656 */
1657 TCL_IEEE_DOUBLE_ROUNDING;
1658
1659 if (numSigDigs <= QUICK_MAX) {
1660 if (exponent >= 0) {
1661 if (exponent <= mmaxpow) {
1662 /*
1663 * The significand is an exact integer, and so is
1664 * 10**exponent. The product will be correct to within 1/2 ulp
1665 * without special handling.
1666 */
1667
1668 retval =
1669 ((double)(Tcl_WideInt)significand * pow10vals[exponent]);
1670 goto returnValue;
1671 } else {
1672 int diff = QUICK_MAX - numSigDigs;
1673
1674 if (exponent-diff <= mmaxpow) {
1675 /*
1676 * 10**exponent is not an exact integer, but
1677 * 10**(exponent-diff) is exact, and so is
1678 * significand*10**diff, so we can still compute the value
1679 * with only one roundoff.
1680 */
1681
1682 volatile double factor =
1683 ((double)(Tcl_WideInt)significand * pow10vals[diff]);
1684 retval = factor * pow10vals[exponent-diff];
1685 goto returnValue;
1686 }
1687 }
1688 } else {
1689 if (exponent >= -mmaxpow) {
1690 /*
1691 * 10**-exponent is an exact integer, and so is the
1692 * significand. Compute the result by one division, again with
1693 * only one rounding.
1694 */
1695
1696 retval =
1697 ((double)(Tcl_WideInt)significand / pow10vals[-exponent]);
1698 goto returnValue;
1699 }
1700 }
1701 }
1702
1703 /*
1704 * All the easy cases have failed. Promote the significand to bignum and
1705 * call MakeHighPrecisionDouble to do it the hard way.
1706 */
1707
1708 TclBNInitBignumFromWideUInt(&significandBig, significand);
1709 retval = MakeHighPrecisionDouble(0, &significandBig, numSigDigs,
1710 exponent);
1711 mp_clear(&significandBig);
1712
1713 /*
1714 * Come here to return the computed value.
1715 */
1716
1717 returnValue:
1718 if (signum) {
1719 retval = -retval;
1720 }
1721
1722 /*
1723 * On gcc on x86, restore the floating point mode word.
1724 */
1725
1726 TCL_DEFAULT_DOUBLE_ROUNDING;
1727
1728 return retval;
1729 }
1730
1731 /*
1732 *----------------------------------------------------------------------
1733 *
1734 * MakeHighPrecisionDouble --
1735 *
1736 * Makes the double precision number, signum*significand*10**exponent.
1737 *
1738 * Results:
1739 * Returns the constructed number.
1740 *
1741 * MakeHighPrecisionDouble is used when arbitrary-precision arithmetic is
1742 * needed to ensure correct rounding. It begins by calculating a
1743 * low-precision approximation to the desired number, and then refines
1744 * the answer in high precision.
1745 *
1746 *----------------------------------------------------------------------
1747 */
1748
1749 static double
1750 MakeHighPrecisionDouble(
1751 int signum, /* 1=negative, 0=nonnegative */
1752 mp_int *significand, /* Exact significand of the number */
1753 int numSigDigs, /* Number of significant digits */
1754 int exponent) /* Power of 10 by which to multiply */
1755 {
1756 TCL_IEEE_DOUBLE_ROUNDING_DECL
1757
1758 int machexp; /* Machine exponent of a power of 10. */
1759 int shift, n;
1760 mp_int bntmp;
1761
1762 /*
1763 * With gcc on x86, the floating point rounding mode is double-extended.
1764 * This causes the result of double-precision calculations to be rounded
1765 * twice: once to the precision of double-extended and then again to the
1766 * precision of double. Double-rounding introduces gratuitous errors of 1
1767 * ulp, so we need to change rounding mode to 53-bits. We also make
1768 * 'retval' volatile to make sure that it doesn't get promoted to a
1769 * register.
1770 */
1771 volatile double retval;
1772
1773 /*
1774 * A zero significand requires explicit construction of -0.0.
1775 * (Unary minus returns positive zero.)
1776 */
1777 if (mp_iszero(significand)) {
1778 return copysign(0.0, -signum);
1779 }
1780
1781 /*
1782 * Set the 53-bit rounding mode. WARNING: It must be reset before
1783 * returning.
1784 */
1785 TCL_IEEE_DOUBLE_ROUNDING;
1786
1787 /*
1788 * Make quick checks for over/underflow. Be careful to avoid
1789 * integer overflow when calculating with 'exponent'.
1790 */
1791 if (exponent >= 0 && exponent-1 > maxDigits-numSigDigs) {
1792 retval = HUGE_VAL;
1793 goto returnValue;
1794 } else if (exponent < 0 && numSigDigs+exponent < minDigits+1) {
1795 retval = 0.0;
1796 goto returnValue;
1797 }
1798
1799 /*
1800 * Develop a first approximation to the significand. It is tempting simply
1801 * to force bignum to double, but that will overflow on input numbers like
1802 * 1.[string repeat 0 1000]1; while this is a not terribly likely
1803 * scenario, we still have to deal with it. Use fraction and exponent
1804 * instead. Once we have the significand, multiply by 10**exponent. Test
1805 * for overflow. Convert back to a double, and test for underflow.
1806 */
1807
1808 /*
1809 * TCL bug ca62367d61: the following two if-conditions handle the case,
1810 * if the mantissa is to long to be represented.
1811 * Very high numbers are returned, if this is not handled
1812 */
1813
1814
1815 if (exponent < -511) {
1816 mp_init_copy(&bntmp, significand);
1817 shift = -exponent - 511;
1818 exponent += shift;
1819 while (shift > 0) {
1820 n = (shift > 9) ? 9 : shift;
1821 mp_div_d(&bntmp, (mp_digit) pow10_wide[n], &bntmp, NULL);
1822 shift -= n;
1823 }
1824 significand = &bntmp;
1825 } else if (exponent > 511) {
1826 mp_init_copy(&bntmp, significand);
1827 shift = exponent - 511;
1828 exponent -= shift;
1829 while (shift > 0) {
1830 n = (shift > 9) ? 9 : shift;
1831 mp_mul_d(&bntmp, (mp_digit) pow10_wide[n], &bntmp);
1832 shift -= n;
1833 }
1834 significand = &bntmp;
1835 }
1836
1837 retval = BignumToBiasedFrExp(significand, &machexp);
1838 retval = Pow10TimesFrExp(exponent, retval, &machexp);
1839 if (machexp > DBL_MAX_EXP*log2FLT_RADIX) {
1840 retval = HUGE_VAL;
1841 goto returnValue;
1842 }
1843 retval = SafeLdExp(retval, machexp);
1844 if (tiny == 0.0) {
1845 tiny = SafeLdExp(1.0, DBL_MIN_EXP * log2FLT_RADIX - mantBits);
1846 }
1847 if (retval < tiny) {
1848 retval = tiny;
1849 }
1850
1851 /*
1852 * Refine the result twice. (The second refinement should be necessary
1853 * only if the best approximation is a power of 2 minus 1/2 ulp).
1854 */
1855
1856 retval = RefineApproximation(retval, significand, exponent);
1857 retval = RefineApproximation(retval, significand, exponent);
1858
1859 /*
1860 * Come here to return the computed value.
1861 */
1862
1863 returnValue:
1864 if (significand == &bntmp) {
1865 mp_clear(&bntmp);
1866 }
1867 if (signum) {
1868 retval = -retval;
1869 }
1870
1871 /*
1872 * On gcc on x86, restore the floating point mode word.
1873 */
1874
1875 TCL_DEFAULT_DOUBLE_ROUNDING;
1876
1877 return retval;
1878 }
1879
1880 /*
1881 *----------------------------------------------------------------------
1882 *
1883 * MakeNaN --
1884 *
1885 * Makes a "Not a Number" given a set of bits to put in the tag bits
1886 *
1887 * Note that a signalling NaN is never returned.
1888 *
1889 *----------------------------------------------------------------------
1890 */
1891
1892 #ifdef IEEE_FLOATING_POINT
1893 static double
1894 MakeNaN(
1895 int signum, /* Sign bit (1=negative, 0=nonnegative. */
1896 Tcl_WideUInt tags) /* Tag bits to put in the NaN. */
1897 {
1898 union {
1899 Tcl_WideUInt iv;
1900 double dv;
1901 } theNaN;
1902
1903 theNaN.iv = tags;
1904 theNaN.iv &= (((Tcl_WideUInt) 1) << 51) - 1;
1905 if (signum) {
1906 theNaN.iv |= ((Tcl_WideUInt) (0x8000 | NAN_START)) << 48;
1907 } else {
1908 theNaN.iv |= ((Tcl_WideUInt) NAN_START) << 48;
1909 }
1910 if (n770_fp) {
1911 theNaN.iv = Nokia770Twiddle(theNaN.iv);
1912 }
1913 return theNaN.dv;
1914 }
1915 #endif
1916
1917 /*
1918 *----------------------------------------------------------------------
1919 *
1920 * RefineApproximation --
1921 *
1922 * Given a poor approximation to a floating point number, returns a
1923 * better one. (The better approximation is correct to within 1 ulp, and
1924 * is entirely correct if the poor approximation is correct to 1 ulp.)
1925 *
1926 * Results:
1927 * Returns the improved result.
1928 *
1929 *----------------------------------------------------------------------
1930 */
1931
1932 static double
1933 RefineApproximation(
1934 double approxResult, /* Approximate result of conversion. */
1935 mp_int *exactSignificand, /* Integer significand. */
1936 int exponent) /* Power of 10 to multiply by significand. */
1937 {
1938 int M2, M5; /* Powers of 2 and of 5 needed to put the
1939 * decimal and binary numbers over a common
1940 * denominator. */
1941 double significand; /* Sigificand of the binary number. */
1942 int binExponent; /* Exponent of the binary number. */
1943 int msb; /* Most significant bit position of an
1944 * intermediate result. */
1945 int nDigits; /* Number of mp_digit's in an intermediate
1946 * result. */
1947 mp_int twoMv; /* Approx binary value expressed as an exact
1948 * integer scaled by the multiplier 2M. */
1949 mp_int twoMd; /* Exact decimal value expressed as an exact
1950 * integer scaled by the multiplier 2M. */
1951 int scale; /* Scale factor for M. */
1952 int multiplier; /* Power of two to scale M. */
1953 double num, den; /* Numerator and denominator of the correction
1954 * term. */
1955 double quot; /* Correction term. */
1956 double minincr; /* Lower bound on the absolute value of the
1957 * correction term. */
1958 int roundToEven = 0; /* Flag == TRUE if we need to invoke
1959 * "round to even" functionality */
1960 double rteSignificand; /* Significand of the round-to-even result */
1961 int rteExponent; /* Exponent of the round-to-even result */
1962 int shift; /* Shift count for converting numerator
1963 * and denominator of corrector to floating
1964 * point */
1965 Tcl_WideInt rteSigWide; /* Wide integer version of the significand
1966 * for testing evenness */
1967 int i;
1968
1969 /*
1970 * The first approximation is always low. If we find that it's HUGE_VAL,
1971 * we're done.
1972 */
1973
1974 if (approxResult == HUGE_VAL) {
1975 return approxResult;
1976 }
1977 significand = frexp(approxResult, &binExponent);
1978
1979 /*
1980 * We are trying to compute a corrector term that, when added to the
1981 * approximate result, will yield close to the exact result.
1982 * The exact result is exactSignificand * 10**exponent.
1983 * The approximate result is significand * 2**binExponent
1984 * If exponent<0, we need to multiply the exact value by 10**-exponent
1985 * to make it an integer, plus another factor of 2 to decide on rounding.
1986 * Similarly if binExponent<FP_PRECISION, we need
1987 * to multiply by 2**FP_PRECISION to make the approximate value an integer.
1988 *
1989 * Let M = 2**M2 * 5**M5 be the least common multiple of these two
1990 * multipliers.
1991 */
1992
1993 i = mantBits - binExponent;
1994 if (i < 0) {
1995 M2 = 0;
1996 } else {
1997 M2 = i;
1998 }
1999 if (exponent > 0) {
2000 M5 = 0;
2001 } else {
2002 M5 = -exponent;
2003 if (M5 - 1 > M2) {
2004 M2 = M5 - 1;
2005 }
2006 }
2007
2008 /*
2009 * Compute twoMv as 2*M*v, where v is the approximate value.
2010 * This is done by bit-whacking to calculate 2**(M2+1)*significand,
2011 * and then multiplying by 5**M5.
2012 */
2013
2014 msb = binExponent + M2; /* 1008 */
2015 nDigits = msb / MP_DIGIT_BIT + 1;
2016 mp_init_size(&twoMv, nDigits);
2017 i = (msb % MP_DIGIT_BIT + 1);
2018 twoMv.used = nDigits;
2019 significand *= SafeLdExp(1.0, i);
2020 while (--nDigits >= 0) {
2021 twoMv.dp[nDigits] = (mp_digit) significand;
2022 significand -= (mp_digit) significand;
2023 significand = SafeLdExp(significand, MP_DIGIT_BIT);
2024 }
2025 for (i = 0; i <= 8; ++i) {
2026 if (M5 & (1 << i)) {
2027 mp_mul(&twoMv, pow5+i, &twoMv);
2028 }
2029 }
2030
2031 /*
2032 * Compute twoMd as 2*M*d, where d is the exact value.
2033 * This is done by multiplying by 5**(M5+exponent) and then multiplying
2034 * by 2**(M5+exponent+1), which is, of course, a left shift.
2035 */
2036
2037 mp_init_copy(&twoMd, exactSignificand);
2038 for (i=0; i<=8; ++i) {
2039 if ((M5 + exponent) & (1 << i)) {
2040 mp_mul(&twoMd, pow5+i, &twoMd);
2041 }
2042 }
2043 mp_mul_2d(&twoMd, M2+exponent+1, &twoMd);
2044
2045 /*
2046 * Now let twoMd = twoMd - twoMv, the difference between the exact and
2047 * approximate values.
2048 */
2049
2050 mp_sub(&twoMd, &twoMv, &twoMd);
2051
2052 /*
2053 * The result, 2Mv-2Md, needs to be divided by 2M to yield a correction
2054 * term. Because 2M may well overflow a double, we need to scale the
2055 * denominator by a factor of 2**binExponent-mantBits. Place that factor
2056 * times 1/2 ULP into twoMd.
2057 */
2058
2059 scale = binExponent - mantBits - 1;
2060 mp_set(&twoMv, 1);
2061 for (i=0; i<=8; ++i) {
2062 if (M5 & (1 << i)) {
2063 mp_mul(&twoMv, pow5+i, &twoMv);
2064 }
2065 }
2066 multiplier = M2 + scale + 1;
2067 if (multiplier > 0) {
2068 mp_mul_2d(&twoMv, multiplier, &twoMv);
2069 } else if (multiplier < 0) {
2070 mp_div_2d(&twoMv, -multiplier, &twoMv, NULL);
2071 }
2072
2073 /*
2074 * Will the eventual correction term be less than, equal to, or
2075 * greater than 1/2 ULP?
2076 */
2077
2078 switch (mp_cmp_mag(&twoMd, &twoMv)) {
2079 case MP_LT:
2080 /*
2081 * If the error is less than 1/2 ULP, there's no correction to make.
2082 */
2083 mp_clear(&twoMd);
2084 mp_clear(&twoMv);
2085 return approxResult;
2086 case MP_EQ:
2087 /*
2088 * If the error is exactly 1/2 ULP, we need to round to even.
2089 */
2090 roundToEven = 1;
2091 break;
2092 case MP_GT:
2093 /*
2094 * We need to correct the result if the error exceeds 1/2 ULP.
2095 */
2096 break;
2097 }
2098
2099 /*
2100 * If we're in the 'round to even' case, and the significand is already
2101 * even, we're done. Return the approximate result.
2102 */
2103 if (roundToEven) {
2104 rteSignificand = frexp(approxResult, &rteExponent);
2105 rteSigWide = (Tcl_WideInt)ldexp(rteSignificand, FP_PRECISION);
2106 if ((rteSigWide & 1) == 0) {
2107 mp_clear(&twoMd);
2108 mp_clear(&twoMv);
2109 return approxResult;
2110 }
2111 }
2112
2113 /*
2114 * Reduce the numerator and denominator of the corrector term so that
2115 * they will fit in the floating point precision.
2116 */
2117 shift = mp_count_bits(&twoMv) - FP_PRECISION - 1;
2118 if (shift > 0) {
2119 mp_div_2d(&twoMv, shift, &twoMv, NULL);
2120 mp_div_2d(&twoMd, shift, &twoMd, NULL);
2121 }
2122
2123 /*
2124 * Convert the numerator and denominator of the corrector term accurately
2125 * to floating point numbers.
2126 */
2127
2128 num = TclBignumToDouble(&twoMd);
2129 den = TclBignumToDouble(&twoMv);
2130
2131 quot = SafeLdExp(num/den, scale);
2132 minincr = SafeLdExp(1.0, binExponent-mantBits);
2133
2134 if (quot<0. && quot>-minincr) {
2135 quot = -minincr;
2136 } else if (quot>0. && quot<minincr) {
2137 quot = minincr;
2138 }
2139
2140 mp_clear(&twoMd);
2141 mp_clear(&twoMv);
2142
2143 return approxResult + quot;
2144 }
2145
2146 /*
2147 *----------------------------------------------------------------------
2148 *
2149 * MultPow5 --
2150 *
2151 * Multiply a bignum by a power of 5.
2152 *
2153 * Side effects:
2154 * Stores base*5**n in result.
2155 *
2156 *----------------------------------------------------------------------
2157 */
2158
2159 static inline void
2160 MulPow5(
2161 mp_int *base, /* Number to multiply. */
2162 unsigned n, /* Power of 5 to multiply by. */
2163 mp_int *result) /* Place to store the result. */
2164 {
2165 mp_int *p = base;
2166 int n13 = n / 13;
2167 int r = n % 13;
2168
2169 if (r != 0) {
2170 mp_mul_d(p, dpow5[r], result);
2171 p = result;
2172 }
2173 r = 0;
2174 while (n13 != 0) {
2175 if (n13 & 1) {
2176 mp_mul(p, pow5_13+r, result);
2177 p = result;
2178 }
2179 n13 >>= 1;
2180 ++r;
2181 }
2182 if (p != result) {
2183 mp_copy(p, result);
2184 }
2185 }
2186
2187 /*
2188 *----------------------------------------------------------------------
2189 *
2190 * NormalizeRightward --
2191 *
2192 * Shifts a number rightward until it is odd (that is, until the least
2193 * significant bit is nonzero.
2194 *
2195 * Results:
2196 * Returns the number of bit positions by which the number was shifted.
2197 *
2198 * Side effects:
2199 * Shifts the number in place; *wPtr is replaced by the shifted number.
2200 *
2201 *----------------------------------------------------------------------
2202 */
2203
2204 static inline int
2205 NormalizeRightward(
2206 Tcl_WideUInt *wPtr) /* INOUT: Number to shift. */
2207 {
2208 int rv = 0;
2209 Tcl_WideUInt w = *wPtr;
2210
2211 if (!(w & (Tcl_WideUInt) 0xFFFFFFFF)) {
2212 w >>= 32; rv += 32;
2213 }
2214 if (!(w & (Tcl_WideUInt) 0xFFFF)) {
2215 w >>= 16; rv += 16;
2216 }
2217 if (!(w & (Tcl_WideUInt) 0xFF)) {
2218 w >>= 8; rv += 8;
2219 }
2220 if (!(w & (Tcl_WideUInt) 0xF)) {
2221 w >>= 4; rv += 4;
2222 }
2223 if (!(w & 0x3)) {
2224 w >>= 2; rv += 2;
2225 }
2226 if (!(w & 0x1)) {
2227 w >>= 1; ++rv;
2228 }
2229 *wPtr = w;
2230 return rv;
2231 }
2232
2233 /*
2234 *----------------------------------------------------------------------
2235 *
2236 * RequiredPrecision --
2237 *
2238 * Determines the number of bits needed to hold an integer.
2239 *
2240 * Results:
2241 * Returns the position of the most significant bit (1 - 64), starting
2242 * the counting at 1 for the LSB (RP(1) -> 1). Returns 0
2243 * if the number is zero.
2244 *
2245 *----------------------------------------------------------------------
2246 */
2247
2248 static int
2249 RequiredPrecision(
2250 Tcl_WideUInt w) /* Number to interrogate. */
2251 {
2252 int rv;
2253 unsigned int wi;
2254
2255 if (w & ((Tcl_WideUInt)0xFFFFFFFF << 32)) {
2256 wi = (unsigned int)(w >> 32); rv = 32;
2257 } else {
2258 wi = (unsigned int)w; rv = 0;
2259 }
2260 if (wi & 0xFFFF0000) {
2261 wi >>= 16; rv += 16;
2262 }
2263 if (wi & 0xFF00) {
2264 wi >>= 8; rv += 8;
2265 }
2266 if (wi & 0xF0) {
2267 wi >>= 4; rv += 4;
2268 }
2269 if (wi & 0xC) {
2270 wi >>= 2; rv += 2;
2271 }
2272 if (wi & 0x2) {
2273 wi >>= 1; ++rv;
2274 }
2275 if (wi & 0x1) {
2276 ++rv;
2277 }
2278 return rv;
2279 }
2280
2281 /*
2282 *----------------------------------------------------------------------
2283 *
2284 * DoubleToExpAndSig --
2285 *
2286 * Separates a 'double' into exponent and significand.
2287 *
2288 * Side effects:
2289 * Stores the significand in '*significand' and the exponent in '*expon'
2290 * so that dv == significand * 2.0**expon, and significand is odd. Also
2291 * stores the position of the leftmost 1-bit in 'significand' in 'bits'.
2292 *
2293 *----------------------------------------------------------------------
2294 */
2295
2296 static inline void
2297 DoubleToExpAndSig(
2298 double dv, /* Number to convert. */
2299 Tcl_WideUInt *significand, /* OUTPUT: Significand of the number. */
2300 int *expon, /* OUTPUT: Exponent to multiply the number
2301 * by. */
2302 int *bits) /* OUTPUT: Number of significant bits. */
2303 {
2304 Double d; /* Number being converted. */
2305 Tcl_WideUInt z; /* Significand under construction. */
2306 int de; /* Exponent of the number. */
2307 int k; /* Bit count. */
2308
2309 d.d = dv;
2310
2311 /*
2312 * Extract exponent and significand.
2313 */
2314
2315 de = (d.w.word0 & EXP_MASK) >> EXP_SHIFT;
2316 z = d.q & SIG_MASK;
2317 if (de != 0) {
2318 z |= HIDDEN_BIT;
2319 k = NormalizeRightward(&z);
2320 *bits = FP_PRECISION - k;
2321 *expon = k + (de - EXPONENT_BIAS) - (FP_PRECISION-1);
2322 } else {
2323 k = NormalizeRightward(&z);
2324 *expon = k + (de - EXPONENT_BIAS) - (FP_PRECISION-1) + 1;
2325 *bits = RequiredPrecision(z);
2326 }
2327 *significand = z;
2328 }
2329
2330 /*
2331 *----------------------------------------------------------------------
2332 *
2333 * TakeAbsoluteValue --
2334 *
2335 * Takes the absolute value of a 'double' including 0, Inf and NaN
2336 *
2337 * Side effects:
2338 * The 'double' in *d is replaced with its absolute value. The signum is
2339 * stored in 'sign': 1 for negative, 0 for nonnegative.
2340 *
2341 *----------------------------------------------------------------------
2342 */
2343
2344 static inline void
2345 TakeAbsoluteValue(
2346 Double *d, /* Number to replace with absolute value. */
2347 int *sign) /* Place to put the signum. */
2348 {
2349 if (d->w.word0 & SIGN_BIT) {
2350 *sign = 1;
2351 d->w.word0 &= ~SIGN_BIT;
2352 } else {
2353 *sign = 0;
2354 }
2355 }
2356
2357 /*
2358 *----------------------------------------------------------------------
2359 *
2360 * FormatInfAndNaN --
2361 *
2362 * Bailout for formatting infinities and Not-A-Number.
2363 *
2364 * Results:
2365 * Returns one of the strings 'Infinity' and 'NaN'. The string returned
2366 * must be freed by the caller using 'ckfree'.
2367 *
2368 * Side effects:
2369 * Stores 9999 in *decpt, and sets '*endPtr' to designate the terminating
2370 * NUL byte of the string if 'endPtr' is not NULL.
2371 *
2372 *----------------------------------------------------------------------
2373 */
2374
2375 static inline char *
2376 FormatInfAndNaN(
2377 Double *d, /* Exceptional number to format. */
2378 int *decpt, /* Decimal point to set to a bogus value. */
2379 char **endPtr) /* Pointer to the end of the formatted data */
2380 {
2381 char *retval;
2382
2383 *decpt = 9999;
2384 if (!(d->w.word1) && !(d->w.word0 & HI_ORDER_SIG_MASK)) {
2385 retval = (char *)ckalloc(9);
2386 strcpy(retval, "Infinity");
2387 if (endPtr) {
2388 *endPtr = retval + 8;
2389 }
2390 } else {
2391 retval = (char *)ckalloc(4);
2392 strcpy(retval, "NaN");
2393 if (endPtr) {
2394 *endPtr = retval + 3;
2395 }
2396 }
2397 return retval;
2398 }
2399
2400 /*
2401 *----------------------------------------------------------------------
2402 *
2403 * FormatZero --
2404 *
2405 * Bailout to format a zero floating-point number.
2406 *
2407 * Results:
2408 * Returns the constant string "0"
2409 *
2410 * Side effects:
2411 * Stores 1 in '*decpt' and puts a pointer to the NUL byte terminating
2412 * the string in '*endPtr' if 'endPtr' is not NULL.
2413 *
2414 *----------------------------------------------------------------------
2415 */
2416
2417 static inline char *
2418 FormatZero(
2419 int *decpt, /* Location of the decimal point. */
2420 char **endPtr) /* Pointer to the end of the formatted data */
2421 {
2422 char *retval = (char *)ckalloc(2);
2423
2424 strcpy(retval, "0");
2425 if (endPtr) {
2426 *endPtr = retval+1;
2427 }
2428 *decpt = 0;
2429 return retval;
2430 }
2431
2432 /*
2433 *----------------------------------------------------------------------
2434 *
2435 * ApproximateLog10 --
2436 *
2437 * Computes a two-term Taylor series approximation to the common log of a
2438 * number, and computes the number's binary log.
2439 *
2440 * Results:
2441 * Return an approximation to floor(log10(bw*2**be)) that is either exact
2442 * or 1 too high.
2443 *
2444 *----------------------------------------------------------------------
2445 */
2446
2447 static inline int
2448 ApproximateLog10(
2449 Tcl_WideUInt bw, /* Integer significand of the number. */
2450 int be, /* Power of two to scale bw. */
2451 int bbits) /* Number of bits of precision in bw. */
2452 {
2453 int i; /* Log base 2 of the number. */
2454 int k; /* Floor(Log base 10 of the number) */
2455 double ds; /* Mantissa of the number. */
2456 Double d2;
2457
2458 /*
2459 * Compute i and d2 such that d = d2*2**i, and 1 < d2 < 2.
2460 * Compute an approximation to log10(d),
2461 * log10(d) ~ log10(2) * i + log10(1.5)
2462 * + (significand-1.5)/(1.5 * log(10))
2463 */
2464
2465 d2.q = bw << (FP_PRECISION - bbits) & SIG_MASK;
2466 d2.w.word0 |= (EXPONENT_BIAS) << EXP_SHIFT;
2467 i = be + bbits - 1;
2468 ds = (d2.d - 1.5) * TWO_OVER_3LOG10
2469 + LOG10_3HALVES_PLUS_FUDGE + LOG10_2 * i;
2470 k = (int) ds;
2471 if (k > ds) {
2472 --k;
2473 }
2474 return k;
2475 }
2476
2477 /*
2478 *----------------------------------------------------------------------
2479 *
2480 * BetterLog10 --
2481 *
2482 * Improves the result of ApproximateLog10 for numbers in the range
2483 * 1 .. 10**(TEN_PMAX)-1
2484 *
2485 * Side effects:
2486 * Sets k_check to 0 if the new result is known to be exact, and to 1 if
2487 * it may still be one too high.
2488 *
2489 * Results:
2490 * Returns the improved approximation to log10(d).
2491 *
2492 *----------------------------------------------------------------------
2493 */
2494
2495 static inline int
2496 BetterLog10(
2497 double d, /* Original number to format. */
2498 int k, /* Characteristic(Log base 10) of the
2499 * number. */
2500 int *k_check) /* Flag == 1 if k is inexact. */
2501 {
2502 /*
2503 * Performance hack. If k is in the range 0..TEN_PMAX, then we can use a
2504 * powers-of-ten table to check it.
2505 */
2506
2507 if (k >= 0 && k <= TEN_PMAX) {
2508 if (d < tens[k]) {
2509 k--;
2510 }
2511 *k_check = 0;
2512 } else {
2513 *k_check = 1;
2514 }
2515 return k;
2516 }
2517
2518 /*
2519 *----------------------------------------------------------------------
2520 *
2521 * ComputeScale --
2522 *
2523 * Prepares to format a floating-point number as decimal.
2524 *
2525 * Parameters:
2526 * floor(log10*x) is k (or possibly k-1). floor(log2(x) is i. The
2527 * significand of x requires bbits bits to represent.
2528 *
2529 * Results:
2530 * Determines integers b2, b5, s2, s5 so that sig*2**b2*5**b5/2**s2*2**s5
2531 * exactly represents the value of the x/10**k. This value will lie in
2532 * the range [1 .. 10), and allows for computing successive digits by
2533 * multiplying sig%10 by 10.
2534 *
2535 *----------------------------------------------------------------------
2536 */
2537
2538 static inline void
2539 ComputeScale(
2540 int be, /* Exponent part of number: d = bw * 2**be. */
2541 int k, /* Characteristic of log10(number). */
2542 int *b2, /* OUTPUT: Power of 2 in the numerator. */
2543 int *b5, /* OUTPUT: Power of 5 in the numerator. */
2544 int *s2, /* OUTPUT: Power of 2 in the denominator. */
2545 int *s5) /* OUTPUT: Power of 5 in the denominator. */
2546 {
2547 /*
2548 * Scale numerator and denominator powers of 2 so that the input binary
2549 * number is the ratio of integers.
2550 */
2551
2552 if (be <= 0) {
2553 *b2 = 0;
2554 *s2 = -be;
2555 } else {
2556 *b2 = be;
2557 *s2 = 0;
2558 }
2559
2560 /*
2561 * Scale numerator and denominator so that the output decimal number is
2562 * the ratio of integers.
2563 */
2564
2565 if (k >= 0) {
2566 *b5 = 0;
2567 *s5 = k;
2568 *s2 += k;
2569 } else {
2570 *b2 -= k;
2571 *b5 = -k;
2572 *s5 = 0;
2573 }
2574 }
2575
2576 /*
2577 *----------------------------------------------------------------------
2578 *
2579 * SetPrecisionLimits --
2580 *
2581 * Determines how many digits of significance should be computed (and,
2582 * hence, how much memory need be allocated) for formatting a floating
2583 * point number.
2584 *
2585 * Given that 'k' is floor(log10(x)):
2586 * if 'shortest' format is used, there will be at most 18 digits in the
2587 * result.
2588 * if 'F' format is used, there will be at most 'ndigits' + k + 1 digits
2589 * if 'E' format is used, there will be exactly 'ndigits' digits.
2590 *
2591 * Side effects:
2592 * Adjusts '*ndigitsPtr' to have a valid value. Stores the maximum memory
2593 * allocation needed in *iPtr. Sets '*iLimPtr' to the limiting number of
2594 * digits to convert if k has been guessed correctly, and '*iLim1Ptr' to
2595 * the limiting number of digits to convert if k has been guessed to be
2596 * one too high.
2597 *
2598 *----------------------------------------------------------------------
2599 */
2600
2601 static inline void
2602 SetPrecisionLimits(
2603 int convType, /* Type of conversion: TCL_DD_SHORTEST,
2604 * TCL_DD_STEELE0, TCL_DD_E_FMT,
2605 * TCL_DD_F_FMT. */
2606 int k, /* Floor(log10(number to convert)) */
2607 int *ndigitsPtr, /* IN/OUT: Number of digits requested (will be
2608 * adjusted if needed). */
2609 int *iPtr, /* OUT: Maximum number of digits to return. */
2610 int *iLimPtr, /* OUT: Number of digits of significance if
2611 * the bignum method is used.*/
2612 int *iLim1Ptr) /* OUT: Number of digits of significance if
2613 * the quick method is used. */
2614 {
2615 switch (convType) {
2616 case TCL_DD_SHORTEST0:
2617 case TCL_DD_STEELE0:
2618 *iLimPtr = *iLim1Ptr = -1;
2619 *iPtr = 18;
2620 *ndigitsPtr = 0;
2621 break;
2622 case TCL_DD_E_FORMAT:
2623 if (*ndigitsPtr <= 0) {
2624 *ndigitsPtr = 1;
2625 }
2626 *iLimPtr = *iLim1Ptr = *iPtr = *ndigitsPtr;
2627 break;
2628 case TCL_DD_F_FORMAT:
2629 *iPtr = *ndigitsPtr + k + 1;
2630 *iLimPtr = *iPtr;
2631 *iLim1Ptr = *iPtr - 1;
2632 if (*iPtr <= 0) {
2633 *iPtr = 1;
2634 }
2635 break;
2636 default:
2637 *iPtr = -1;
2638 *iLimPtr = -1;
2639 *iLim1Ptr = -1;
2640 Tcl_Panic("impossible conversion type in TclDoubleDigits");
2641 }
2642 }
2643
2644 /*
2645 *----------------------------------------------------------------------
2646 *
2647 * BumpUp --
2648 *
2649 * Increases a string of digits ending in a series of nines to designate
2650 * the next higher number. xxxxb9999... -> xxxx(b+1)0000...
2651 *
2652 * Results:
2653 * Returns a pointer to the end of the adjusted string.
2654 *
2655 * Side effects:
2656 * In the case that the string consists solely of '999999', sets it to
2657 * "1" and moves the decimal point (*kPtr) one place to the right.
2658 *
2659 *----------------------------------------------------------------------
2660 */
2661
2662 static inline char *
2663 BumpUp(
2664 char *s, /* Cursor pointing one past the end of the
2665 * string. */
2666 char *retval, /* Start of the string of digits. */
2667 int *kPtr) /* Position of the decimal point. */
2668 {
2669 while (*--s == '9') {
2670 if (s == retval) {
2671 ++(*kPtr);
2672 *s = '1';
2673 return s+1;
2674 }
2675 }
2676 ++*s;
2677 ++s;
2678 return s;
2679 }
2680
2681 /*
2682 *----------------------------------------------------------------------
2683 *
2684 * AdjustRange --
2685 *
2686 * Rescales a 'double' in preparation for formatting it using the 'quick'
2687 * double-to-string method.
2688 *
2689 * Results:
2690 * Returns the precision that has been lost in the prescaling as a count
2691 * of units in the least significant place.
2692 *
2693 *----------------------------------------------------------------------
2694 */
2695
2696 static inline int
2697 AdjustRange(
2698 double *dPtr, /* INOUT: Number to adjust. */
2699 int k) /* IN: floor(log10(d)) */
2700 {
2701 int ieps; /* Number of roundoff errors that have
2702 * accumulated. */
2703 double d = *dPtr; /* Number to adjust. */
2704 double ds;
2705 int i, j, j1;
2706
2707 ieps = 2;
2708
2709 if (k > 0) {
2710 /*
2711 * The number must be reduced to bring it into range.
2712 */
2713
2714 ds = tens[k & 0xF];
2715 j = k >> 4;
2716 if (j & BLETCH) {
2717 j &= (BLETCH-1);
2718 d /= bigtens[N_BIGTENS - 1];
2719 ieps++;
2720 }
2721 i = 0;
2722 for (; j != 0; j>>=1) {
2723 if (j & 1) {
2724 ds *= bigtens[i];
2725 ++ieps;
2726 }
2727 ++i;
2728 }
2729 d /= ds;
2730 } else if ((j1 = -k) != 0) {
2731 /*
2732 * The number must be increased to bring it into range.
2733 */
2734
2735 d *= tens[j1 & 0xF];
2736 i = 0;
2737 for (j = j1>>4; j; j>>=1) {
2738 if (j & 1) {
2739 ieps++;
2740 d *= bigtens[i];
2741 }
2742 ++i;
2743 }
2744 }
2745
2746 *dPtr = d;
2747 return ieps;
2748 }
2749
2750 /*
2751 *----------------------------------------------------------------------
2752 *
2753 * ShorteningQuickFormat --
2754 *
2755 * Returns a 'quick' format of a double precision number to a string of
2756 * digits, preferring a shorter string of digits if the shorter string is
2757 * still within 1/2 ulp of the number.
2758 *
2759 * Results:
2760 * Returns the string of digits. Returns NULL if the 'quick' method fails
2761 * and the bignum method must be used.
2762 *
2763 * Side effects:
2764 * Stores the position of the decimal point at '*kPtr'.
2765 *
2766 *----------------------------------------------------------------------
2767 */
2768
2769 static inline char *
2770 ShorteningQuickFormat(
2771 double d, /* Number to convert. */
2772 int k, /* floor(log10(d)) */
2773 int ilim, /* Number of significant digits to return. */
2774 double eps, /* Estimated roundoff error. */
2775 char *retval, /* Buffer to receive the digit string. */
2776 int *kPtr) /* Pointer to stash the position of the
2777 * decimal point. */
2778 {
2779 char *s = retval; /* Cursor in the return value. */
2780 int digit; /* Current digit. */
2781 int i;
2782
2783 eps = 0.5 / tens[ilim-1] - eps;
2784 i = 0;
2785 for (;;) {
2786 /*
2787 * Convert a digit.
2788 */
2789
2790 digit = (int) d;
2791 d -= digit;
2792 *s++ = '0' + (char)digit;
2793
2794 /*
2795 * Truncate the conversion if the string of digits is within 1/2 ulp
2796 * of the actual value.
2797 */
2798
2799 if (d < eps) {
2800 *kPtr = k;
2801 return s;
2802 }
2803 if ((1. - d) < eps) {
2804 *kPtr = k;
2805 return BumpUp(s, retval, kPtr);
2806 }
2807
2808 /*
2809 * Bail out if the conversion fails to converge to a sufficiently
2810 * precise value.
2811 */
2812
2813 if (++i >= ilim) {
2814 return NULL;
2815 }
2816
2817 /*
2818 * Bring the next digit to the integer part.
2819 */
2820
2821 eps *= 10;
2822 d *= 10.0;
2823 }
2824 }
2825
2826 /*
2827 *----------------------------------------------------------------------
2828 *
2829 * StrictQuickFormat --
2830 *
2831 * Convert a double precision number of a string of a precise number of
2832 * digits, using the 'quick' double precision method.
2833 *
2834 * Results:
2835 * Returns the digit string, or NULL if the bignum method must be used to
2836 * do the formatting.
2837 *
2838 * Side effects:
2839 * Stores the position of the decimal point in '*kPtr'.
2840 *
2841 *----------------------------------------------------------------------
2842 */
2843
2844 static inline char *
2845 StrictQuickFormat(
2846 double d, /* Number to convert. */
2847 int k, /* floor(log10(d)) */
2848 int ilim, /* Number of significant digits to return. */
2849 double eps, /* Estimated roundoff error. */
2850 char *retval, /* Start of the digit string. */
2851 int *kPtr) /* Pointer to stash the position of the
2852 * decimal point. */
2853 {
2854 char *s = retval; /* Cursor in the return value. */
2855 int digit; /* Current digit of the answer. */
2856 int i;
2857
2858 eps *= tens[ilim-1];
2859 i = 1;
2860 for (;;) {
2861 /*
2862 * Extract a digit.
2863 */
2864
2865 digit = (int)d;
2866 d -= digit;
2867 if (d == 0.0) {
2868 ilim = i;
2869 }
2870 *s++ = '0' + (char)digit;
2871
2872 /*
2873 * When the given digit count is reached, handle trailing strings of 0
2874 * and 9.
2875 */
2876
2877 if (i == ilim) {
2878 if (d > 0.5 + eps) {
2879 *kPtr = k;
2880 return BumpUp(s, retval, kPtr);
2881 } else if (d < 0.5 - eps) {
2882 while (*--s == '0') {
2883 /* do nothing */
2884 }
2885 s++;
2886 *kPtr = k;
2887 return s;
2888 } else {
2889 return NULL;
2890 }
2891 }
2892
2893 /*
2894 * Advance to the next digit.
2895 */
2896
2897 ++i;
2898 d *= 10.0;
2899 }
2900 }
2901
2902 /*
2903 *----------------------------------------------------------------------
2904 *
2905 * QuickConversion --
2906 *
2907 * Converts a floating point number the 'quick' way, when only a limited
2908 * number of digits is required and floating point arithmetic can
2909 * therefore be used for the intermediate results.
2910 *
2911 * Results:
2912 * Returns the converted string, or NULL if the bignum method must be
2913 * used.
2914 *
2915 *----------------------------------------------------------------------
2916 */
2917
2918 static inline char *
2919 QuickConversion(
2920 double e, /* Number to format. */
2921 int k, /* floor(log10(d)), approximately. */
2922 int k_check, /* 0 if k is exact, 1 if it may be too high */
2923 int flags, /* Flags passed to dtoa:
2924 * TCL_DD_SHORTEN_FLAG */
2925 int len, /* Length of the return value. */
2926 int ilim, /* Number of digits to store. */
2927 int ilim1, /* Number of digits to store if we misguessed
2928 * k. */
2929 int *decpt, /* OUTPUT: Location of the decimal point. */
2930 char **endPtr) /* OUTPUT: Pointer to the terminal null
2931 * byte. */
2932 {
2933 int ieps; /* Number of 1-ulp roundoff errors that have
2934 * accumulated in the calculation. */
2935 Double eps; /* Estimated roundoff error. */
2936 char *retval; /* Returned string. */
2937 char *end; /* Pointer to the terminal null byte in the
2938 * returned string. */
2939 volatile double d; /* Workaround for a bug in mingw gcc 3.4.5 */
2940
2941 /*
2942 * Bring d into the range [1 .. 10).
2943 */
2944
2945 ieps = AdjustRange(&e, k);
2946 d = e;
2947
2948 /*
2949 * If the guessed value of k didn't get d into range, adjust it by one. If
2950 * that leaves us outside the range in which quick format is accurate,
2951 * bail out.
2952 */
2953
2954 if (k_check && d < 1. && ilim > 0) {
2955 if (ilim1 < 0) {
2956 return NULL;
2957 }
2958 ilim = ilim1;
2959 --k;
2960 d = d * 10.0;
2961 ++ieps;
2962 }
2963
2964 /*
2965 * Compute estimated roundoff error.
2966 */
2967
2968 eps.d = ieps * d + 7.;
2969 eps.w.word0 -= (FP_PRECISION-1) << EXP_SHIFT;
2970
2971 /*
2972 * Handle the peculiar case where the result has no significant digits.
2973 */
2974
2975 retval = (char *)ckalloc(len + 1);
2976 if (ilim == 0) {
2977 d = d - 5.;
2978 if (d > eps.d) {
2979 *retval = '1';
2980 *decpt = k;
2981 return retval;
2982 } else if (d < -eps.d) {
2983 *decpt = k;
2984 return retval;
2985 } else {
2986 ckfree(retval);
2987 return NULL;
2988 }
2989 }
2990
2991 /*
2992 * Format the digit string.
2993 */
2994
2995 if (flags & TCL_DD_SHORTEN_FLAG) {
2996 end = ShorteningQuickFormat(d, k, ilim, eps.d, retval, decpt);
2997 } else {
2998 end = StrictQuickFormat(d, k, ilim, eps.d, retval, decpt);
2999 }
3000 if (end == NULL) {
3001 ckfree(retval);
3002 return NULL;
3003 }
3004 *end = '\0';
3005 if (endPtr != NULL) {
3006 *endPtr = end;
3007 }
3008 return retval;
3009 }
3010
3011 /*
3012 *----------------------------------------------------------------------
3013 *
3014 * CastOutPowersOf2 --
3015 *
3016 * Adjust the factors 'b2', 'm2', and 's2' to cast out common powers of 2
3017 * from numerator and denominator in preparation for the 'bignum' method
3018 * of floating point conversion.
3019 *
3020 *----------------------------------------------------------------------
3021 */
3022
3023 static inline void
3024 CastOutPowersOf2(
3025 int *b2, /* Power of 2 to multiply the significand. */
3026 int *m2, /* Power of 2 to multiply 1/2 ulp. */
3027 int *s2) /* Power of 2 to multiply the common
3028 * denominator. */
3029 {
3030 int i;
3031
3032 if (*m2 > 0 && *s2 > 0) { /* Find the smallest power of 2 in the
3033 * numerator. */
3034 if (*m2 < *s2) { /* Find the lowest common denominator. */
3035 i = *m2;
3036 } else {
3037 i = *s2;
3038 }
3039 *b2 -= i; /* Reduce to lowest terms. */
3040 *m2 -= i;
3041 *s2 -= i;
3042 }
3043 }
3044
3045 /*
3046 *----------------------------------------------------------------------
3047 *
3048 * ShorteningInt64Conversion --
3049 *
3050 * Converts a double-precision number to the shortest string of digits
3051 * that reconverts exactly to the given number, or to 'ilim' digits if
3052 * that will yield a shorter result. The numerator and denominator in
3053 * David Gay's conversion algorithm are known to fit in Tcl_WideUInt,
3054 * giving considerably faster arithmetic than mp_int's.
3055 *
3056 * Results:
3057 * Returns the string of significant decimal digits, in newly allocated
3058 * memory
3059 *
3060 * Side effects:
3061 * Stores the location of the decimal point in '*decpt' and the location
3062 * of the terminal null byte in '*endPtr'.
3063 *
3064 *----------------------------------------------------------------------
3065 */
3066
3067 static inline char *
3068 ShorteningInt64Conversion(
3069 Double *dPtr, /* Original number to convert. */
3070 int convType, /* Type of conversion (shortest, Steele,
3071 * E format, F format). */
3072 Tcl_WideUInt bw, /* Integer significand. */
3073 int b2, int b5, /* Scale factor for the significand in the
3074 * numerator. */
3075 int m2plus, int m2minus, int m5,
3076 /* Scale factors for 1/2 ulp in the numerator
3077 * (will be different if bw == 1. */
3078 int s2, int s5, /* Scale factors for the denominator. */
3079 int k, /* Number of output digits before the decimal
3080 * point. */
3081 int len, /* Number of digits to allocate. */
3082 int ilim, /* Number of digits to convert if b >= s */
3083 int ilim1, /* Number of digits to convert if b < s */
3084 int *decpt, /* OUTPUT: Position of the decimal point. */
3085 char **endPtr) /* OUTPUT: Position of the terminal '\0' at
3086 * the end of the returned string. */
3087 {
3088 char *retval = (char *)ckalloc(len + 1);
3089 /* Output buffer. */
3090 Tcl_WideUInt b = (bw * wuipow5[b5]) << b2;
3091 /* Numerator of the fraction being
3092 * converted. */
3093 Tcl_WideUInt S = wuipow5[s5] << s2;
3094 /* Denominator of the fraction being
3095 * converted. */
3096 Tcl_WideUInt mplus, mminus; /* Ranges for testing whether the result is
3097 * within roundoff of being exact. */
3098 int digit; /* Current output digit. */
3099 char *s = retval; /* Cursor in the output buffer. */
3100 int i; /* Current position in the output buffer. */
3101
3102 /*
3103 * Adjust if the logarithm was guessed wrong.
3104 */
3105
3106 if (b < S) {
3107 b = 10 * b;
3108 ++m2plus; ++m2minus; ++m5;
3109 ilim = ilim1;
3110 --k;
3111 }
3112
3113 /*
3114 * Compute roundoff ranges.
3115 */
3116
3117 mplus = wuipow5[m5] << m2plus;
3118 mminus = wuipow5[m5] << m2minus;
3119
3120 /*
3121 * Loop through the digits.
3122 */
3123
3124 i = 1;
3125 for (;;) {
3126 digit = (int)(b / S);
3127 if (digit > 10) {
3128 Tcl_Panic("wrong digit!");
3129 }
3130 b = b % S;
3131
3132 /*
3133 * Does the current digit put us on the low side of the exact value
3134 * but within roundoff of being exact?
3135 */
3136
3137 if (b < mplus || (b == mplus
3138 && convType != TCL_DD_STEELE0 && (dPtr->w.word1 & 1) == 0)) {
3139 /*
3140 * Make sure we shouldn't be rounding *up* instead, in case the
3141 * next number above is closer.
3142 */
3143
3144 if (2 * b > S || (2 * b == S && (digit & 1) != 0)) {
3145 ++digit;
3146 if (digit == 10) {
3147 *s++ = '9';
3148 s = BumpUp(s, retval, &k);
3149 break;
3150 }
3151 }
3152
3153 /*
3154 * Stash the current digit.
3155 */
3156
3157 *s++ = '0' + (char)digit;
3158 break;
3159 }
3160
3161 /*
3162 * Does one plus the current digit put us within roundoff of the
3163 * number?
3164 */
3165
3166 if (b > S - mminus || (b == S - mminus
3167 && convType != TCL_DD_STEELE0 && (dPtr->w.word1 & 1) == 0)) {
3168 if (digit == 9) {
3169 *s++ = '9';
3170 s = BumpUp(s, retval, &k);
3171 break;
3172 }
3173 ++digit;
3174 *s++ = '0' + (char)digit;
3175 break;
3176 }
3177
3178 /*
3179 * Have we converted all the requested digits?
3180 */
3181
3182 *s++ = '0' + (char)digit;
3183 if (i == ilim) {
3184 if (2*b > S || (2*b == S && (digit & 1) != 0)) {
3185 s = BumpUp(s, retval, &k);
3186 }
3187 break;
3188 }
3189
3190 /*
3191 * Advance to the next digit.
3192 */
3193
3194 b = 10 * b;
3195 mplus = 10 * mplus;
3196 mminus = 10 * mminus;
3197 ++i;
3198 }
3199
3200 /*
3201 * Endgame - store the location of the decimal point and the end of the
3202 * string.
3203 */
3204
3205 *s = '\0';
3206 *decpt = k;
3207 if (endPtr) {
3208 *endPtr = s;
3209 }
3210 return retval;
3211 }
3212
3213 /*
3214 *----------------------------------------------------------------------
3215 *
3216 * StrictInt64Conversion --
3217 *
3218 * Converts a double-precision number to a fixed-length string of 'ilim'
3219 * digits that reconverts exactly to the given number. ('ilim' should be
3220 * replaced with 'ilim1' in the case where log10(d) has been
3221 * overestimated). The numerator and denominator in David Gay's
3222 * conversion algorithm are known to fit in Tcl_WideUInt, giving
3223 * considerably faster arithmetic than mp_int's.
3224 *
3225 * Results:
3226 * Returns the string of significant decimal digits, in newly allocated
3227 * memory
3228 *
3229 * Side effects:
3230 * Stores the location of the decimal point in '*decpt' and the location
3231 * of the terminal null byte in '*endPtr'.
3232 *
3233 *----------------------------------------------------------------------
3234 */
3235
3236 static inline char *
3237 StrictInt64Conversion(
3238 Tcl_WideUInt bw, /* Integer significand. */
3239 int b2, int b5, /* Scale factor for the significand in the
3240 * numerator. */
3241 int s2, int s5, /* Scale factors for the denominator. */
3242 int k, /* Number of output digits before the decimal
3243 * point. */
3244 int len, /* Number of digits to allocate. */
3245 int ilim, /* Number of digits to convert if b >= s */
3246 int ilim1, /* Number of digits to convert if b < s */
3247 int *decpt, /* OUTPUT: Position of the decimal point. */
3248 char **endPtr) /* OUTPUT: Position of the terminal '\0' at
3249 * the end of the returned string. */
3250 {
3251 char *retval = (char *)ckalloc(len + 1);
3252 /* Output buffer. */
3253 Tcl_WideUInt b = (bw * wuipow5[b5]) << b2;
3254 /* Numerator of the fraction being
3255 * converted. */
3256 Tcl_WideUInt S = wuipow5[s5] << s2;
3257 /* Denominator of the fraction being
3258 * converted. */
3259 int digit; /* Current output digit. */
3260 char *s = retval; /* Cursor in the output buffer. */
3261 int i; /* Current position in the output buffer. */
3262
3263 /*
3264 * Adjust if the logarithm was guessed wrong.
3265 */
3266
3267 if (b < S) {
3268 b = 10 * b;
3269 ilim = ilim1;
3270 --k;
3271 }
3272
3273 /*
3274 * Loop through the digits.
3275 */
3276
3277 i = 1;
3278 for (;;) {
3279 digit = (int)(b / S);
3280 if (digit > 10) {
3281 Tcl_Panic("wrong digit!");
3282 }
3283 b = b % S;
3284
3285 /*
3286 * Have we converted all the requested digits?
3287 */
3288
3289 *s++ = '0' + (char)digit;
3290 if (i == ilim) {
3291 if (2*b > S || (2*b == S && (digit & 1) != 0)) {
3292 s = BumpUp(s, retval, &k);
3293 } else {
3294 while (*--s == '0') {
3295 /* do nothing */
3296 }
3297 ++s;
3298 }
3299 break;
3300 }
3301
3302 /*
3303 * Advance to the next digit.
3304 */
3305
3306 b = 10 * b;
3307 ++i;
3308 }
3309
3310 /*
3311 * Endgame - store the location of the decimal point and the end of the
3312 * string.
3313 */
3314
3315 *s = '\0';
3316 *decpt = k;
3317 if (endPtr) {
3318 *endPtr = s;
3319 }
3320 return retval;
3321 }
3322
3323 /*
3324 *----------------------------------------------------------------------
3325 *
3326 * ShouldBankerRoundUpPowD --
3327 *
3328 * Test whether bankers' rounding should round a digit up. Assumption is
3329 * made that the denominator of the fraction being tested is a power of
3330 * 2**MP_DIGIT_BIT.
3331 *
3332 * Results:
3333 * Returns 1 iff the fraction is more than 1/2, or if the fraction is
3334 * exactly 1/2 and the digit is odd.
3335 *
3336 *----------------------------------------------------------------------
3337 */
3338
3339 static inline int
3340 ShouldBankerRoundUpPowD(
3341 mp_int *b, /* Numerator of the fraction. */
3342 int sd, /* Denominator is 2**(sd*MP_DIGIT_BIT). */
3343 int isodd) /* 1 if the digit is odd, 0 if even. */
3344 {
3345 int i;
3346 static const mp_digit topbit = ((mp_digit)1) << (MP_DIGIT_BIT - 1);
3347
3348 if (b->used < sd || (b->dp[sd-1] & topbit) == 0) {
3349 return 0;
3350 }
3351 if (b->dp[sd-1] != topbit) {
3352 return 1;
3353 }
3354 for (i = sd-2; i >= 0; --i) {
3355 if (b->dp[i] != 0) {
3356 return 1;
3357 }
3358 }
3359 return isodd;
3360 }
3361
3362 /*
3363 *----------------------------------------------------------------------
3364 *
3365 * ShouldBankerRoundUpToNextPowD --
3366 *
3367 * Tests whether bankers' rounding will round down in the "denominator is
3368 * a power of 2**MP_DIGIT" case.
3369 *
3370 * Results:
3371 * Returns 1 if the rounding will be performed - which increases the
3372 * digit by one - and 0 otherwise.
3373 *
3374 *----------------------------------------------------------------------
3375 */
3376
3377 static inline int
3378 ShouldBankerRoundUpToNextPowD(
3379 mp_int *b, /* Numerator of the fraction. */
3380 mp_int *m, /* Numerator of the rounding tolerance. */
3381 int sd, /* Common denominator is 2**(sd*MP_DIGIT_BIT). */
3382 int convType, /* Conversion type: STEELE defeats
3383 * round-to-even (not sure why one wants to do
3384 * this; I copied it from Gay). FIXME */
3385 int isodd, /* 1 if the integer significand is odd. */
3386 mp_int *temp) /* Work area for the calculation. */
3387 {
3388 int i;
3389
3390 /*
3391 * Compare B and S-m - which is the same as comparing B+m and S - which we
3392 * do by computing b+m and doing a bitwhack compare against
3393 * 2**(MP_DIGIT_BIT*sd)
3394 */
3395
3396 mp_add(b, m, temp);
3397 if (temp->used <= sd) { /* Too few digits to be > s */
3398 return 0;
3399 }
3400 if (temp->used > sd+1 || temp->dp[sd] > 1) {
3401 /* >= 2s */
3402 return 1;
3403 }
3404 for (i = sd-1; i >= 0; --i) {
3405 /* Check for ==s */
3406 if (temp->dp[i] != 0) { /* > s */
3407 return 1;
3408 }
3409 }
3410 if (convType == TCL_DD_STEELE0) {
3411 /* Biased rounding. */
3412 return 0;
3413 }
3414 return isodd;
3415 }
3416
3417 /*
3418 *----------------------------------------------------------------------
3419 *
3420 * ShorteningBignumConversionPowD --
3421 *
3422 * Converts a double-precision number to the shortest string of digits
3423 * that reconverts exactly to the given number, or to 'ilim' digits if
3424 * that will yield a shorter result. The denominator in David Gay's
3425 * conversion algorithm is known to be a power of 2**MP_DIGIT_BIT, and hence
3426 * the division in the main loop may be replaced by a digit shift and
3427 * mask.
3428 *
3429 * Results:
3430 * Returns the string of significant decimal digits, in newly allocated
3431 * memory
3432 *
3433 * Side effects:
3434 * Stores the location of the decimal point in '*decpt' and the location
3435 * of the terminal null byte in '*endPtr'.
3436 *
3437 *----------------------------------------------------------------------
3438 */
3439
3440 static inline char *
3441 ShorteningBignumConversionPowD(
3442 Double *dPtr, /* Original number to convert. */
3443 int convType, /* Type of conversion (shortest, Steele,
3444 * E format, F format). */
3445 Tcl_WideUInt bw, /* Integer significand. */
3446 int b2, int b5, /* Scale factor for the significand in the
3447 * numerator. */
3448 int m2plus, int m2minus, int m5,
3449 /* Scale factors for 1/2 ulp in the numerator
3450 * (will be different if bw == 1). */
3451 int sd, /* Scale factor for the denominator. */
3452 int k, /* Number of output digits before the decimal
3453 * point. */
3454 int len, /* Number of digits to allocate. */
3455 int ilim, /* Number of digits to convert if b >= s */
3456 int ilim1, /* Number of digits to convert if b < s */
3457 int *decpt, /* OUTPUT: Position of the decimal point. */
3458 char **endPtr) /* OUTPUT: Position of the terminal '\0' at
3459 * the end of the returned string. */
3460 {
3461 char *retval = (char *)ckalloc(len + 1);
3462 /* Output buffer. */
3463 mp_int b; /* Numerator of the fraction being
3464 * converted. */
3465 mp_int mplus, mminus; /* Bounds for roundoff. */
3466 mp_digit digit; /* Current output digit. */
3467 char *s = retval; /* Cursor in the output buffer. */
3468 int i; /* Index in the output buffer. */
3469 mp_int temp;
3470 int r1;
3471
3472 /*
3473 * b = bw * 2**b2 * 5**b5
3474 * mminus = 5**m5
3475 */
3476
3477 TclBNInitBignumFromWideUInt(&b, bw);
3478 mp_init_set(&mminus, 1);
3479 MulPow5(&b, b5, &b);
3480 mp_mul_2d(&b, b2, &b);
3481
3482 /*
3483 * Adjust if the logarithm was guessed wrong.
3484 */
3485
3486 if (b.used <= sd) {
3487 mp_mul_d(&b, 10, &b);
3488 ++m2plus; ++m2minus; ++m5;
3489 ilim = ilim1;
3490 --k;
3491 }
3492
3493 /*
3494 * mminus = 5**m5 * 2**m2minus
3495 * mplus = 5**m5 * 2**m2plus
3496 */
3497
3498 mp_mul_2d(&mminus, m2minus, &mminus);
3499 MulPow5(&mminus, m5, &mminus);
3500 if (m2plus > m2minus) {
3501 mp_init_copy(&mplus, &mminus);
3502 mp_mul_2d(&mplus, m2plus-m2minus, &mplus);
3503 }
3504 mp_init(&temp);
3505
3506 /*
3507 * Loop through the digits. Do division and mod by s == 2**(sd*MP_DIGIT_BIT)
3508 * by mp_digit extraction.
3509 */
3510
3511 i = 0;
3512 for (;;) {
3513 if (b.used <= sd) {
3514 digit = 0;
3515 } else {
3516 digit = b.dp[sd];
3517 if (b.used > sd+1 || digit >= 10) {
3518 Tcl_Panic("wrong digit!");
3519 }
3520 --b.used; mp_clamp(&b);
3521 }
3522
3523 /*
3524 * Does the current digit put us on the low side of the exact value
3525 * but within roundoff of being exact?
3526 */
3527
3528 r1 = mp_cmp_mag(&b, (m2plus > m2minus)? &mplus : &mminus);
3529 if (r1 == MP_LT || (r1 == MP_EQ
3530 && convType != TCL_DD_STEELE0 && (dPtr->w.word1 & 1) == 0)) {
3531 /*
3532 * Make sure we shouldn't be rounding *up* instead, in case the
3533 * next number above is closer.
3534 */
3535
3536 if (ShouldBankerRoundUpPowD(&b, sd, digit&1)) {
3537 ++digit;
3538 if (digit == 10) {
3539 *s++ = '9';
3540 s = BumpUp(s, retval, &k);
3541 break;
3542 }
3543 }
3544
3545 /*
3546 * Stash the last digit.
3547 */
3548
3549 *s++ = '0' + (char)digit;
3550 break;
3551 }
3552
3553 /*
3554 * Does one plus the current digit put us within roundoff of the
3555 * number?
3556 */
3557
3558 if (ShouldBankerRoundUpToNextPowD(&b, &mminus, sd, convType,
3559 dPtr->w.word1 & 1, &temp)) {
3560 if (digit == 9) {
3561 *s++ = '9';
3562 s = BumpUp(s, retval, &k);
3563 break;
3564 }
3565 ++digit;
3566 *s++ = '0' + (char)digit;
3567 break;
3568 }
3569
3570 /*
3571 * Have we converted all the requested digits?
3572 */
3573
3574 *s++ = '0' + (char)digit;
3575 if (i == ilim) {
3576 if (ShouldBankerRoundUpPowD(&b, sd, digit&1)) {
3577 s = BumpUp(s, retval, &k);
3578 }
3579 break;
3580 }
3581
3582 /*
3583 * Advance to the next digit.
3584 */
3585
3586 mp_mul_d(&b, 10, &b);
3587 mp_mul_d(&mminus, 10, &mminus);
3588 if (m2plus > m2minus) {
3589 mp_mul_2d(&mminus, m2plus-m2minus, &mplus);
3590 }
3591 ++i;
3592 }
3593
3594 /*
3595 * Endgame - store the location of the decimal point and the end of the
3596 * string.
3597 */
3598
3599 if (m2plus > m2minus) {
3600 mp_clear(&mplus);
3601 }
3602 mp_clear_multi(&b, &mminus, &temp, (void *)NULL);
3603 *s = '\0';
3604 *decpt = k;
3605 if (endPtr) {
3606 *endPtr = s;
3607 }
3608 return retval;
3609 }
3610
3611 /*
3612 *----------------------------------------------------------------------
3613 *
3614 * StrictBignumConversionPowD --
3615 *
3616 * Converts a double-precision number to a fixed-lengt string of 'ilim'
3617 * digits (or 'ilim1' if log10(d) has been overestimated). The
3618 * denominator in David Gay's conversion algorithm is known to be a power
3619 * of 2**MP_DIGIT_BIT, and hence the division in the main loop may be
3620 * replaced by a digit shift and mask.
3621 *
3622 * Results:
3623 * Returns the string of significant decimal digits, in newly allocated
3624 * memory.
3625 *
3626 * Side effects:
3627 * Stores the location of the decimal point in '*decpt' and the location
3628 * of the terminal null byte in '*endPtr'.
3629 *
3630 *----------------------------------------------------------------------
3631 */
3632
3633 static inline char *
3634 StrictBignumConversionPowD(
3635 Tcl_WideUInt bw, /* Integer significand. */
3636 int b2, int b5, /* Scale factor for the significand in the
3637 * numerator. */
3638 int sd, /* Scale factor for the denominator. */
3639 int k, /* Number of output digits before the decimal
3640 * point. */
3641 int len, /* Number of digits to allocate. */
3642 int ilim, /* Number of digits to convert if b >= s */
3643 int ilim1, /* Number of digits to convert if b < s */
3644 int *decpt, /* OUTPUT: Position of the decimal point. */
3645 char **endPtr) /* OUTPUT: Position of the terminal '\0' at
3646 * the end of the returned string. */
3647 {
3648 char *retval = (char *)ckalloc(len + 1);
3649 /* Output buffer. */
3650 mp_int b; /* Numerator of the fraction being
3651 * converted. */
3652 mp_digit digit; /* Current output digit. */
3653 char *s = retval; /* Cursor in the output buffer. */
3654 int i; /* Index in the output buffer. */
3655 mp_int temp;
3656
3657 /*
3658 * b = bw * 2**b2 * 5**b5
3659 */
3660
3661 TclBNInitBignumFromWideUInt(&b, bw);
3662 MulPow5(&b, b5, &b);
3663 mp_mul_2d(&b, b2, &b);
3664
3665 /*
3666 * Adjust if the logarithm was guessed wrong.
3667 */
3668
3669 if (b.used <= sd) {
3670 mp_mul_d(&b, 10, &b);
3671 ilim = ilim1;
3672 --k;
3673 }
3674 mp_init(&temp);
3675
3676 /*
3677 * Loop through the digits. Do division and mod by s == 2**(sd*MP_DIGIT_BIT)
3678 * by mp_digit extraction.
3679 */
3680
3681 i = 1;
3682 for (;;) {
3683 if (b.used <= sd) {
3684 digit = 0;
3685 } else {
3686 digit = b.dp[sd];
3687 if (b.used > sd+1 || digit >= 10) {
3688 Tcl_Panic("wrong digit!");
3689 }
3690 --b.used;
3691 mp_clamp(&b);
3692 }
3693
3694 /*
3695 * Have we converted all the requested digits?
3696 */
3697
3698 *s++ = '0' + (char)digit;
3699 if (i == ilim) {
3700 if (ShouldBankerRoundUpPowD(&b, sd, digit&1)) {
3701 s = BumpUp(s, retval, &k);
3702 }
3703 while (*--s == '0') {
3704 /* do nothing */
3705 }
3706 ++s;
3707 break;
3708 }
3709
3710 /*
3711 * Advance to the next digit.
3712 */
3713
3714 mp_mul_d(&b, 10, &b);
3715 ++i;
3716 }
3717
3718 /*
3719 * Endgame - store the location of the decimal point and the end of the
3720 * string.
3721 */
3722
3723 mp_clear_multi(&b, &temp, (void *)NULL);
3724 *s = '\0';
3725 *decpt = k;
3726 if (endPtr) {
3727 *endPtr = s;
3728 }
3729 return retval;
3730 }
3731
3732 /*
3733 *----------------------------------------------------------------------
3734 *
3735 * ShouldBankerRoundUp --
3736 *
3737 * Tests whether a digit should be rounded up or down when finishing
3738 * bignum-based floating point conversion.
3739 *
3740 * Results:
3741 * Returns 1 if the number needs to be rounded up, 0 otherwise.
3742 *
3743 *----------------------------------------------------------------------
3744 */
3745
3746 static inline int
3747 ShouldBankerRoundUp(
3748 mp_int *twor, /* 2x the remainder from thd division that
3749 * produced the last digit. */
3750 mp_int *S, /* Denominator. */
3751 int isodd) /* Flag == 1 if the last digit is odd. */
3752 {
3753 int r = mp_cmp_mag(twor, S);
3754
3755 switch (r) {
3756 case MP_EQ:
3757 return isodd;
3758 case MP_GT:
3759 return 1;
3760 default:
3761 return 0;
3762 }
3763 }
3764
3765 /*
3766 *----------------------------------------------------------------------
3767 *
3768 * ShouldBankerRoundUpToNext --
3769 *
3770 * Tests whether the remainder is great enough to force rounding to the
3771 * next higher digit.
3772 *
3773 * Results:
3774 * Returns 1 if the number should be rounded up, 0 otherwise.
3775 *
3776 *----------------------------------------------------------------------
3777 */
3778
3779 static inline int
3780 ShouldBankerRoundUpToNext(
3781 mp_int *b, /* Remainder from the division that produced
3782 * the last digit. */
3783 mp_int *m, /* Numerator of the rounding tolerance. */
3784 mp_int *S, /* Denominator. */
3785 int convType, /* Conversion type: STEELE0 defeats
3786 * round-to-even. (Not sure why one would want
3787 * this; I coped it from Gay). FIXME */
3788 int isodd, /* 1 if the integer significand is odd. */
3789 mp_int *temp) /* Work area needed for the calculation. */
3790 {
3791 int r;
3792
3793 /*
3794 * Compare b and S-m: this is the same as comparing B+m and S.
3795 */
3796
3797 mp_add(b, m, temp);
3798 r = mp_cmp_mag(temp, S);
3799 switch(r) {
3800 case MP_EQ:
3801 if (convType == TCL_DD_STEELE0) {
3802 return 0;
3803 } else {
3804 return isodd;
3805 }
3806 case MP_GT:
3807 return 1;
3808 default:
3809 return 0;
3810 }
3811 }
3812
3813 /*
3814 *----------------------------------------------------------------------
3815 *
3816 * ShorteningBignumConversion --
3817 *
3818 * Convert a floating point number to a variable-length digit string
3819 * using the multiprecision method.
3820 *
3821 * Results:
3822 * Returns the string of digits.
3823 *
3824 * Side effects:
3825 * Stores the position of the decimal point in *decpt. Stores a pointer
3826 * to the end of the number in *endPtr.
3827 *
3828 *----------------------------------------------------------------------
3829 */
3830
3831 static inline char *
3832 ShorteningBignumConversion(
3833 Double *dPtr, /* Original number being converted. */
3834 int convType, /* Conversion type. */
3835 Tcl_WideUInt bw, /* Integer significand and exponent. */
3836 int b2, /* Scale factor for the significand. */
3837 int m2plus, int m2minus, /* Scale factors for 1/2 ulp in numerator. */
3838 int s2, int s5, /* Scale factors for denominator. */
3839 int k, /* Guessed position of the decimal point. */
3840 int len, /* Size of the digit buffer to allocate. */
3841 int ilim, /* Number of digits to convert if b >= s */
3842 int ilim1, /* Number of digits to convert if b < s */
3843 int *decpt, /* OUTPUT: Position of the decimal point. */
3844 char **endPtr) /* OUTPUT: Pointer to the end of the number */
3845 {
3846 char *retval = (char *)ckalloc(len+1);
3847 /* Buffer of digits to return. */
3848 char *s = retval; /* Cursor in the return value. */
3849 mp_int b; /* Numerator of the result. */
3850 mp_int mminus; /* 1/2 ulp below the result. */
3851 mp_int mplus; /* 1/2 ulp above the result. */
3852 mp_int S; /* Denominator of the result. */
3853 mp_int dig; /* Current digit of the result. */
3854 int digit; /* Current digit of the result. */
3855 mp_int temp; /* Work area. */
3856 int minit = 1; /* Fudge factor for when we misguess k. */
3857 int i;
3858 int r1;
3859
3860 /*
3861 * b = bw * 2**b2 * 5**b5
3862 * S = 2**s2 * 5*s5
3863 */
3864
3865 TclBNInitBignumFromWideUInt(&b, bw);
3866 mp_mul_2d(&b, b2, &b);
3867 mp_init_set(&S, 1);
3868 MulPow5(&S, s5, &S); mp_mul_2d(&S, s2, &S);
3869
3870 /*
3871 * Handle the case where we guess the position of the decimal point wrong.
3872 */
3873
3874 if (mp_cmp_mag(&b, &S) == MP_LT) {
3875 mp_mul_d(&b, 10, &b);
3876 minit = 10;
3877 ilim =ilim1;
3878 --k;
3879 }
3880
3881 /*
3882 * mminus = 2**m2minus * 5**m5
3883 */
3884
3885 mp_init_set(&mminus, minit);
3886 mp_mul_2d(&mminus, m2minus, &mminus);
3887 if (m2plus > m2minus) {
3888 mp_init_copy(&mplus, &mminus);
3889 mp_mul_2d(&mplus, m2plus-m2minus, &mplus);
3890 }
3891 mp_init(&temp);
3892
3893 /*
3894 * Loop through the digits.
3895 */
3896
3897 mp_init(&dig);
3898 i = 1;
3899 for (;;) {
3900 mp_div(&b, &S, &dig, &b);
3901 if (dig.used > 1 || dig.dp[0] >= 10) {
3902 Tcl_Panic("wrong digit!");
3903 }
3904 digit = (int)dig.dp[0];
3905
3906 /*
3907 * Does the current digit leave us with a remainder small enough to
3908 * round to it?
3909 */
3910
3911 r1 = mp_cmp_mag(&b, (m2plus > m2minus)? &mplus : &mminus);
3912 if (r1 == MP_LT || (r1 == MP_EQ
3913 && convType != TCL_DD_STEELE0 && (dPtr->w.word1 & 1) == 0)) {
3914 mp_mul_2d(&b, 1, &b);
3915 if (ShouldBankerRoundUp(&b, &S, digit&1)) {
3916 ++digit;
3917 if (digit == 10) {
3918 *s++ = '9';
3919 s = BumpUp(s, retval, &k);
3920 break;
3921 }
3922 }
3923 *s++ = '0' + (char)digit;
3924 break;
3925 }
3926
3927 /*
3928 * Does the current digit leave us with a remainder large enough to
3929 * commit to rounding up to the next higher digit?
3930 */
3931
3932 if (ShouldBankerRoundUpToNext(&b, &mminus, &S, convType,
3933 dPtr->w.word1 & 1, &temp)) {
3934 ++digit;
3935 if (digit == 10) {
3936 *s++ = '9';
3937 s = BumpUp(s, retval, &k);
3938 break;
3939 }
3940 *s++ = '0' + (char)digit;
3941 break;
3942 }
3943
3944 /*
3945 * Have we converted all the requested digits?
3946 */
3947
3948 *s++ = '0' + (char)digit;
3949 if (i == ilim) {
3950 mp_mul_2d(&b, 1, &b);
3951 if (ShouldBankerRoundUp(&b, &S, digit&1)) {
3952 s = BumpUp(s, retval, &k);
3953 }
3954 break;
3955 }
3956
3957 /*
3958 * Advance to the next digit.
3959 */
3960
3961 if (s5 > 0) {
3962 /*
3963 * Can possibly shorten the denominator.
3964 */
3965
3966 mp_mul_2d(&b, 1, &b);
3967 mp_mul_2d(&mminus, 1, &mminus);
3968 if (m2plus > m2minus) {
3969 mp_mul_2d(&mplus, 1, &mplus);
3970 }
3971 mp_div_d(&S, 5, &S, NULL);
3972 --s5;
3973
3974 /*
3975 * IDEA: It might possibly be a win to fall back to int64_t
3976 * arithmetic here if S < 2**64/10. But it's a win only for
3977 * a fairly narrow range of magnitudes so perhaps not worth
3978 * bothering. We already know that we shorten the
3979 * denominator by at least 1 mp_digit, perhaps 2, as we do
3980 * the conversion for 17 digits of significance.
3981 * Possible savings:
3982 * 10**26 1 trip through loop before fallback possible
3983 * 10**27 1 trip
3984 * 10**28 2 trips
3985 * 10**29 3 trips
3986 * 10**30 4 trips
3987 * 10**31 5 trips
3988 * 10**32 6 trips
3989 * 10**33 7 trips
3990 * 10**34 8 trips
3991 * 10**35 9 trips
3992 * 10**36 10 trips
3993 * 10**37 11 trips
3994 * 10**38 12 trips
3995 * 10**39 13 trips
3996 * 10**40 14 trips
3997 * 10**41 15 trips
3998 * 10**42 16 trips
3999 * thereafter no gain.
4000 */
4001 } else {
4002 mp_mul_d(&b, 10, &b);
4003 mp_mul_d(&mminus, 10, &mminus);
4004 if (m2plus > m2minus) {
4005 mp_mul_2d(&mplus, 10, &mplus);
4006 }
4007 }
4008
4009 ++i;
4010 }
4011
4012 /*
4013 * Endgame - store the location of the decimal point and the end of the
4014 * string.
4015 */
4016
4017 if (m2plus > m2minus) {
4018 mp_clear(&mplus);
4019 }
4020 mp_clear_multi(&b, &mminus, &temp, &dig, &S, (void *)NULL);
4021 *s = '\0';
4022 *decpt = k;
4023 if (endPtr) {
4024 *endPtr = s;
4025 }
4026 return retval;
4027 }
4028
4029 /*
4030 *----------------------------------------------------------------------
4031 *
4032 * StrictBignumConversion --
4033 *
4034 * Convert a floating point number to a fixed-length digit string using
4035 * the multiprecision method.
4036 *
4037 * Results:
4038 * Returns the string of digits.
4039 *
4040 * Side effects:
4041 * Stores the position of the decimal point in *decpt. Stores a pointer
4042 * to the end of the number in *endPtr.
4043 *
4044 *----------------------------------------------------------------------
4045 */
4046
4047 static inline char *
4048 StrictBignumConversion(
4049 Tcl_WideUInt bw, /* Integer significand and exponent. */
4050 int b2, /* Scale factor for the significand. */
4051 int s2, int s5, /* Scale factors for denominator. */
4052 int k, /* Guessed position of the decimal point. */
4053 int len, /* Size of the digit buffer to allocate. */
4054 int ilim, /* Number of digits to convert if b >= s */
4055 int ilim1, /* Number of digits to convert if b < s */
4056 int *decpt, /* OUTPUT: Position of the decimal point. */
4057 char **endPtr) /* OUTPUT: Pointer to the end of the number */
4058 {
4059 char *retval = (char *)ckalloc(len+1);
4060 /* Buffer of digits to return. */
4061 char *s = retval; /* Cursor in the return value. */
4062 mp_int b; /* Numerator of the result. */
4063 mp_int S; /* Denominator of the result. */
4064 mp_int dig; /* Current digit of the result. */
4065 int digit; /* Current digit of the result. */
4066 mp_int temp; /* Work area. */
4067 int g; /* Size of the current digit ground. */
4068 int i, j;
4069
4070 /*
4071 * b = bw * 2**b2 * 5**b5
4072 * S = 2**s2 * 5*s5
4073 */
4074
4075 mp_init_multi(&temp, &dig, (void *)NULL);
4076 TclBNInitBignumFromWideUInt(&b, bw);
4077 mp_mul_2d(&b, b2, &b);
4078 mp_init_set(&S, 1);
4079 MulPow5(&S, s5, &S); mp_mul_2d(&S, s2, &S);
4080
4081 /*
4082 * Handle the case where we guess the position of the decimal point wrong.
4083 */
4084
4085 if (mp_cmp_mag(&b, &S) == MP_LT) {
4086 mp_mul_d(&b, 10, &b);
4087 ilim =ilim1;
4088 --k;
4089 }
4090
4091 /*
4092 * Convert the leading digit.
4093 */
4094
4095 i = 0;
4096 mp_div(&b, &S, &dig, &b);
4097 if (dig.used > 1 || dig.dp[0] >= 10) {
4098 Tcl_Panic("wrong digit!");
4099 }
4100 digit = (int)dig.dp[0];
4101
4102 /*
4103 * Is a single digit all that was requested?
4104 */
4105
4106 *s++ = '0' + (char)digit;
4107 if (++i >= ilim) {
4108 mp_mul_2d(&b, 1, &b);
4109 if (ShouldBankerRoundUp(&b, &S, digit&1)) {
4110 s = BumpUp(s, retval, &k);
4111 }
4112 } else {
4113 for (;;) {
4114 /*
4115 * Shift by a group of digits.
4116 */
4117
4118 g = ilim - i;
4119 if (g > DIGIT_GROUP) {
4120 g = DIGIT_GROUP;
4121 }
4122 if (s5 >= g) {
4123 mp_div_d(&S, dpow5[g], &S, NULL);
4124 s5 -= g;
4125 } else if (s5 > 0) {
4126 mp_div_d(&S, dpow5[s5], &S, NULL);
4127 mp_mul_d(&b, dpow5[g - s5], &b);
4128 s5 = 0;
4129 } else {
4130 mp_mul_d(&b, dpow5[g], &b);
4131 }
4132 mp_mul_2d(&b, g, &b);
4133
4134 /*
4135 * As with the shortening bignum conversion, it's possible at this
4136 * point that we will have reduced the denominator to less than
4137 * 2**64/10, at which point it would be possible to fall back to
4138 * to int64_t arithmetic. But the potential payoff is tremendously
4139 * less - unless we're working in F format - because we know that
4140 * three groups of digits will always suffice for %#.17e, the
4141 * longest format that doesn't introduce empty precision.
4142 *
4143 * Extract the next group of digits.
4144 */
4145
4146 mp_div(&b, &S, &dig, &b);
4147 if (dig.used > 1) {
4148 Tcl_Panic("wrong digit!");
4149 }
4150 digit = (int)dig.dp[0];
4151 for (j = g-1; j >= 0; --j) {
4152 int t = itens[j];
4153
4154 *s++ = (char)(digit / t + '0');
4155 digit %= t;
4156 }
4157 i += g;
4158
4159 /*
4160 * Have we converted all the requested digits?
4161 */
4162
4163 if (i == ilim) {
4164 mp_mul_2d(&b, 1, &b);
4165 if (ShouldBankerRoundUp(&b, &S, digit&1)) {
4166 s = BumpUp(s, retval, &k);
4167 }
4168 break;
4169 }
4170 }
4171 }
4172 while (*--s == '0') {
4173 /* do nothing */
4174 }
4175 ++s;
4176
4177 /*
4178 * Endgame - store the location of the decimal point and the end of the
4179 * string.
4180 */
4181
4182 mp_clear_multi(&b, &S, &temp, &dig, (void *)NULL);
4183 *s = '\0';
4184 *decpt = k;
4185 if (endPtr) {
4186 *endPtr = s;
4187 }
4188 return retval;
4189 }
4190
4191 /*
4192 *----------------------------------------------------------------------
4193 *
4194 * TclDoubleDigits --
4195 *
4196 * Core of Tcl's conversion of double-precision floating point numbers to
4197 * decimal.
4198 *
4199 * Results:
4200 * Returns a newly-allocated string of digits.
4201 *
4202 * Side effects:
4203 * Sets *decpt to the index of the character in the string before the
4204 * place that the decimal point should go. If 'endPtr' is not NULL, sets
4205 * endPtr to point to the terminating '\0' byte of the string. Sets *sign
4206 * to 1 if a minus sign should be printed with the number, or 0 if a plus
4207 * sign (or no sign) should appear.
4208 *
4209 * This function is a service routine that produces the string of digits for
4210 * floating-point-to-decimal conversion. It can do a number of things
4211 * according to the 'flags' argument. Valid values for 'flags' include:
4212 * TCL_DD_SHORTEST - This is the default for floating point conversion if
4213 * ::tcl_precision is 0. It constructs the shortest string of
4214 * digits that will reconvert to the given number when scanned.
4215 * For floating point numbers that are exactly between two
4216 * decimal numbers, it resolves using the 'round to even' rule.
4217 * With this value, the 'ndigits' parameter is ignored.
4218 * TCL_DD_STEELE - This value is not recommended and may be removed in
4219 * the future. It follows the conversion algorithm outlined in
4220 * "How to Print Floating-Point Numbers Accurately" by Guy
4221 * L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90,
4222 * pp. 112-126]. This rule has the effect of rendering 1e23 as
4223 * 9.9999999999999999e22 - which is a 'better' approximation in
4224 * the sense that it will reconvert correctly even if a
4225 * subsequent input conversion is 'round up' or 'round down'
4226 * rather than 'round to nearest', but is surprising otherwise.
4227 * TCL_DD_E_FORMAT - This value is used to prepare numbers for %e format
4228 * conversion (or for default floating->string if tcl_precision
4229 * is not 0). It constructs a string of at most 'ndigits' digits,
4230 * choosing the one that is closest to the given number (and
4231 * resolving ties with 'round to even'). It is allowed to return
4232 * fewer than 'ndigits' if the number converts exactly; if the
4233 * TCL_DD_E_FORMAT|TCL_DD_SHORTEN_FLAG is supplied instead, it
4234 * also returns fewer digits if the shorter string will still
4235 * reconvert without loss to the given input number. In any case,
4236 * strings of trailing zeroes are suppressed.
4237 * TCL_DD_F_FORMAT - This value is used to prepare numbers for %f format
4238 * conversion. It requests that conversion proceed until
4239 * 'ndigits' digits after the decimal point have been converted.
4240 * It is possible for this format to result in a zero-length
4241 * string if the number is sufficiently small. Again, it is
4242 * permissible for TCL_DD_F_FORMAT to return fewer digits for a
4243 * number that converts exactly, and changing the argument to
4244 * TCL_DD_F_FORMAT|TCL_DD_SHORTEN_FLAG will allow the routine
4245 * also to return fewer digits if the shorter string will still
4246 * reconvert without loss to the given input number. Strings of
4247 * trailing zeroes are suppressed.
4248 *
4249 * To any of these flags may be OR'ed TCL_DD_NO_QUICK; this flag requires
4250 * all calculations to be done in exact arithmetic. Normally, E and F
4251 * format with fewer than about 14 digits will be done with a quick
4252 * floating point approximation and fall back on the exact arithmetic
4253 * only if the input number is close enough to the midpoint between two
4254 * decimal strings that more precision is needed to resolve which string
4255 * is correct.
4256 *
4257 * The value stored in the 'decpt' argument on return may be negative
4258 * (indicating that the decimal point falls to the left of the string) or
4259 * greater than the length of the string. In addition, the value -9999 is used
4260 * as a sentinel to indicate that the string is one of the special values
4261 * "Infinity" and "NaN", and that no decimal point should be inserted.
4262 *
4263 *----------------------------------------------------------------------
4264 */
4265
4266 char *
4267 TclDoubleDigits(
4268 double dv, /* Number to convert. */
4269 int ndigits, /* Number of digits requested. */
4270 int flags, /* Conversion flags. */
4271 int *decpt, /* OUTPUT: Position of the decimal point. */
4272 int *sign, /* OUTPUT: 1 if the result is negative. */
4273 char **endPtr) /* OUTPUT: If not NULL, receives a pointer to
4274 * one character beyond the end of the
4275 * returned string. */
4276 {
4277 int convType = (flags & TCL_DD_CONVERSION_TYPE_MASK);
4278 /* Type of conversion being performed:
4279 * TCL_DD_SHORTEST0, TCL_DD_STEELE0,
4280 * TCL_DD_E_FORMAT, or TCL_DD_F_FORMAT. */
4281 Double d; /* Union for deconstructing doubles. */
4282 Tcl_WideUInt bw; /* Integer significand. */
4283 int be; /* Power of 2 by which b must be multiplied */
4284 int bbits; /* Number of bits needed to represent b. */
4285 int denorm; /* Flag == 1 iff the input number was
4286 * denormalized. */
4287 int k; /* Estimate of floor(log10(d)). */
4288 int k_check; /* Flag == 1 if d is near enough to a power of
4289 * ten that k must be checked. */
4290 int b2, b5, s2, s5; /* Powers of 2 and 5 in the numerator and
4291 * denominator of intermediate results. */
4292 int ilim = -1, ilim1 = -1; /* Number of digits to convert, and number to
4293 * convert if log10(d) has been
4294 * overestimated. */
4295 char *retval; /* Return value from this function. */
4296 int i = -1;
4297
4298 /*
4299 * Put the input number into a union for bit-whacking.
4300 */
4301
4302 d.d = dv;
4303
4304 /*
4305 * Handle the cases of negative numbers (by taking the absolute value:
4306 * this includes -Inf and -NaN!), infinity, Not a Number, and zero.
4307 */
4308
4309 TakeAbsoluteValue(&d, sign);
4310 if ((d.w.word0 & EXP_MASK) == EXP_MASK) {
4311 return FormatInfAndNaN(&d, decpt, endPtr);
4312 }
4313 if (d.d == 0.0) {
4314 return FormatZero(decpt, endPtr);
4315 }
4316
4317 /*
4318 * Unpack the floating point into a wide integer and an exponent.
4319 * Determine the number of bits that the big integer requires, and compute
4320 * a quick approximation (which may be one too high) of ceil(log10(d.d)).
4321 */
4322
4323 denorm = ((d.w.word0 & EXP_MASK) == 0);
4324 DoubleToExpAndSig(d.d, &bw, &be, &bbits);
4325 k = ApproximateLog10(bw, be, bbits);
4326 k = BetterLog10(d.d, k, &k_check);
4327
4328 /* At this point, we have:
4329 * d is the number to convert.
4330 * bw are significand and exponent: d == bw*2**be,
4331 * bbits is the length of bw: 2**bbits-1 <= bw < 2**bbits
4332 * k is either ceil(log10(d)) or ceil(log10(d))+1. k_check is 0 if we
4333 * know that k is exactly ceil(log10(d)) and 1 if we need to check.
4334 * We want a rational number
4335 * r = b * 10**(1-k) = bw * 2**b2 * 5**b5 / (2**s2 / 5**s5),
4336 * with b2, b5, s2, s5 >= 0. Note that the most significant decimal
4337 * digit is floor(r) and that successive digits can be obtained by
4338 * setting r <- 10*floor(r) (or b <= 10 * (b % S)). Find appropriate
4339 * b2, b5, s2, s5.
4340 */
4341
4342 ComputeScale(be, k, &b2, &b5, &s2, &s5);
4343
4344 /*
4345 * Correct an incorrect caller-supplied 'ndigits'. Also determine:
4346 * i = The maximum number of decimal digits that will be returned in the
4347 * formatted string. This is k + 1 + ndigits for F format, 18 for
4348 * shortest and Steele, and ndigits for E format.
4349 * ilim = The number of significant digits to convert if k has been
4350 * guessed correctly. This is -1 for shortest and Steele (which
4351 * stop when all significance has been lost), 'ndigits' for E
4352 * format, and 'k + 1 + ndigits' for F format.
4353 * ilim1 = The minimum number of significant digits to convert if k has
4354 * been guessed 1 too high. This, too, is -1 for shortest and
4355 * Steele, and 'ndigits' for E format, but it's 'ndigits-1' for F
4356 * format.
4357 */
4358
4359 SetPrecisionLimits(convType, k, &ndigits, &i, &ilim, &ilim1);
4360
4361 /*
4362 * Try to do low-precision conversion in floating point rather than
4363 * resorting to expensive multiprecision arithmetic.
4364 */
4365
4366 if (ilim >= 0 && ilim <= QUICK_MAX && !(flags & TCL_DD_NO_QUICK)) {
4367 retval = QuickConversion(d.d, k, k_check, flags, i, ilim, ilim1,
4368 decpt, endPtr);
4369 if (retval != NULL) {
4370 return retval;
4371 }
4372 }
4373
4374 /*
4375 * For shortening conversions, determine the upper and lower bounds for
4376 * the remainder at which we can stop.
4377 * m+ = (2**m2plus * 5**m5) / (2**s2 * 5**s5) is the limit on the high
4378 * side, and
4379 * m- = (2**m2minus * 5**m5) / (2**s2 * 5**s5) is the limit on the low
4380 * side.
4381 * We may need to increase s2 to put m2plus, m2minus, b2 over a common
4382 * denominator.
4383 */
4384
4385 if (flags & TCL_DD_SHORTEN_FLAG) {
4386 int m2minus = b2;
4387 int m2plus;
4388 int m5 = b5;
4389 int len = i;
4390
4391 /*
4392 * Find the quantity i so that (2**i*5**b5)/(2**s2*5**s5) is 1/2 unit
4393 * in the least significant place of the floating point number.
4394 */
4395
4396 if (denorm) {
4397 i = be + EXPONENT_BIAS + (FP_PRECISION-1);
4398 } else {
4399 i = 1 + FP_PRECISION - bbits;
4400 }
4401 b2 += i;
4402 s2 += i;
4403
4404 /*
4405 * Reduce the fractions to lowest terms, since the above calculation
4406 * may have left excess powers of 2 in numerator and denominator.
4407 */
4408
4409 CastOutPowersOf2(&b2, &m2minus, &s2);
4410
4411 /*
4412 * In the special case where bw==1, the nearest floating point number
4413 * to it on the low side is 1/4 ulp below it. Adjust accordingly.
4414 */
4415
4416 m2plus = m2minus;
4417 if (!denorm && bw == 1) {
4418 ++b2;
4419 ++s2;
4420 ++m2plus;
4421 }
4422
4423 if (s5+1 < N_LOG2POW5 && s2+1 + log2pow5[s5+1] < 64) {
4424 /*
4425 * If 10*2**s2*5**s5 == 2**(s2+1)+5**(s5+1) fits in a 64-bit word,
4426 * then all our intermediate calculations can be done using exact
4427 * 64-bit arithmetic with no need for expensive multiprecision
4428 * operations. (This will be true for all numbers in the range
4429 * [1.0e-3 .. 1.0e+24]).
4430 */
4431
4432 return ShorteningInt64Conversion(&d, convType, bw, b2, b5, m2plus,
4433 m2minus, m5, s2, s5, k, len, ilim, ilim1, decpt, endPtr);
4434 } else if (s5 == 0) {
4435 /*
4436 * The denominator is a power of 2, so we can replace division by
4437 * digit shifts. First we round up s2 to a multiple of MP_DIGIT_BIT,
4438 * and adjust m2 and b2 accordingly. Then we launch into a version
4439 * of the comparison that's specialized for the 'power of mp_digit
4440 * in the denominator' case.
4441 */
4442
4443 if (s2 % MP_DIGIT_BIT != 0) {
4444 int delta = MP_DIGIT_BIT - (s2 % MP_DIGIT_BIT);
4445
4446 b2 += delta;
4447 m2plus += delta;
4448 m2minus += delta;
4449 s2 += delta;
4450 }
4451 return ShorteningBignumConversionPowD(&d, convType, bw, b2, b5,
4452 m2plus, m2minus, m5, s2/MP_DIGIT_BIT, k, len, ilim, ilim1,
4453 decpt, endPtr);
4454 } else {
4455 /*
4456 * Alas, there's no helpful special case; use full-up bignum
4457 * arithmetic for the conversion.
4458 */
4459
4460 return ShorteningBignumConversion(&d, convType, bw, b2, m2plus,
4461 m2minus, s2, s5, k, len, ilim, ilim1, decpt, endPtr);
4462 }
4463 } else {
4464 /*
4465 * Non-shortening conversion.
4466 */
4467
4468 int len = i;
4469
4470 /*
4471 * Reduce numerator and denominator to lowest terms.
4472 */
4473
4474 if (b2 >= s2 && s2 > 0) {
4475 b2 -= s2; s2 = 0;
4476 } else if (s2 >= b2 && b2 > 0) {
4477 s2 -= b2; b2 = 0;
4478 }
4479
4480 if (s5+1 < N_LOG2POW5 && s2+1 + log2pow5[s5+1] < 64) {
4481 /*
4482 * If 10*2**s2*5**s5 == 2**(s2+1)+5**(s5+1) fits in a 64-bit word,
4483 * then all our intermediate calculations can be done using exact
4484 * 64-bit arithmetic with no need for expensive multiprecision
4485 * operations.
4486 */
4487
4488 return StrictInt64Conversion(bw, b2, b5, s2, s5, k,
4489 len, ilim, ilim1, decpt, endPtr);
4490 } else if (s5 == 0) {
4491 /*
4492 * The denominator is a power of 2, so we can replace division by
4493 * digit shifts. First we round up s2 to a multiple of MP_DIGIT_BIT,
4494 * and adjust m2 and b2 accordingly. Then we launch into a version
4495 * of the comparison that's specialized for the 'power of mp_digit
4496 * in the denominator' case.
4497 */
4498
4499 if (s2 % MP_DIGIT_BIT != 0) {
4500 int delta = MP_DIGIT_BIT - (s2 % MP_DIGIT_BIT);
4501
4502 b2 += delta;
4503 s2 += delta;
4504 }
4505 return StrictBignumConversionPowD(bw, b2, b5,
4506 s2/MP_DIGIT_BIT, k, len, ilim, ilim1, decpt, endPtr);
4507 } else {
4508 /*
4509 * There are no helpful special cases, but at least we know in
4510 * advance how many digits we will convert. We can run the
4511 * conversion in steps of DIGIT_GROUP digits, so as to have many
4512 * fewer mp_int divisions.
4513 */
4514
4515 return StrictBignumConversion(bw, b2, s2, s5, k,
4516 len, ilim, ilim1, decpt, endPtr);
4517 }
4518 }
4519 }
4520
4521 /*
4522 *----------------------------------------------------------------------
4523 *
4524 * TclInitDoubleConversion --
4525 *
4526 * Initializes constants that are needed for conversions to and from
4527 * 'double'
4528 *
4529 * Results:
4530 * None.
4531 *
4532 * Side effects:
4533 * The log base 2 of the floating point radix, the number of bits in a
4534 * double mantissa, and a table of the powers of five and ten are
4535 * computed and stored.
4536 *
4537 *----------------------------------------------------------------------
4538 */
4539
4540 void
4541 TclInitDoubleConversion(void)
4542 {
4543 int i;
4544 int x;
4545 Tcl_WideUInt u;
4546 double d;
4547 #ifdef IEEE_FLOATING_POINT
4548 union {
4549 double dv;
4550 Tcl_WideUInt iv;
4551 } bitwhack;
4552 #endif
4553 #if defined(__sgi) && defined(_COMPILER_VERSION)
4554 union fpc_csr mipsCR;
4555
4556 mipsCR.fc_word = get_fpc_csr();
4557 mipsCR.fc_struct.flush = 0;
4558 set_fpc_csr(mipsCR.fc_word);
4559 #endif
4560
4561 /*
4562 * Initialize table of powers of 10 expressed as wide integers.
4563 */
4564
4565 maxpow10_wide = (int)
4566 floor(sizeof(Tcl_WideUInt) * CHAR_BIT * log(2.) / log(10.));
4567 pow10_wide = (Tcl_WideUInt *)
4568 ckalloc((maxpow10_wide + 1) * sizeof(Tcl_WideUInt));
4569 u = 1;
4570 for (i = 0; i < maxpow10_wide; ++i) {
4571 pow10_wide[i] = u;
4572 u *= 10;
4573 }
4574 pow10_wide[i] = u;
4575
4576 /*
4577 * Determine how many bits of precision a double has, and how many decimal
4578 * digits that represents.
4579 */
4580
4581 if (frexp((double) FLT_RADIX, &log2FLT_RADIX) != 0.5) {
4582 Tcl_Panic("This code doesn't work on a decimal machine!");
4583 }
4584 log2FLT_RADIX--;
4585 mantBits = DBL_MANT_DIG * log2FLT_RADIX;
4586 d = 1.0;
4587
4588 /*
4589 * Initialize a table of powers of ten that can be exactly represented in
4590 * a double.
4591 */
4592
4593 x = (int) (DBL_MANT_DIG * log((double) FLT_RADIX) / log(5.0));
4594 if (x < MAXPOW) {
4595 mmaxpow = x;
4596 } else {
4597 mmaxpow = MAXPOW;
4598 }
4599 for (i=0 ; i<=mmaxpow ; ++i) {
4600 pow10vals[i] = d;
4601 d *= 10.0;
4602 }
4603
4604 /*
4605 * Initialize a table of large powers of five.
4606 */
4607
4608 for (i=0; i<9; ++i) {
4609 mp_init(pow5 + i);
4610 }
4611 mp_set(pow5, 5);
4612 for (i=0; i<8; ++i) {
4613 mp_sqr(pow5+i, pow5+i+1);
4614 }
4615 mp_init_set_int(pow5_13, 1220703125);
4616 for (i = 1; i < 5; ++i) {
4617 mp_init(pow5_13 + i);
4618 mp_sqr(pow5_13 + i - 1, pow5_13 + i);
4619 }
4620
4621 /*
4622 * Determine the number of decimal digits to the left and right of the
4623 * decimal point in the largest and smallest double, the smallest double
4624 * that differs from zero, and the number of mp_digits needed to represent
4625 * the significand of a double.
4626 */
4627
4628 maxDigits = (int) ((DBL_MAX_EXP * log((double) FLT_RADIX)
4629 + 0.5 * log(10.)) / log(10.));
4630 minDigits = (int) floor((DBL_MIN_EXP - DBL_MANT_DIG)
4631 * log((double) FLT_RADIX) / log(10.));
4632 log10_DIGIT_MAX = (int) floor(MP_DIGIT_BIT * log(2.) / log(10.));
4633
4634 /*
4635 * Nokia 770's software-emulated floating point is "middle endian": the
4636 * bytes within a 32-bit word are little-endian (like the native
4637 * integers), but the two words of a 'double' are presented most
4638 * significant word first.
4639 */
4640
4641 #ifdef IEEE_FLOATING_POINT
4642 bitwhack.dv = 1.000000238418579;
4643 /* 3ff0 0000 4000 0000 */
4644 if ((bitwhack.iv >> 32) == 0x3FF00000) {
4645 n770_fp = 0;
4646 } else if ((bitwhack.iv & 0xFFFFFFFF) == 0x3FF00000) {
4647 n770_fp = 1;
4648 } else {
4649 Tcl_Panic("unknown floating point word order on this machine");
4650 }
4651 #endif
4652 }
4653
4654 /*
4655 *----------------------------------------------------------------------
4656 *
4657 * TclFinalizeDoubleConversion --
4658 *
4659 * Cleans up this file on exit.
4660 *
4661 * Results:
4662 * None
4663 *
4664 * Side effects:
4665 * Memory allocated by TclInitDoubleConversion is freed.
4666 *
4667 *----------------------------------------------------------------------
4668 */
4669
4670 void
4671 TclFinalizeDoubleConversion(void)
4672 {
4673 int i;
4674
4675 ckfree(pow10_wide);
4676 for (i=0; i<9; ++i) {
4677 mp_clear(pow5 + i);
4678 }
4679 for (i=0; i < 5; ++i) {
4680 mp_clear(pow5_13 + i);
4681 }
4682 }
4683
4684 /*
4685 *----------------------------------------------------------------------
4686 *
4687 * Tcl_InitBignumFromDouble --
4688 *
4689 * Extracts the integer part of a double and converts it to an arbitrary
4690 * precision integer.
4691 *
4692 * Results:
4693 * None.
4694 *
4695 * Side effects:
4696 * Initializes the bignum supplied, and stores the converted number in
4697 * it.
4698 *
4699 *----------------------------------------------------------------------
4700 */
4701
4702 int
4703 Tcl_InitBignumFromDouble(
4704 Tcl_Interp *interp, /* For error message. */
4705 double d, /* Number to convert. */
4706 mp_int *b) /* Place to store the result. */
4707 {
4708 double fract;
4709 int expt;
4710
4711 /*
4712 * Infinite values can't convert to bignum.
4713 */
4714
4715 if (TclIsInfinite(d)) {
4716 if (interp != NULL) {
4717 const char *s = "integer value too large to represent";
4718
4719 Tcl_SetObjResult(interp, Tcl_NewStringObj(s, -1));
4720 Tcl_SetErrorCode(interp, "ARITH", "IOVERFLOW", s, (char *)NULL);
4721 }
4722 return TCL_ERROR;
4723 }
4724
4725 fract = frexp(d,&expt);
4726 if (expt <= 0) {
4727 mp_init(b);
4728 mp_zero(b);
4729 } else {
4730 Tcl_WideInt w = (Tcl_WideInt)ldexp(fract, mantBits);
4731 int shift = expt - mantBits;
4732
4733 TclBNInitBignumFromWideInt(b, w);
4734 if (shift < 0) {
4735 mp_div_2d(b, -shift, b, NULL);
4736 } else if (shift > 0) {
4737 mp_mul_2d(b, shift, b);
4738 }
4739 }
4740 return TCL_OK;
4741 }
4742
4743 /*
4744 *----------------------------------------------------------------------
4745 *
4746 * TclBignumToDouble --
4747 *
4748 * Convert an arbitrary-precision integer to a native floating point
4749 * number.
4750 *
4751 * Results:
4752 * Returns the converted number. Sets errno to ERANGE if the number is
4753 * too large to convert.
4754 *
4755 *----------------------------------------------------------------------
4756 */
4757
4758 double
4759 TclBignumToDouble(
4760 const mp_int *a) /* Integer to convert. */
4761 {
4762 mp_int b;
4763 int bits, shift, i, lsb;
4764 double r;
4765
4766 /*
4767 * We need a 'mantBits'-bit significand. Determine what shift will
4768 * give us that.
4769 */
4770
4771 bits = mp_count_bits(a);
4772 if (bits > DBL_MAX_EXP*log2FLT_RADIX) {
4773 errno = ERANGE;
4774 if (mp_isneg(a)) {
4775 return -HUGE_VAL;
4776 } else {
4777 return HUGE_VAL;
4778 }
4779 }
4780 shift = mantBits - bits;
4781
4782 /*
4783 * If shift > 0, shift the significand left by the requisite number of
4784 * bits. If shift == 0, the significand is already exactly 'mantBits'
4785 * in length. If shift < 0, we will need to shift the significand right
4786 * by the requisite number of bits, and round it. If the '1-shift'
4787 * least significant bits are 0, but the 'shift'th bit is nonzero,
4788 * then the significand lies exactly between two values and must be
4789 * 'rounded to even'.
4790 */
4791
4792 mp_init(&b);
4793 if (shift == 0) {
4794 mp_copy(a, &b);
4795 } else if (shift > 0) {
4796 mp_mul_2d(a, shift, &b);
4797 } else if (shift < 0) {
4798 lsb = mp_cnt_lsb(a);
4799 if (lsb == -1-shift) {
4800
4801 /*
4802 * Round to even
4803 */
4804
4805 mp_div_2d(a, -shift, &b, NULL);
4806 if (mp_isodd(&b)) {
4807 if (mp_isneg(&b)) {
4808 mp_sub_d(&b, 1, &b);
4809 } else {
4810 mp_add_d(&b, 1, &b);
4811 }
4812 }
4813 } else {
4814
4815 /*
4816 * Ordinary rounding
4817 */
4818
4819 mp_div_2d(a, -1-shift, &b, NULL);
4820 if (mp_isneg(&b)) {
4821 mp_sub_d(&b, 1, &b);
4822 } else {
4823 mp_add_d(&b, 1, &b);
4824 }
4825 mp_div_2d(&b, 1, &b, NULL);
4826 }
4827 }
4828
4829 /*
4830 * Accumulate the result, one mp_digit at a time.
4831 */
4832
4833 r = 0.0;
4834 for (i=b.used-1 ; i>=0 ; --i) {
4835 r = ldexp(r, MP_DIGIT_BIT) + b.dp[i];
4836 }
4837 mp_clear(&b);
4838
4839 /*
4840 * Scale the result to the correct number of bits.
4841 */
4842
4843 r = ldexp(r, bits - mantBits);
4844
4845 /*
4846 * Return the result with the appropriate sign.
4847 */
4848
4849 if (mp_isneg(a)) {
4850 return -r;
4851 } else {
4852 return r;
4853 }
4854 }
4855
4856 /*
4857 *----------------------------------------------------------------------
4858 *
4859 * TclCeil --
4860 *
4861 * Computes the smallest floating point number that is at least the
4862 * mp_int argument.
4863 *
4864 * Results:
4865 * Returns the floating point number.
4866 *
4867 *----------------------------------------------------------------------
4868 */
4869
4870 double
4871 TclCeil(
4872 const mp_int *a) /* Integer to convert. */
4873 {
4874 double r = 0.0;
4875 mp_int b;
4876
4877 mp_init(&b);
4878 if (mp_isneg(a)) {
4879 mp_neg(a, &b);
4880 r = -TclFloor(&b);
4881 } else {
4882 int bits = mp_count_bits(a);
4883
4884 if (bits > DBL_MAX_EXP*log2FLT_RADIX) {
4885 r = HUGE_VAL;
4886 } else {
4887 int i, exact = 1, shift = mantBits - bits;
4888
4889 if (shift > 0) {
4890 mp_mul_2d(a, shift, &b);
4891 } else if (shift < 0) {
4892 mp_int d;
4893 mp_init(&d);
4894 mp_div_2d(a, -shift, &b, &d);
4895 exact = mp_iszero(&d);
4896 mp_clear(&d);
4897 } else {
4898 mp_copy(a, &b);
4899 }
4900 if (!exact) {
4901 mp_add_d(&b, 1, &b);
4902 }
4903 for (i=b.used-1 ; i>=0 ; --i) {
4904 r = ldexp(r, MP_DIGIT_BIT) + b.dp[i];
4905 }
4906 r = ldexp(r, bits - mantBits);
4907 }
4908 }
4909 mp_clear(&b);
4910 return r;
4911 }
4912
4913 /*
4914 *----------------------------------------------------------------------
4915 *
4916 * TclFloor --
4917 *
4918 * Computes the largest floating point number less than or equal to the
4919 * mp_int argument.
4920 *
4921 * Results:
4922 * Returns the floating point value.
4923 *
4924 *----------------------------------------------------------------------
4925 */
4926
4927 double
4928 TclFloor(
4929 const mp_int *a) /* Integer to convert. */
4930 {
4931 double r = 0.0;
4932 mp_int b;
4933
4934 mp_init(&b);
4935 if (mp_isneg(a)) {
4936 mp_neg(a, &b);
4937 r = -TclCeil(&b);
4938 } else {
4939 int bits = mp_count_bits(a);
4940
4941 if (bits > DBL_MAX_EXP*log2FLT_RADIX) {
4942 r = DBL_MAX;
4943 } else {
4944 int i, shift = mantBits - bits;
4945
4946 if (shift > 0) {
4947 mp_mul_2d(a, shift, &b);
4948 } else if (shift < 0) {
4949 mp_div_2d(a, -shift, &b, NULL);
4950 } else {
4951 mp_copy(a, &b);
4952 }
4953 for (i=b.used-1 ; i>=0 ; --i) {
4954 r = ldexp(r, MP_DIGIT_BIT) + b.dp[i];
4955 }
4956 r = ldexp(r, bits - mantBits);
4957 }
4958 }
4959 mp_clear(&b);
4960 return r;
4961 }
4962
4963 /*
4964 *----------------------------------------------------------------------
4965 *
4966 * BignumToBiasedFrExp --
4967 *
4968 * Convert an arbitrary-precision integer to a native floating point
4969 * number in the range [0.5,1) times a power of two. NOTE: Intentionally
4970 * converts to a number that's a few ulp too small, so that
4971 * RefineApproximation will not overflow near the high end of the
4972 * machine's arithmetic range.
4973 *
4974 * Results:
4975 * Returns the converted number.
4976 *
4977 * Side effects:
4978 * Stores the exponent of two in 'machexp'.
4979 *
4980 *----------------------------------------------------------------------
4981 */
4982
4983 static double
4984 BignumToBiasedFrExp(
4985 const mp_int *a, /* Integer to convert. */
4986 int *machexp) /* Power of two. */
4987 {
4988 mp_int b;
4989 int bits;
4990 int shift;
4991 int i;
4992 double r;
4993
4994 /*
4995 * Determine how many bits we need, and extract that many from the input.
4996 * Round to nearest unit in the last place.
4997 */
4998
4999 bits = mp_count_bits(a);
5000 shift = mantBits - 2 - bits;
5001 mp_init(&b);
5002 if (shift > 0) {
5003 mp_mul_2d(a, shift, &b);
5004 } else if (shift < 0) {
5005 mp_div_2d(a, -shift, &b, NULL);
5006 } else {
5007 mp_copy(a, &b);
5008 }
5009
5010 /*
5011 * Accumulate the result, one mp_digit at a time.
5012 */
5013
5014 r = 0.0;
5015 for (i=b.used-1; i>=0; --i) {
5016 r = ldexp(r, MP_DIGIT_BIT) + b.dp[i];
5017 }
5018 mp_clear(&b);
5019
5020 /*
5021 * Return the result with the appropriate sign.
5022 */
5023
5024 *machexp = bits - mantBits + 2;
5025 return (mp_isneg(a) ? -r : r);
5026 }
5027
5028 /*
5029 *----------------------------------------------------------------------
5030 *
5031 * Pow10TimesFrExp --
5032 *
5033 * Multiply a power of ten by a number expressed as fraction and
5034 * exponent.
5035 *
5036 * Results:
5037 * Returns the significand of the result.
5038 *
5039 * Side effects:
5040 * Overwrites the 'machexp' parameter with the exponent of the result.
5041 *
5042 * Assumes that 'exponent' is such that 10**exponent would be a double, even
5043 * though 'fraction*10**(machexp+exponent)' might overflow.
5044 *
5045 *----------------------------------------------------------------------
5046 */
5047
5048 static double
5049 Pow10TimesFrExp(
5050 int exponent, /* Power of 10 to multiply by. */
5051 double fraction, /* Significand of multiplicand. */
5052 int *machexp) /* On input, exponent of multiplicand. On
5053 * output, exponent of result. */
5054 {
5055 int i, j;
5056 int expt = *machexp;
5057 double retval = fraction;
5058
5059 if (exponent > 0) {
5060 /*
5061 * Multiply by 10**exponent.
5062 */
5063
5064 retval = frexp(retval * pow10vals[exponent & 0xF], &j);
5065 expt += j;
5066 for (i=4; i<9; ++i) {
5067 if (exponent & (1<<i)) {
5068 retval = frexp(retval * pow_10_2_n[i], &j);
5069 expt += j;
5070 }
5071 }
5072 } else if (exponent < 0) {
5073 /*
5074 * Divide by 10**-exponent.
5075 */
5076
5077 retval = frexp(retval / pow10vals[(-exponent) & 0xF], &j);
5078 expt += j;
5079 for (i=4; i<9; ++i) {
5080 if ((-exponent) & (1<<i)) {
5081 retval = frexp(retval / pow_10_2_n[i], &j);
5082 expt += j;
5083 }
5084 }
5085 }
5086
5087 *machexp = expt;
5088 return retval;
5089 }
5090
5091 /*
5092 *----------------------------------------------------------------------
5093 *
5094 * SafeLdExp --
5095 *
5096 * Do an 'ldexp' operation, but handle denormals gracefully.
5097 *
5098 * Results:
5099 * Returns the appropriately scaled value.
5100 *
5101 * On some platforms, 'ldexp' fails when presented with a number too
5102 * small to represent as a normalized double. This routine does 'ldexp'
5103 * in two steps for those numbers, to return correctly denormalized
5104 * values.
5105 *
5106 *----------------------------------------------------------------------
5107 */
5108
5109 static double
5110 SafeLdExp(
5111 double fract,
5112 int expt)
5113 {
5114 int minexpt = DBL_MIN_EXP * log2FLT_RADIX;
5115 volatile double a, b, retval;
5116
5117 if (expt < minexpt) {
5118 a = ldexp(fract, expt - mantBits - minexpt);
5119 b = ldexp(1.0, mantBits + minexpt);
5120 retval = a * b;
5121 } else {
5122 retval = ldexp(fract, expt);
5123 }
5124 return retval;
5125 }
5126
5127 /*
5128 *----------------------------------------------------------------------
5129 *
5130 * TclFormatNaN --
5131 *
5132 * Makes the string representation of a "Not a Number"
5133 *
5134 * Results:
5135 * None.
5136 *
5137 * Side effects:
5138 * Stores the string representation in the supplied buffer, which must be
5139 * at least TCL_DOUBLE_SPACE characters.
5140 *
5141 *----------------------------------------------------------------------
5142 */
5143
5144 void
5145 TclFormatNaN(
5146 double value, /* The Not-a-Number to format. */
5147 char *buffer) /* String representation. */
5148 {
5149 #ifndef IEEE_FLOATING_POINT
5150 strcpy(buffer, "NaN");
5151 return;
5152 #else
5153 union {
5154 double dv;
5155 Tcl_WideUInt iv;
5156 } bitwhack;
5157
5158 bitwhack.dv = value;
5159 if (n770_fp) {
5160 bitwhack.iv = Nokia770Twiddle(bitwhack.iv);
5161 }
5162 if (bitwhack.iv & ((Tcl_WideUInt)1 << 63)) {
5163 bitwhack.iv &= ~ ((Tcl_WideUInt)1 << 63);
5164 *buffer++ = '-';
5165 }
5166 *buffer++ = 'N';
5167 *buffer++ = 'a';
5168 *buffer++ = 'N';
5169 bitwhack.iv &= (((Tcl_WideUInt) 1) << 51) - 1;
5170 if (bitwhack.iv != 0) {
5171 snprintf(buffer, TCL_DOUBLE_SPACE, "(%" TCL_LL_MODIFIER "x)", bitwhack.iv);
5172 } else {
5173 *buffer = '\0';
5174 }
5175 #endif /* IEEE_FLOATING_POINT */
5176 }
5177
5178 /*
5179 *----------------------------------------------------------------------
5180 *
5181 * Nokia770Twiddle --
5182 *
5183 * Transpose the two words of a number for Nokia 770 floating point
5184 * handling.
5185 *
5186 *----------------------------------------------------------------------
5187 */
5188 #ifdef IEEE_FLOATING_POINT
5189 static Tcl_WideUInt
5190 Nokia770Twiddle(
5191 Tcl_WideUInt w) /* Number to transpose. */
5192 {
5193 return (((w >> 32) & 0xFFFFFFFF) | (w << 32));
5194 }
5195 #endif
5196
5197 /*
5198 *----------------------------------------------------------------------
5199 *
5200 * TclNokia770Doubles --
5201 *
5202 * Transpose the two words of a number for Nokia 770 floating point
5203 * handling.
5204 *
5205 *----------------------------------------------------------------------
5206 */
5207
5208 int
5209 TclNokia770Doubles(void)
5210 {
5211 return n770_fp;
5212 }
5213
5214 /*
5215 * Local Variables:
5216 * mode: c
5217 * c-basic-offset: 4
5218 * fill-column: 78
5219 * End:
5220 */