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.
10 * Copyright (c) 2005 by Kevin B. Kenny. All rights reserved.
12 * See the file "license.terms" for information on usage and redistribution of
13 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
22 #define copysign _copysign
26 * Define KILL_OCTAL to suppress interpretation of numbers with leading zero
27 * as octal. (Ceterum censeo: numeros octonarios delendos esse.)
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.
38 #if (FLT_RADIX == 2) && (DBL_MANT_DIG == 53) && (DBL_MAX_EXP == 1024)
39 # define IEEE_FLOATING_POINT
43 * Rounding controls. (Thanks a lot, Intel!)
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.
56 typedef unsigned int fpu_control_t __attribute__ ((__mode__ (__HI__)));
58 #define _FPU_GETCW(cw) __asm__ __volatile__ ("fnstcw %0" : "=m" (*&cw))
59 #define _FPU_SETCW(cw) __asm__ __volatile__ ("fldcw %0" : : "m" (*&cw))
60 # define FPU_IEEE_ROUNDING 0x027F
61 # define ADJUST_FPU_CONTROL_WORD
62 #define TCL_IEEE_DOUBLE_ROUNDING \
63 fpu_control_t roundTo53Bits = FPU_IEEE_ROUNDING; \
64 fpu_control_t oldRoundingMode; \
65 _FPU_GETCW(oldRoundingMode); \
66 _FPU_SETCW(roundTo53Bits)
67 #define TCL_DEFAULT_DOUBLE_ROUNDING \
68 _FPU_SETCW(oldRoundingMode)
71 * Sun ProC needs sunmath for rounding control on x86 like gcc above.
75 #define TCL_IEEE_DOUBLE_ROUNDING \
76 ieee_flags("set","precision","double",NULL)
77 #define TCL_DEFAULT_DOUBLE_ROUNDING \
78 ieee_flags("clear","precision",NULL,NULL)
81 * Other platforms are assumed to always operate in full IEEE mode, so we make
82 * the macros to go in and out of that mode do nothing.
85 #else /* !__GNUC__ && !__sun */
86 #define TCL_IEEE_DOUBLE_ROUNDING ((void) 0)
87 #define TCL_DEFAULT_DOUBLE_ROUNDING ((void) 0)
90 #define TCL_IEEE_DOUBLE_ROUNDING ((void) 0)
91 #define TCL_DEFAULT_DOUBLE_ROUNDING ((void) 0)
95 * MIPS floating-point units need special settings in control registers to use
96 * gradual underflow as we expect. This fix is for the MIPSpro compiler.
99 #if defined(__sgi) && defined(_COMPILER_VERSION)
104 * HP's PA_RISC architecture uses 7ff4000000000000 to represent a quiet NaN.
105 * Everyone else uses 7ff8000000000000. (Why, HP, why?)
109 # define NAN_START 0x7FF4
110 # define NAN_MASK (((Tcl_WideUInt) 1) << 50)
112 # define NAN_START 0x7FF8
113 # define NAN_MASK (((Tcl_WideUInt) 1) << 51)
117 * Constants used by this file (most of which are only ever calculated at
121 /* Magic constants */
123 #define LOG10_2 0.3010299956639812
124 #define TWO_OVER_3LOG10 0.28952965460216784
125 #define LOG10_3HALVES_PLUS_FUDGE 0.1760912590558
128 * Definitions of the parts of an IEEE754-format floating point number.
131 #define SIGN_BIT 0x80000000
132 /* Mask for the sign bit in the first word of
134 #define EXP_MASK 0x7FF00000
135 /* Mask for the exponent field in the first
136 * word of a double. */
137 #define EXP_SHIFT 20 /* Shift count to make the exponent an
139 #define HIDDEN_BIT (((Tcl_WideUInt) 0x00100000) << 32)
140 /* Hidden 1 bit for the significand. */
141 #define HI_ORDER_SIG_MASK 0x000FFFFF
142 /* Mask for the high-order part of the
143 * significand in the first word of a
145 #define SIG_MASK (((Tcl_WideUInt) HI_ORDER_SIG_MASK << 32) \
147 /* Mask for the 52-bit significand. */
148 #define FP_PRECISION 53 /* Number of bits of significand plus the
150 #define EXPONENT_BIAS 0x3FF /* Bias of the exponent 0. */
153 * Derived quantities.
156 #define TEN_PMAX 22 /* floor(FP_PRECISION*log(2)/log(5)) */
157 #define QUICK_MAX 14 /* floor((FP_PRECISION-1)*log(2)/log(10))-1 */
158 #define BLETCH 0x10 /* Highest power of two that is greater than
159 * DBL_MAX_10_EXP, divided by 16. */
160 #define DIGIT_GROUP 8 /* floor(MP_DIGIT_BIT*log(2)/log(10)) */
163 * Union used to dismantle floating point numbers.
166 typedef union Double {
168 #ifdef WORDS_BIGENDIAN
180 static int maxpow10_wide; /* The powers of ten that can be represented
181 * exactly as wide integers. */
182 static Tcl_WideUInt *pow10_wide;
184 static double pow10vals[MAXPOW+1];
185 /* The powers of ten that can be represented
186 * exactly as IEEE754 doubles. */
187 static int mmaxpow; /* Largest power of ten that can be
188 * represented exactly in a 'double'. */
189 static int log10_DIGIT_MAX; /* The number of decimal digits that fit in an
191 static int log2FLT_RADIX; /* Logarithm of the floating point radix. */
192 static int mantBits; /* Number of bits in a double's significand */
193 static mp_int pow5[9]; /* Table of powers of 5**(2**n), up to
195 static double tiny = 0.0; /* The smallest representable double. */
196 static int maxDigits; /* The maximum number of digits to the left of
197 * the decimal point of a double. */
198 static int minDigits; /* The maximum number of digits to the right
199 * of the decimal point in a double. */
200 static const double pow_10_2_n[] = { /* Inexact higher powers of ten. */
212 static int n770_fp; /* Flag is 1 on Nokia N770 floating point.
213 * Nokia's floating point has the words
214 * reversed: if big-endian is 7654 3210,
215 * and little-endian is 0123 4567,
216 * then Nokia's FP is 4567 0123;
217 * little-endian within the 32-bit words but
218 * big-endian between them. */
221 * Table of powers of 5 that are small enough to fit in an mp_digit.
224 static const mp_digit dpow5[13] = {
226 625, 3125, 15625, 78125,
227 390625, 1953125, 9765625, 48828125,
232 * Table of powers: pow5_13[n] = 5**(13*2**(n+1))
235 static mp_int pow5_13[5]; /* Table of powers: 5**13, 5**26, 5**52,
237 static const double tens[] = {
238 1e00, 1e01, 1e02, 1e03, 1e04, 1e05, 1e06, 1e07, 1e08, 1e09,
239 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
243 static const int itens [] = {
255 static const double bigtens[] = {
256 1e016, 1e032, 1e064, 1e128, 1e256
260 static const int log2pow5[27] = {
261 01, 3, 5, 7, 10, 12, 14, 17, 19, 21,
262 24, 26, 28, 31, 33, 35, 38, 40, 42, 45,
263 47, 49, 52, 54, 56, 59, 61
265 #define N_LOG2POW5 27
267 static const Tcl_WideUInt wuipow5[27] = {
268 (Tcl_WideUInt) 1, /* 5**0 */
273 (Tcl_WideUInt) 3125, /* 5**5 */
274 (Tcl_WideUInt) 3125*5,
275 (Tcl_WideUInt) 3125*25,
276 (Tcl_WideUInt) 3125*125,
277 (Tcl_WideUInt) 3125*625,
278 (Tcl_WideUInt) 3125*3125, /* 5**10 */
279 (Tcl_WideUInt) 3125*3125*5,
280 (Tcl_WideUInt) 3125*3125*25,
281 (Tcl_WideUInt) 3125*3125*125,
282 (Tcl_WideUInt) 3125*3125*625,
283 (Tcl_WideUInt) 3125*3125*3125, /* 5**15 */
284 (Tcl_WideUInt) 3125*3125*3125*5,
285 (Tcl_WideUInt) 3125*3125*3125*25,
286 (Tcl_WideUInt) 3125*3125*3125*125,
287 (Tcl_WideUInt) 3125*3125*3125*625,
288 (Tcl_WideUInt) 3125*3125*3125*3125, /* 5**20 */
289 (Tcl_WideUInt) 3125*3125*3125*3125*5,
290 (Tcl_WideUInt) 3125*3125*3125*3125*25,
291 (Tcl_WideUInt) 3125*3125*3125*3125*125,
292 (Tcl_WideUInt) 3125*3125*3125*3125*625,
293 (Tcl_WideUInt) 3125*3125*3125*3125*3125, /* 5**25 */
294 (Tcl_WideUInt) 3125*3125*3125*3125*3125*5 /* 5**26 */
298 * Static functions defined in this file.
301 static int AccumulateDecimalDigit(unsigned, int,
302 Tcl_WideUInt *, mp_int *, int);
303 static double MakeHighPrecisionDouble(int signum,
304 mp_int *significand, int nSigDigs, long exponent);
305 static double MakeLowPrecisionDouble(int signum,
306 Tcl_WideUInt significand, int nSigDigs,
308 #ifdef IEEE_FLOATING_POINT
309 static double MakeNaN(int signum, Tcl_WideUInt tag);
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 *,
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 *,
326 static char * BumpUp(char *, char *, int *);
327 static int AdjustRange(double *, int);
328 static char * ShorteningQuickFormat(double, int, int, double,
330 static char * StrictQuickFormat(double, int, int, double,
332 static char * QuickConversion(double, int, int, int, int, int, int,
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(Double *, int, 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,
350 static char * StrictBignumConversionPowD(Double *dPtr, int convType,
351 Tcl_WideUInt bw, int b2, int b5,
352 int sd, int k, int len,
353 int ilim, int ilim1, int *decpt,
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,
364 static char * StrictBignumConversion(Double *dPtr, int convType,
365 Tcl_WideUInt bw, int b2,
366 int s2, int s5, int k, int len,
367 int ilim, int ilim1, int *decpt,
369 static double BignumToBiasedFrExp(const mp_int *big, int *machexp);
370 static double Pow10TimesFrExp(int exponent, double fraction,
372 static double SafeLdExp(double fraction, int exponent);
373 #ifdef IEEE_FLOATING_POINT
374 static Tcl_WideUInt Nokia770Twiddle(Tcl_WideUInt w);
378 *----------------------------------------------------------------------
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.
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.
395 * The argument flags is an input that controls the numeric formats
396 * recognized by the parser. The flag bits are:
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
417 * - TCL_PARSE_NO_WHITESPACE: reject any leading/trailing whitespace
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
427 * The arguments objPtr and endPtrPtr as well as the return code are the
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
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
445 * When the parser determines that a partial string matches a format it
446 * is looking for, the value of endPtrPtr determines what happens:
448 * - If endPtrPtr is NULL, then TCL_ERROR is returned, with error message
449 * generation as above.
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
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.
469 * Returns a standard Tcl result.
472 * The string representaton of objPtr may be generated.
474 * The internal representation and Tcl_ObjType of objPtr may be changed.
475 * This may involve allocation and/or freeing of memory.
477 *----------------------------------------------------------------------
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
489 int numBytes, /* Maximum number of bytes to scan, see
491 const char **endPtrPtr, /* Place to store pointer to the character
492 * that terminated the scan. */
493 int flags) /* Flags governing the parse. */
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
506 enum State acceptState = INITIAL;
508 int signum = 0; /* Sign of the number being parsed. */
509 Tcl_WideUInt significandWide = 0;
510 /* Significand of the number being parsed (if
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
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
530 int exponentSignum = 0; /* Signum of the exponent of a floating point
532 long 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
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;
545 #define ALL_BITS (~(Tcl_WideUInt)0)
546 #define MOST_BITS (ALL_BITS >> 1)
549 * Initialize bytes to start of the object's string rep if the caller
550 * didn't pass anything else.
554 bytes = TclGetString(objPtr);
562 char c = len ? *p : '\0';
567 * Initial state. Acceptable characters are +, -, digits, period,
568 * I, N, and whitespace.
571 if (TclIsSpaceProcM(c)) {
572 if (flags & TCL_PARSE_NO_WHITESPACE) {
576 } else if (c == '+') {
579 } else if (c == '-') {
588 * Scanned a leading + or -. Acceptable characters are digits,
593 if (flags & TCL_PARSE_DECIMAL_ONLY) {
599 } else if (flags & TCL_PARSE_HEXADECIMAL_ONLY) {
601 } else if (flags & TCL_PARSE_BINARY_ONLY) {
603 } else if (flags & TCL_PARSE_OCTAL_ONLY) {
605 } else if (isdigit(UCHAR(c))) {
606 significandWide = c - '0';
610 } else if (flags & TCL_PARSE_INTEGER_ONLY) {
612 } else if (c == '.') {
613 state = LEADING_RADIX_POINT;
615 } else if (c == 'I' || c == 'i') {
618 #ifdef IEEE_FLOATING_POINT
619 } else if (c == 'N' || c == 'n') {
628 * Scanned a leading zero (perhaps with a + or -). Acceptable
629 * inputs are digits, period, X, b, and E. If 8 or 9 is
630 * encountered, the number can't be octal. This state and the
631 * OCTAL state differ only in whether they recognize 'X' and 'b'.
637 if (c == 'x' || c == 'X') {
638 if (flags & (TCL_PARSE_OCTAL_ONLY|TCL_PARSE_BINARY_ONLY)) {
644 if (flags & TCL_PARSE_HEXADECIMAL_ONLY) {
647 if (flags & TCL_PARSE_SCAN_PREFIXES) {
650 if (c == 'b' || c == 'B') {
651 if (flags & TCL_PARSE_OCTAL_ONLY) {
657 if (flags & TCL_PARSE_BINARY_ONLY) {
660 if (c == 'o' || c == 'O') {
672 * Scanned an optional + or -, followed by a string of octal
673 * digits. Acceptable inputs are more digits, period, or E. If 8
674 * or 9 is encountered, commit to floating point.
687 } else if (c >= '1' && c <= '7') {
688 if (objPtr != NULL) {
689 shift = 3 * (numTrailZeros + 1);
690 significandOverflow = AccumulateDecimalDigit(
691 (unsigned)(c-'0'), numTrailZeros,
692 &significandWide, &significandBig,
693 significandOverflow);
695 if (!octalSignificandOverflow) {
697 * Shifting by more bits than are in the value being
698 * shifted is at least de facto nonportable. Check for
699 * too large shifts first.
702 if ((octalSignificandWide != 0)
703 && (((size_t)shift >=
704 CHAR_BIT*sizeof(Tcl_WideUInt))
705 || (octalSignificandWide >
706 (~(Tcl_WideUInt)0 >> shift)))) {
707 octalSignificandOverflow = 1;
708 TclBNInitBignumFromWideUInt(&octalSignificandBig,
709 octalSignificandWide);
712 if (!octalSignificandOverflow) {
713 octalSignificandWide =
714 (octalSignificandWide << shift) + (c - '0');
716 mp_mul_2d(&octalSignificandBig, shift,
717 &octalSignificandBig);
718 mp_add_d(&octalSignificandBig, (mp_digit)(c - '0'),
719 &octalSignificandBig);
722 if (numSigDigs != 0) {
723 numSigDigs += numTrailZeros+1;
736 * No forgiveness for bad digits in explicitly octal numbers.
741 if (flags & TCL_PARSE_INTEGER_ONLY) {
743 * No seeking floating point when parsing only integer.
751 * Scanned a number with a leading zero that contains an 8, 9,
752 * radix point or E. This is an invalid octal number, but might
753 * still be floating point.
760 } else if (isdigit(UCHAR(c))) {
761 if (objPtr != NULL) {
762 significandOverflow = AccumulateDecimalDigit(
763 (unsigned)(c-'0'), numTrailZeros,
764 &significandWide, &significandBig,
765 significandOverflow);
767 if (numSigDigs != 0) {
768 numSigDigs += (numTrailZeros + 1);
775 } else if (c == '.') {
778 } else if (c == 'E' || c == 'e') {
779 state = EXPONENT_START;
786 * Scanned 0x. If state is HEXADECIMAL, scanned at least one
787 * character following the 0x. The only acceptable inputs are
788 * hexadecimal digits.
803 } else if (isdigit(UCHAR(c))) {
805 } else if (c >= 'A' && c <= 'F') {
807 } else if (c >= 'a' && c <= 'f') {
812 if (objPtr != NULL) {
813 shift = 4 * (numTrailZeros + 1);
814 if (!significandOverflow) {
816 * Shifting by more bits than are in the value being
817 * shifted is at least de facto nonportable. Check for too
818 * large shifts first.
821 if (significandWide != 0 &&
822 ((size_t)shift >= CHAR_BIT*sizeof(Tcl_WideUInt) ||
823 significandWide > (~(Tcl_WideUInt)0 >> shift))) {
824 significandOverflow = 1;
825 TclBNInitBignumFromWideUInt(&significandBig,
829 if (!significandOverflow) {
830 significandWide = (significandWide << shift) + d;
832 mp_mul_2d(&significandBig, shift, &significandBig);
833 mp_add_d(&significandBig, (mp_digit) d, &significandBig);
851 } else if (c != '1') {
854 if (objPtr != NULL) {
855 shift = numTrailZeros + 1;
856 if (!significandOverflow) {
858 * Shifting by more bits than are in the value being
859 * shifted is at least de facto nonportable. Check for too
860 * large shifts first.
863 if (significandWide != 0 &&
864 ((size_t)shift >= CHAR_BIT*sizeof(Tcl_WideUInt) ||
865 significandWide > (~(Tcl_WideUInt)0 >> shift))) {
866 significandOverflow = 1;
867 TclBNInitBignumFromWideUInt(&significandBig,
871 if (!significandOverflow) {
872 significandWide = (significandWide << shift) + 1;
874 mp_mul_2d(&significandBig, shift, &significandBig);
875 mp_add_d(&significandBig, (mp_digit) 1, &significandBig);
884 * Scanned an optional + or - followed by a string of decimal
898 } else if (isdigit(UCHAR(c))) {
899 if (objPtr != NULL) {
900 significandOverflow = AccumulateDecimalDigit(
901 (unsigned)(c - '0'), numTrailZeros,
902 &significandWide, &significandBig,
903 significandOverflow);
905 numSigDigs += numTrailZeros+1;
909 } else if (flags & TCL_PARSE_INTEGER_ONLY) {
911 } else if (c == '.') {
914 } else if (c == 'E' || c == 'e') {
915 state = EXPONENT_START;
921 * Found a decimal point. If no digits have yet been scanned, E is
922 * not allowed; otherwise, it introduces the exponent. If at least
923 * one digit has been found, we have a possible complete number.
930 if (c == 'E' || c=='e') {
931 state = EXPONENT_START;
936 case LEADING_RADIX_POINT:
942 } else if (isdigit(UCHAR(c))) {
944 if (objPtr != NULL) {
945 significandOverflow = AccumulateDecimalDigit(
946 (unsigned)(c-'0'), numTrailZeros,
947 &significandWide, &significandBig,
948 significandOverflow);
950 if (numSigDigs != 0) {
951 numSigDigs += numTrailZeros+1;
963 * Scanned the E at the start of an exponent. Make sure a legal
964 * character follows before using the C library strtol routine,
965 * which allows whitespace.
969 state = EXPONENT_SIGNUM;
971 } else if (c == '-') {
973 state = EXPONENT_SIGNUM;
978 case EXPONENT_SIGNUM:
980 * Found the E at the start of the exponent, followed by a sign
984 if (isdigit(UCHAR(c))) {
993 * Found an exponent with at least one digit. Accumulate it,
994 * making sure to hard-pin it to LONG_MAX on overflow.
1000 if (isdigit(UCHAR(c))) {
1001 if (exponent < (LONG_MAX - 9) / 10) {
1002 exponent = 10 * exponent + (c - '0');
1004 exponent = LONG_MAX;
1012 * Parse out INFINITY by simply spelling it out. INF is accepted
1013 * as an abbreviation; other prefices are not.
1017 if (c == 'n' || c == 'N') {
1023 if (c == 'f' || c == 'F') {
1029 acceptState = state;
1032 if (c == 'i' || c == 'I') {
1038 if (c == 'n' || c == 'N') {
1044 if (c == 'i' || c == 'I') {
1050 if (c == 't' || c == 'T') {
1056 if (c == 'y' || c == 'Y') {
1065 #ifdef IEEE_FLOATING_POINT
1067 if (c == 'a' || c == 'A') {
1073 if (c == 'n' || c == 'N') {
1079 acceptState = state;
1089 * Parse NaN(hexdigits)
1098 if (TclIsSpaceProcM(c)) {
1101 if (numSigDigs < 13) {
1102 if (c >= '0' && c <= '9') {
1104 } else if (c >= 'a' && c <= 'f') {
1106 } else if (c >= 'A' && c <= 'F') {
1112 significandWide = (significandWide << 4) + d;
1121 acceptState = state;
1131 if (acceptState == INITIAL) {
1133 * No numeric string at all found.
1137 if (endPtrPtr != NULL) {
1142 * Back up to the last accepting state in the lexer.
1147 if (!(flags & TCL_PARSE_NO_WHITESPACE)) {
1149 * Accept trailing whitespace.
1152 while (len != 0 && TclIsSpaceProcM(*p)) {
1157 if (endPtrPtr == NULL) {
1158 if ((len != 0) && ((numBytes > 0) || (*p != '\0'))) {
1167 * Generate and store the appropriate internal rep.
1170 if (status == TCL_OK && objPtr != NULL) {
1171 TclFreeIntRep(objPtr);
1172 switch (acceptState) {
1178 case LEADING_RADIX_POINT:
1179 case EXPONENT_START:
1180 case EXPONENT_SIGNUM:
1187 #ifdef IEEE_FLOATING_POINT
1193 Tcl_Panic("TclParseNumber: bad acceptState %d parsing '%s'",
1194 acceptState, bytes);
1196 shift = numTrailZeros;
1197 if (!significandOverflow && significandWide != 0 &&
1198 ((size_t)shift >= CHAR_BIT*sizeof(Tcl_WideUInt) ||
1199 significandWide > (MOST_BITS + signum) >> shift)) {
1200 significandOverflow = 1;
1201 TclBNInitBignumFromWideUInt(&significandBig, significandWide);
1204 if (!significandOverflow) {
1205 significandWide <<= shift;
1207 mp_mul_2d(&significandBig, shift, &significandBig);
1214 * Returning a hex integer. Final scaling step.
1217 shift = 4 * numTrailZeros;
1218 if (!significandOverflow && significandWide !=0 &&
1219 ((size_t)shift >= CHAR_BIT*sizeof(Tcl_WideUInt) ||
1220 significandWide > (MOST_BITS + signum) >> shift)) {
1221 significandOverflow = 1;
1222 TclBNInitBignumFromWideUInt(&significandBig, significandWide);
1225 if (!significandOverflow) {
1226 significandWide <<= shift;
1228 mp_mul_2d(&significandBig, shift, &significandBig);
1235 * Returning an octal integer. Final scaling step.
1238 shift = 3 * numTrailZeros;
1239 if (!octalSignificandOverflow && octalSignificandWide != 0 &&
1240 ((size_t)shift >= CHAR_BIT*sizeof(Tcl_WideUInt) ||
1241 octalSignificandWide > (MOST_BITS + signum) >> shift)) {
1242 octalSignificandOverflow = 1;
1243 TclBNInitBignumFromWideUInt(&octalSignificandBig,
1244 octalSignificandWide);
1247 if (!octalSignificandOverflow) {
1248 octalSignificandWide <<= shift;
1250 mp_mul_2d(&octalSignificandBig, shift,
1251 &octalSignificandBig);
1254 if (!octalSignificandOverflow) {
1255 if (octalSignificandWide >
1256 (Tcl_WideUInt)(((~(unsigned long)0) >> 1) + signum)) {
1257 #ifndef TCL_WIDE_INT_IS_LONG
1258 if (octalSignificandWide <= (MOST_BITS + signum)) {
1259 objPtr->typePtr = &tclWideIntType;
1261 objPtr->internalRep.wideValue =
1262 - (Tcl_WideInt) octalSignificandWide;
1264 objPtr->internalRep.wideValue =
1265 (Tcl_WideInt) octalSignificandWide;
1270 TclBNInitBignumFromWideUInt(&octalSignificandBig,
1271 octalSignificandWide);
1272 octalSignificandOverflow = 1;
1274 objPtr->typePtr = &tclIntType;
1276 objPtr->internalRep.longValue =
1277 - (long) octalSignificandWide;
1279 objPtr->internalRep.longValue =
1280 (long) octalSignificandWide;
1284 if (octalSignificandOverflow) {
1286 (void)mp_neg(&octalSignificandBig, &octalSignificandBig);
1288 TclSetBignumInternalRep(objPtr, &octalSignificandBig);
1294 significandOverflow = AccumulateDecimalDigit(0, numTrailZeros-1,
1295 &significandWide, &significandBig, significandOverflow);
1296 if (!significandOverflow && (significandWide > MOST_BITS+signum)) {
1297 significandOverflow = 1;
1298 TclBNInitBignumFromWideUInt(&significandBig, significandWide);
1301 if (!significandOverflow) {
1302 if (significandWide >
1303 (Tcl_WideUInt)(((~(unsigned long)0) >> 1) + signum)) {
1304 #ifndef TCL_WIDE_INT_IS_LONG
1305 if (significandWide <= MOST_BITS+signum) {
1306 objPtr->typePtr = &tclWideIntType;
1308 objPtr->internalRep.wideValue =
1309 - (Tcl_WideInt) significandWide;
1311 objPtr->internalRep.wideValue =
1312 (Tcl_WideInt) significandWide;
1317 TclBNInitBignumFromWideUInt(&significandBig,
1319 significandOverflow = 1;
1321 objPtr->typePtr = &tclIntType;
1323 objPtr->internalRep.longValue =
1324 - (long) significandWide;
1326 objPtr->internalRep.longValue =
1327 (long) significandWide;
1331 if (significandOverflow) {
1333 (void)mp_neg(&significandBig, &significandBig);
1335 TclSetBignumInternalRep(objPtr, &significandBig);
1343 * Here, we're parsing a floating-point number. 'significandWide'
1344 * or 'significandBig' contains the exact significand, according
1345 * to whether 'significandOverflow' is set. The desired floating
1346 * point value is significand * 10**k, where
1347 * k = numTrailZeros+exponent-numDigitsAfterDp.
1350 objPtr->typePtr = &tclDoubleType;
1351 if (exponentSignum) {
1353 * At this point exponent>=0, so the following calculation
1356 exponent = -exponent;
1360 * Adjust the exponent for the number of trailing zeros that
1361 * have not been accumulated, and the number of digits after
1362 * the decimal point. Pin any overflow to LONG_MAX/LONG_MIN
1366 if (exponent >= 0) {
1367 if (exponent - numDigitsAfterDp > LONG_MAX - numTrailZeros) {
1368 exponent = LONG_MAX;
1370 exponent = exponent - numDigitsAfterDp + numTrailZeros;
1373 if (exponent + numTrailZeros < LONG_MIN + numDigitsAfterDp) {
1374 exponent = LONG_MIN;
1376 exponent = exponent + numTrailZeros - numDigitsAfterDp;
1381 * The desired number is now significandWide * 10**exponent
1382 * or significandBig * 10**exponent, depending on whether
1383 * the significand has overflowed a wide int.
1385 if (!significandOverflow) {
1386 objPtr->internalRep.doubleValue = MakeLowPrecisionDouble(
1387 signum, significandWide, numSigDigs, exponent);
1389 objPtr->internalRep.doubleValue = MakeHighPrecisionDouble(
1390 signum, &significandBig, numSigDigs, exponent);
1397 objPtr->internalRep.doubleValue = -HUGE_VAL;
1399 objPtr->internalRep.doubleValue = HUGE_VAL;
1401 objPtr->typePtr = &tclDoubleType;
1404 #ifdef IEEE_FLOATING_POINT
1407 objPtr->internalRep.doubleValue = MakeNaN(signum, significandWide);
1408 objPtr->typePtr = &tclDoubleType;
1412 /* This case only to silence compiler warning. */
1413 Tcl_Panic("TclParseNumber: state INITIAL can't happen here");
1418 * Format an error message when an invalid number is encountered.
1421 if (status != TCL_OK) {
1422 if (interp != NULL) {
1423 Tcl_Obj *msg = Tcl_ObjPrintf("expected %s but got \"",
1426 Tcl_AppendLimitedToObj(msg, bytes, numBytes, 50, "");
1427 Tcl_AppendToObj(msg, "\"", -1);
1428 if (state == BAD_OCTAL) {
1429 Tcl_AppendToObj(msg, " (looks like invalid octal number)", -1);
1431 Tcl_SetObjResult(interp, msg);
1432 Tcl_SetErrorCode(interp, "TCL", "VALUE", "NUMBER", NULL);
1440 if (octalSignificandOverflow) {
1441 mp_clear(&octalSignificandBig);
1443 if (significandOverflow) {
1444 mp_clear(&significandBig);
1450 *----------------------------------------------------------------------
1452 * AccumulateDecimalDigit --
1454 * Consume a decimal digit in a number being scanned.
1457 * Returns 1 if the number has overflowed to a bignum, 0 if it still fits
1458 * in a wide integer.
1461 * Updates either the wide or bignum representation.
1463 *----------------------------------------------------------------------
1467 AccumulateDecimalDigit(
1468 unsigned digit, /* Digit being scanned. */
1469 int numZeros, /* Count of zero digits preceding the digit
1471 Tcl_WideUInt *wideRepPtr, /* Representation of the partial number as a
1473 mp_int *bignumRepPtr, /* Representation of the partial number as a
1475 int bignumFlag) /* Flag == 1 if the number overflowed previous
1482 * Try wide multiplication first.
1489 * There's no need to multiply if the multiplicand is zero.
1492 *wideRepPtr = digit;
1494 } else if (numZeros >= maxpow10_wide
1495 || w > ((~(Tcl_WideUInt)0)-digit)/pow10_wide[numZeros+1]) {
1497 * Wide multiplication will overflow. Expand the number to a
1498 * bignum and fall through into the bignum case.
1501 TclBNInitBignumFromWideUInt(bignumRepPtr, w);
1504 * Wide multiplication.
1507 *wideRepPtr = w * pow10_wide[numZeros+1] + digit;
1513 * Bignum multiplication.
1516 if (numZeros < log10_DIGIT_MAX) {
1518 * Up to about 8 zeros - single digit multiplication.
1521 mp_mul_d(bignumRepPtr, (mp_digit) pow10_wide[numZeros+1],
1523 mp_add_d(bignumRepPtr, (mp_digit) digit, bignumRepPtr);
1526 * More than single digit multiplication. Multiply by the appropriate
1527 * small powers of 5, and then shift. Large strings of zeroes are
1528 * eaten 256 at a time; this is less efficient than it could be, but
1529 * seems implausible. We presume that MP_DIGIT_BIT is at least 27. The
1530 * first multiplication, by up to 10**7, is done with a one-DIGIT
1531 * multiply (this presumes that MP_DIGIT_BIT >= 24).
1535 mp_mul_d(bignumRepPtr, (mp_digit) pow10_wide[n&0x7], bignumRepPtr);
1536 for (i=3; i<=7; ++i) {
1538 mp_mul(bignumRepPtr, pow5+i, bignumRepPtr);
1542 mp_mul(bignumRepPtr, pow5+8, bignumRepPtr);
1545 mp_mul_2d(bignumRepPtr, (int)(numZeros+1)&~0x7, bignumRepPtr);
1546 mp_add_d(bignumRepPtr, (mp_digit) digit, bignumRepPtr);
1553 *----------------------------------------------------------------------
1555 * MakeLowPrecisionDouble --
1557 * Makes the double precision number, signum*significand*10**exponent.
1560 * Returns the constructed number.
1562 * Common cases, where there are few enough digits that the number can be
1563 * represented with at most roundoff, are handled specially here. If the
1564 * number requires more than one rounded operation to compute, the code
1565 * promotes the significand to a bignum and calls MakeHighPrecisionDouble
1568 *----------------------------------------------------------------------
1572 MakeLowPrecisionDouble(
1573 int signum, /* 1 if the number is negative, 0 otherwise */
1574 Tcl_WideUInt significand, /* Significand of the number */
1575 int numSigDigs, /* Number of digits in the significand */
1576 long exponent) /* Power of ten */
1578 double retval; /* Value of the number. */
1579 mp_int significandBig; /* Significand expressed as a bignum. */
1582 * With gcc on x86, the floating point rounding mode is double-extended.
1583 * This causes the result of double-precision calculations to be rounded
1584 * twice: once to the precision of double-extended and then again to the
1585 * precision of double. Double-rounding introduces gratuitous errors of 1
1586 * ulp, so we need to change rounding mode to 53-bits.
1589 TCL_IEEE_DOUBLE_ROUNDING;
1592 * Test for the easy cases.
1595 if (significand == 0) {
1596 return copysign(0.0, -signum);
1598 if (numSigDigs <= QUICK_MAX) {
1599 if (exponent >= 0) {
1600 if (exponent <= mmaxpow) {
1602 * The significand is an exact integer, and so is
1603 * 10**exponent. The product will be correct to within 1/2 ulp
1604 * without special handling.
1608 ((Tcl_WideInt)significand * pow10vals[exponent]);
1611 int diff = QUICK_MAX - numSigDigs;
1613 if (exponent-diff <= mmaxpow) {
1615 * 10**exponent is not an exact integer, but
1616 * 10**(exponent-diff) is exact, and so is
1617 * significand*10**diff, so we can still compute the value
1618 * with only one roundoff.
1621 volatile double factor = (double)
1622 ((Tcl_WideInt)significand * pow10vals[diff]);
1623 retval = factor * pow10vals[exponent-diff];
1628 if (exponent >= -mmaxpow) {
1630 * 10**-exponent is an exact integer, and so is the
1631 * significand. Compute the result by one division, again with
1632 * only one rounding.
1636 ((Tcl_WideInt)significand / pow10vals[-exponent]);
1643 * All the easy cases have failed. Promote ths significand to bignum and
1644 * call MakeHighPrecisionDouble to do it the hard way.
1647 TclBNInitBignumFromWideUInt(&significandBig, significand);
1648 retval = MakeHighPrecisionDouble(0, &significandBig, numSigDigs,
1650 mp_clear(&significandBig);
1653 * Come here to return the computed value.
1662 * On gcc on x86, restore the floating point mode word.
1665 TCL_DEFAULT_DOUBLE_ROUNDING;
1671 *----------------------------------------------------------------------
1673 * MakeHighPrecisionDouble --
1675 * Makes the double precision number, signum*significand*10**exponent.
1678 * Returns the constructed number.
1680 * MakeHighPrecisionDouble is used when arbitrary-precision arithmetic is
1681 * needed to ensure correct rounding. It begins by calculating a
1682 * low-precision approximation to the desired number, and then refines
1683 * the answer in high precision.
1685 *----------------------------------------------------------------------
1689 MakeHighPrecisionDouble(
1690 int signum, /* 1=negative, 0=nonnegative */
1691 mp_int *significand, /* Exact significand of the number */
1692 int numSigDigs, /* Number of significant digits */
1693 long exponent) /* Power of 10 by which to multiply */
1696 int machexp; /* Machine exponent of a power of 10. */
1699 * With gcc on x86, the floating point rounding mode is double-extended.
1700 * This causes the result of double-precision calculations to be rounded
1701 * twice: once to the precision of double-extended and then again to the
1702 * precision of double. Double-rounding introduces gratuitous errors of 1
1703 * ulp, so we need to change rounding mode to 53-bits.
1706 TCL_IEEE_DOUBLE_ROUNDING;
1709 * Quick checks for zero, and over/underflow. Be careful to avoid
1710 * integer overflow when calculating with 'exponent'.
1713 if (mp_iszero(significand)) {
1714 return copysign(0.0, -signum);
1716 if (exponent >= 0 && exponent-1 > maxDigits-numSigDigs) {
1719 } else if (exponent < 0 && numSigDigs+exponent < minDigits+1) {
1725 * Develop a first approximation to the significand. It is tempting simply
1726 * to force bignum to double, but that will overflow on input numbers like
1727 * 1.[string repeat 0 1000]1; while this is a not terribly likely
1728 * scenario, we still have to deal with it. Use fraction and exponent
1729 * instead. Once we have the significand, multiply by 10**exponent. Test
1730 * for overflow. Convert back to a double, and test for underflow.
1733 retval = BignumToBiasedFrExp(significand, &machexp);
1734 retval = Pow10TimesFrExp(exponent, retval, &machexp);
1735 if (machexp > DBL_MAX_EXP*log2FLT_RADIX) {
1739 retval = SafeLdExp(retval, machexp);
1741 tiny = SafeLdExp(1.0, DBL_MIN_EXP * log2FLT_RADIX - mantBits);
1743 if (retval < tiny) {
1748 * Refine the result twice. (The second refinement should be necessary
1749 * only if the best approximation is a power of 2 minus 1/2 ulp).
1752 retval = RefineApproximation(retval, significand, exponent);
1753 retval = RefineApproximation(retval, significand, exponent);
1756 * Come here to return the computed value.
1765 * On gcc on x86, restore the floating point mode word.
1768 TCL_DEFAULT_DOUBLE_ROUNDING;
1774 *----------------------------------------------------------------------
1778 * Makes a "Not a Number" given a set of bits to put in the tag bits
1780 * Note that a signalling NaN is never returned.
1782 *----------------------------------------------------------------------
1785 #ifdef IEEE_FLOATING_POINT
1788 int signum, /* Sign bit (1=negative, 0=nonnegative. */
1789 Tcl_WideUInt tags) /* Tag bits to put in the NaN. */
1797 theNaN.iv &= (((Tcl_WideUInt) 1) << 51) - 1;
1799 theNaN.iv |= ((Tcl_WideUInt) (0x8000 | NAN_START)) << 48;
1801 theNaN.iv |= ((Tcl_WideUInt) NAN_START) << 48;
1804 theNaN.iv = Nokia770Twiddle(theNaN.iv);
1811 *----------------------------------------------------------------------
1813 * RefineApproximation --
1815 * Given a poor approximation to a floating point number, returns a
1816 * better one. (The better approximation is correct to within 1 ulp, and
1817 * is entirely correct if the poor approximation is correct to 1 ulp.)
1820 * Returns the improved result.
1822 *----------------------------------------------------------------------
1826 RefineApproximation(
1827 double approxResult, /* Approximate result of conversion. */
1828 mp_int *exactSignificand, /* Integer significand. */
1829 int exponent) /* Power of 10 to multiply by significand. */
1831 int M2, M5; /* Powers of 2 and of 5 needed to put the
1832 * decimal and binary numbers over a common
1834 double significand; /* Sigificand of the binary number. */
1835 int binExponent; /* Exponent of the binary number. */
1836 int msb; /* Most significant bit position of an
1837 * intermediate result. */
1838 int nDigits; /* Number of mp_digit's in an intermediate
1840 mp_int twoMv; /* Approx binary value expressed as an exact
1841 * integer scaled by the multiplier 2M. */
1842 mp_int twoMd; /* Exact decimal value expressed as an exact
1843 * integer scaled by the multiplier 2M. */
1844 int scale; /* Scale factor for M. */
1845 int multiplier; /* Power of two to scale M. */
1846 double num, den; /* Numerator and denominator of the correction
1848 double quot; /* Correction term. */
1849 double minincr; /* Lower bound on the absolute value of the
1850 * correction term. */
1851 int roundToEven = 0; /* Flag == TRUE if we need to invoke
1852 * "round to even" functionality */
1853 double rteSignificand; /* Significand of the round-to-even result */
1854 int rteExponent; /* Exponent of the round-to-even result */
1855 int shift; /* Shift count for converting numerator
1856 * and denominator of corrector to floating
1858 Tcl_WideInt rteSigWide; /* Wide integer version of the significand
1859 * for testing evenness */
1863 * The first approximation is always low. If we find that it's HUGE_VAL,
1867 if (approxResult == HUGE_VAL) {
1868 return approxResult;
1870 significand = frexp(approxResult, &binExponent);
1873 * We are trying to compute a corrector term that, when added to the
1874 * approximate result, will yield close to the exact result.
1875 * The exact result is exactSignificand * 10**exponent.
1876 * The approximate result is significand * 2**binExponent
1877 * If exponent<0, we need to multiply the exact value by 10**-exponent
1878 * to make it an integer, plus another factor of 2 to decide on rounding.
1879 * Similarly if binExponent<FP_PRECISION, we need
1880 * to multiply by 2**FP_PRECISION to make the approximate value an integer.
1882 * Let M = 2**M2 * 5**M5 be the least common multiple of these two
1886 i = mantBits - binExponent;
1902 * Compute twoMv as 2*M*v, where v is the approximate value.
1903 * This is done by bit-whacking to calculate 2**(M2+1)*significand,
1904 * and then multiplying by 5**M5.
1907 msb = binExponent + M2; /* 1008 */
1908 nDigits = msb / MP_DIGIT_BIT + 1;
1909 mp_init_size(&twoMv, nDigits);
1910 i = (msb % MP_DIGIT_BIT + 1);
1911 twoMv.used = nDigits;
1912 significand *= SafeLdExp(1.0, i);
1913 while (--nDigits >= 0) {
1914 twoMv.dp[nDigits] = (mp_digit) significand;
1915 significand -= (mp_digit) significand;
1916 significand = SafeLdExp(significand, MP_DIGIT_BIT);
1918 for (i = 0; i <= 8; ++i) {
1919 if (M5 & (1 << i)) {
1920 mp_mul(&twoMv, pow5+i, &twoMv);
1925 * Compute twoMd as 2*M*d, where d is the exact value.
1926 * This is done by multiplying by 5**(M5+exponent) and then multiplying
1927 * by 2**(M5+exponent+1), which is, of couse, a left shift.
1930 mp_init_copy(&twoMd, exactSignificand);
1931 for (i=0; i<=8; ++i) {
1932 if ((M5 + exponent) & (1 << i)) {
1933 mp_mul(&twoMd, pow5+i, &twoMd);
1936 mp_mul_2d(&twoMd, M2+exponent+1, &twoMd);
1939 * Now let twoMd = twoMd - twoMv, the difference between the exact and
1940 * approximate values.
1943 mp_sub(&twoMd, &twoMv, &twoMd);
1946 * The result, 2Mv-2Md, needs to be divided by 2M to yield a correction
1947 * term. Because 2M may well overflow a double, we need to scale the
1948 * denominator by a factor of 2**binExponent-mantBits. Place that factor
1949 * times 1/2 ULP into twoMd.
1952 scale = binExponent - mantBits - 1;
1954 for (i=0; i<=8; ++i) {
1955 if (M5 & (1 << i)) {
1956 mp_mul(&twoMv, pow5+i, &twoMv);
1959 multiplier = M2 + scale + 1;
1960 if (multiplier > 0) {
1961 mp_mul_2d(&twoMv, multiplier, &twoMv);
1962 } else if (multiplier < 0) {
1963 mp_div_2d(&twoMv, -multiplier, &twoMv, NULL);
1967 * Will the eventual correction term be less than, equal to, or
1968 * greater than 1/2 ULP?
1971 switch (mp_cmp_mag(&twoMd, &twoMv)) {
1974 * If the error is less than 1/2 ULP, there's no correction to make.
1978 return approxResult;
1981 * If the error is exactly 1/2 ULP, we need to round to even.
1987 * We need to correct the result if the error exceeds 1/2 ULP.
1993 * If we're in the 'round to even' case, and the significand is already
1994 * even, we're done. Return the approximate result.
1997 rteSignificand = frexp(approxResult, &rteExponent);
1998 rteSigWide = (Tcl_WideInt) ldexp(rteSignificand, FP_PRECISION);
1999 if ((rteSigWide & 1) == 0) {
2002 return approxResult;
2007 * Reduce the numerator and denominator of the corrector term so that
2008 * they will fit in the floating point precision.
2010 shift = mp_count_bits(&twoMv) - FP_PRECISION - 1;
2012 mp_div_2d(&twoMv, shift, &twoMv, NULL);
2013 mp_div_2d(&twoMd, shift, &twoMd, NULL);
2017 * Convert the numerator and denominator of the corrector term accurately
2018 * to floating point numbers.
2021 num = TclBignumToDouble(&twoMd);
2022 den = TclBignumToDouble(&twoMv);
2024 quot = SafeLdExp(num/den, scale);
2025 minincr = SafeLdExp(1.0, binExponent-mantBits);
2027 if (quot<0. && quot>-minincr) {
2029 } else if (quot>0. && quot<minincr) {
2036 return approxResult + quot;
2040 *----------------------------------------------------------------------
2044 * Multiply a bignum by a power of 5.
2047 * Stores base*5**n in result.
2049 *----------------------------------------------------------------------
2054 mp_int *base, /* Number to multiply. */
2055 unsigned n, /* Power of 5 to multiply by. */
2056 mp_int *result) /* Place to store the result. */
2063 mp_mul_d(p, dpow5[r], result);
2069 mp_mul(p, pow5_13+r, result);
2081 *----------------------------------------------------------------------
2083 * NormalizeRightward --
2085 * Shifts a number rightward until it is odd (that is, until the least
2086 * significant bit is nonzero.
2089 * Returns the number of bit positions by which the number was shifted.
2092 * Shifts the number in place; *wPtr is replaced by the shifted number.
2094 *----------------------------------------------------------------------
2099 Tcl_WideUInt *wPtr) /* INOUT: Number to shift. */
2102 Tcl_WideUInt w = *wPtr;
2104 if (!(w & (Tcl_WideUInt) 0xFFFFFFFF)) {
2107 if (!(w & (Tcl_WideUInt) 0xFFFF)) {
2110 if (!(w & (Tcl_WideUInt) 0xFF)) {
2113 if (!(w & (Tcl_WideUInt) 0xF)) {
2127 *----------------------------------------------------------------------
2129 * RequiredPrecision --
2131 * Determines the number of bits needed to hold an intger.
2134 * Returns the position of the most significant bit (0 - 63). Returns 0
2135 * if the number is zero.
2137 *----------------------------------------------------------------------
2142 Tcl_WideUInt w) /* Number to interrogate. */
2147 if (w & ((Tcl_WideUInt) 0xFFFFFFFF << 32)) {
2148 wi = (unsigned long) (w >> 32); rv = 32;
2150 wi = (unsigned long) w; rv = 0;
2152 if (wi & 0xFFFF0000) {
2153 wi >>= 16; rv += 16;
2174 *----------------------------------------------------------------------
2176 * DoubleToExpAndSig --
2178 * Separates a 'double' into exponent and significand.
2181 * Stores the significand in '*significand' and the exponent in '*expon'
2182 * so that dv == significand * 2.0**expon, and significand is odd. Also
2183 * stores the position of the leftmost 1-bit in 'significand' in 'bits'.
2185 *----------------------------------------------------------------------
2190 double dv, /* Number to convert. */
2191 Tcl_WideUInt *significand, /* OUTPUT: Significand of the number. */
2192 int *expon, /* OUTPUT: Exponent to multiply the number
2194 int *bits) /* OUTPUT: Number of significant bits. */
2196 Double d; /* Number being converted. */
2197 Tcl_WideUInt z; /* Significand under construction. */
2198 int de; /* Exponent of the number. */
2199 int k; /* Bit count. */
2204 * Extract exponent and significand.
2207 de = (d.w.word0 & EXP_MASK) >> EXP_SHIFT;
2211 k = NormalizeRightward(&z);
2212 *bits = FP_PRECISION - k;
2213 *expon = k + (de - EXPONENT_BIAS) - (FP_PRECISION-1);
2215 k = NormalizeRightward(&z);
2216 *expon = k + (de - EXPONENT_BIAS) - (FP_PRECISION-1) + 1;
2217 *bits = RequiredPrecision(z);
2223 *----------------------------------------------------------------------
2225 * TakeAbsoluteValue --
2227 * Takes the absolute value of a 'double' including 0, Inf and NaN
2230 * The 'double' in *d is replaced with its absolute value. The signum is
2231 * stored in 'sign': 1 for negative, 0 for nonnegative.
2233 *----------------------------------------------------------------------
2238 Double *d, /* Number to replace with absolute value. */
2239 int *sign) /* Place to put the signum. */
2241 if (d->w.word0 & SIGN_BIT) {
2243 d->w.word0 &= ~SIGN_BIT;
2250 *----------------------------------------------------------------------
2252 * FormatInfAndNaN --
2254 * Bailout for formatting infinities and Not-A-Number.
2257 * Returns one of the strings 'Infinity' and 'NaN'. The string returned
2258 * must be freed by the caller using 'ckfree'.
2261 * Stores 9999 in *decpt, and sets '*endPtr' to designate the terminating
2262 * NUL byte of the string if 'endPtr' is not NULL.
2264 *----------------------------------------------------------------------
2267 static inline char *
2269 Double *d, /* Exceptional number to format. */
2270 int *decpt, /* Decimal point to set to a bogus value. */
2271 char **endPtr) /* Pointer to the end of the formatted data */
2276 if (!(d->w.word1) && !(d->w.word0 & HI_ORDER_SIG_MASK)) {
2277 retval = ckalloc(9);
2278 strcpy(retval, "Infinity");
2280 *endPtr = retval + 8;
2283 retval = ckalloc(4);
2284 strcpy(retval, "NaN");
2286 *endPtr = retval + 3;
2293 *----------------------------------------------------------------------
2297 * Bailout to format a zero floating-point number.
2300 * Returns the constant string "0"
2303 * Stores 1 in '*decpt' and puts a pointer to the NUL byte terminating
2304 * the string in '*endPtr' if 'endPtr' is not NULL.
2306 *----------------------------------------------------------------------
2309 static inline char *
2311 int *decpt, /* Location of the decimal point. */
2312 char **endPtr) /* Pointer to the end of the formatted data */
2314 char *retval = ckalloc(2);
2316 strcpy(retval, "0");
2325 *----------------------------------------------------------------------
2327 * ApproximateLog10 --
2329 * Computes a two-term Taylor series approximation to the common log of a
2330 * number, and computes the number's binary log.
2333 * Return an approximation to floor(log10(bw*2**be)) that is either exact
2336 *----------------------------------------------------------------------
2341 Tcl_WideUInt bw, /* Integer significand of the number. */
2342 int be, /* Power of two to scale bw. */
2343 int bbits) /* Number of bits of precision in bw. */
2345 int i; /* Log base 2 of the number. */
2346 int k; /* Floor(Log base 10 of the number) */
2347 double ds; /* Mantissa of the number. */
2351 * Compute i and d2 such that d = d2*2**i, and 1 < d2 < 2.
2352 * Compute an approximation to log10(d),
2353 * log10(d) ~ log10(2) * i + log10(1.5)
2354 * + (significand-1.5)/(1.5 * log(10))
2357 d2.q = bw << (FP_PRECISION - bbits) & SIG_MASK;
2358 d2.w.word0 |= (EXPONENT_BIAS) << EXP_SHIFT;
2360 ds = (d2.d - 1.5) * TWO_OVER_3LOG10
2361 + LOG10_3HALVES_PLUS_FUDGE + LOG10_2 * i;
2370 *----------------------------------------------------------------------
2374 * Improves the result of ApproximateLog10 for numbers in the range
2375 * 1 .. 10**(TEN_PMAX)-1
2378 * Sets k_check to 0 if the new result is known to be exact, and to 1 if
2379 * it may still be one too high.
2382 * Returns the improved approximation to log10(d).
2384 *----------------------------------------------------------------------
2389 double d, /* Original number to format. */
2390 int k, /* Characteristic(Log base 10) of the
2392 int *k_check) /* Flag == 1 if k is inexact. */
2395 * Performance hack. If k is in the range 0..TEN_PMAX, then we can use a
2396 * powers-of-ten table to check it.
2399 if (k >= 0 && k <= TEN_PMAX) {
2411 *----------------------------------------------------------------------
2415 * Prepares to format a floating-point number as decimal.
2418 * floor(log10*x) is k (or possibly k-1). floor(log2(x) is i. The
2419 * significand of x requires bbits bits to represent.
2422 * Determines integers b2, b5, s2, s5 so that sig*2**b2*5**b5/2**s2*2**s5
2423 * exactly represents the value of the x/10**k. This value will lie in
2424 * the range [1 .. 10), and allows for computing successive digits by
2425 * multiplying sig%10 by 10.
2427 *----------------------------------------------------------------------
2432 int be, /* Exponent part of number: d = bw * 2**be. */
2433 int k, /* Characteristic of log10(number). */
2434 int *b2, /* OUTPUT: Power of 2 in the numerator. */
2435 int *b5, /* OUTPUT: Power of 5 in the numerator. */
2436 int *s2, /* OUTPUT: Power of 2 in the denominator. */
2437 int *s5) /* OUTPUT: Power of 5 in the denominator. */
2440 * Scale numerator and denominator powers of 2 so that the input binary
2441 * number is the ratio of integers.
2453 * Scale numerator and denominator so that the output decimal number is
2454 * the ratio of integers.
2469 *----------------------------------------------------------------------
2471 * SetPrecisionLimits --
2473 * Determines how many digits of significance should be computed (and,
2474 * hence, how much memory need be allocated) for formatting a floating
2477 * Given that 'k' is floor(log10(x)):
2478 * if 'shortest' format is used, there will be at most 18 digits in the
2480 * if 'F' format is used, there will be at most 'ndigits' + k + 1 digits
2481 * if 'E' format is used, there will be exactly 'ndigits' digits.
2484 * Adjusts '*ndigitsPtr' to have a valid value. Stores the maximum memory
2485 * allocation needed in *iPtr. Sets '*iLimPtr' to the limiting number of
2486 * digits to convert if k has been guessed correctly, and '*iLim1Ptr' to
2487 * the limiting number of digits to convert if k has been guessed to be
2490 *----------------------------------------------------------------------
2495 int convType, /* Type of conversion: TCL_DD_SHORTEST,
2496 * TCL_DD_STEELE0, TCL_DD_E_FMT,
2498 int k, /* Floor(log10(number to convert)) */
2499 int *ndigitsPtr, /* IN/OUT: Number of digits requested (will be
2500 * adjusted if needed). */
2501 int *iPtr, /* OUT: Maximum number of digits to return. */
2502 int *iLimPtr, /* OUT: Number of digits of significance if
2503 * the bignum method is used.*/
2504 int *iLim1Ptr) /* OUT: Number of digits of significance if
2505 * the quick method is used. */
2508 case TCL_DD_SHORTEST0:
2509 case TCL_DD_STEELE0:
2510 *iLimPtr = *iLim1Ptr = -1;
2514 case TCL_DD_E_FORMAT:
2515 if (*ndigitsPtr <= 0) {
2518 *iLimPtr = *iLim1Ptr = *iPtr = *ndigitsPtr;
2520 case TCL_DD_F_FORMAT:
2521 *iPtr = *ndigitsPtr + k + 1;
2523 *iLim1Ptr = *iPtr - 1;
2532 Tcl_Panic("impossible conversion type in TclDoubleDigits");
2537 *----------------------------------------------------------------------
2541 * Increases a string of digits ending in a series of nines to designate
2542 * the next higher number. xxxxb9999... -> xxxx(b+1)0000...
2545 * Returns a pointer to the end of the adjusted string.
2548 * In the case that the string consists solely of '999999', sets it to
2549 * "1" and moves the decimal point (*kPtr) one place to the right.
2551 *----------------------------------------------------------------------
2554 static inline char *
2556 char *s, /* Cursor pointing one past the end of the
2558 char *retval, /* Start of the string of digits. */
2559 int *kPtr) /* Position of the decimal point. */
2561 while (*--s == '9') {
2574 *----------------------------------------------------------------------
2578 * Rescales a 'double' in preparation for formatting it using the 'quick'
2579 * double-to-string method.
2582 * Returns the precision that has been lost in the prescaling as a count
2583 * of units in the least significant place.
2585 *----------------------------------------------------------------------
2590 double *dPtr, /* INOUT: Number to adjust. */
2591 int k) /* IN: floor(log10(d)) */
2593 int ieps; /* Number of roundoff errors that have
2595 double d = *dPtr; /* Number to adjust. */
2603 * The number must be reduced to bring it into range.
2610 d /= bigtens[N_BIGTENS - 1];
2614 for (; j != 0; j>>=1) {
2622 } else if ((j1 = -k) != 0) {
2624 * The number must be increased to bring it into range.
2627 d *= tens[j1 & 0xF];
2629 for (j = j1>>4; j; j>>=1) {
2643 *----------------------------------------------------------------------
2645 * ShorteningQuickFormat --
2647 * Returns a 'quick' format of a double precision number to a string of
2648 * digits, preferring a shorter string of digits if the shorter string is
2649 * still within 1/2 ulp of the number.
2652 * Returns the string of digits. Returns NULL if the 'quick' method fails
2653 * and the bignum method must be used.
2656 * Stores the position of the decimal point at '*kPtr'.
2658 *----------------------------------------------------------------------
2661 static inline char *
2662 ShorteningQuickFormat(
2663 double d, /* Number to convert. */
2664 int k, /* floor(log10(d)) */
2665 int ilim, /* Number of significant digits to return. */
2666 double eps, /* Estimated roundoff error. */
2667 char *retval, /* Buffer to receive the digit string. */
2668 int *kPtr) /* Pointer to stash the position of the
2671 char *s = retval; /* Cursor in the return value. */
2672 int digit; /* Current digit. */
2675 eps = 0.5 / tens[ilim-1] - eps;
2687 * Truncate the conversion if the string of digits is within 1/2 ulp
2688 * of the actual value.
2695 if ((1. - d) < eps) {
2697 return BumpUp(s, retval, kPtr);
2701 * Bail out if the conversion fails to converge to a sufficiently
2710 * Bring the next digit to the integer part.
2719 *----------------------------------------------------------------------
2721 * StrictQuickFormat --
2723 * Convert a double precision number of a string of a precise number of
2724 * digits, using the 'quick' double precision method.
2727 * Returns the digit string, or NULL if the bignum method must be used to
2728 * do the formatting.
2731 * Stores the position of the decimal point in '*kPtr'.
2733 *----------------------------------------------------------------------
2736 static inline char *
2738 double d, /* Number to convert. */
2739 int k, /* floor(log10(d)) */
2740 int ilim, /* Number of significant digits to return. */
2741 double eps, /* Estimated roundoff error. */
2742 char *retval, /* Start of the digit string. */
2743 int *kPtr) /* Pointer to stash the position of the
2746 char *s = retval; /* Cursor in the return value. */
2747 int digit; /* Current digit of the answer. */
2750 eps *= tens[ilim-1];
2765 * When the given digit count is reached, handle trailing strings of 0
2770 if (d > 0.5 + eps) {
2772 return BumpUp(s, retval, kPtr);
2773 } else if (d < 0.5 - eps) {
2774 while (*--s == '0') {
2786 * Advance to the next digit.
2795 *----------------------------------------------------------------------
2797 * QuickConversion --
2799 * Converts a floating point number the 'quick' way, when only a limited
2800 * number of digits is required and floating point arithmetic can
2801 * therefore be used for the intermediate results.
2804 * Returns the converted string, or NULL if the bignum method must be
2807 *----------------------------------------------------------------------
2810 static inline char *
2812 double e, /* Number to format. */
2813 int k, /* floor(log10(d)), approximately. */
2814 int k_check, /* 0 if k is exact, 1 if it may be too high */
2815 int flags, /* Flags passed to dtoa:
2816 * TCL_DD_SHORTEN_FLAG */
2817 int len, /* Length of the return value. */
2818 int ilim, /* Number of digits to store. */
2819 int ilim1, /* Number of digits to store if we misguessed
2821 int *decpt, /* OUTPUT: Location of the decimal point. */
2822 char **endPtr) /* OUTPUT: Pointer to the terminal null
2825 int ieps; /* Number of 1-ulp roundoff errors that have
2826 * accumulated in the calculation. */
2827 Double eps; /* Estimated roundoff error. */
2828 char *retval; /* Returned string. */
2829 char *end; /* Pointer to the terminal null byte in the
2830 * returned string. */
2831 volatile double d; /* Workaround for a bug in mingw gcc 3.4.5 */
2834 * Bring d into the range [1 .. 10).
2837 ieps = AdjustRange(&e, k);
2841 * If the guessed value of k didn't get d into range, adjust it by one. If
2842 * that leaves us outside the range in which quick format is accurate,
2846 if (k_check && d < 1. && ilim > 0) {
2857 * Compute estimated roundoff error.
2860 eps.d = ieps * d + 7.;
2861 eps.w.word0 -= (FP_PRECISION-1) << EXP_SHIFT;
2864 * Handle the peculiar case where the result has no significant digits.
2867 retval = ckalloc(len + 1);
2874 } else if (d < -eps.d) {
2884 * Format the digit string.
2887 if (flags & TCL_DD_SHORTEN_FLAG) {
2888 end = ShorteningQuickFormat(d, k, ilim, eps.d, retval, decpt);
2890 end = StrictQuickFormat(d, k, ilim, eps.d, retval, decpt);
2897 if (endPtr != NULL) {
2904 *----------------------------------------------------------------------
2906 * CastOutPowersOf2 --
2908 * Adjust the factors 'b2', 'm2', and 's2' to cast out common powers of 2
2909 * from numerator and denominator in preparation for the 'bignum' method
2910 * of floating point conversion.
2912 *----------------------------------------------------------------------
2917 int *b2, /* Power of 2 to multiply the significand. */
2918 int *m2, /* Power of 2 to multiply 1/2 ulp. */
2919 int *s2) /* Power of 2 to multiply the common
2924 if (*m2 > 0 && *s2 > 0) { /* Find the smallest power of 2 in the
2926 if (*m2 < *s2) { /* Find the lowest common denominator. */
2931 *b2 -= i; /* Reduce to lowest terms. */
2938 *----------------------------------------------------------------------
2940 * ShorteningInt64Conversion --
2942 * Converts a double-precision number to the shortest string of digits
2943 * that reconverts exactly to the given number, or to 'ilim' digits if
2944 * that will yield a shorter result. The numerator and denominator in
2945 * David Gay's conversion algorithm are known to fit in Tcl_WideUInt,
2946 * giving considerably faster arithmetic than mp_int's.
2949 * Returns the string of significant decimal digits, in newly allocated
2953 * Stores the location of the decimal point in '*decpt' and the location
2954 * of the terminal null byte in '*endPtr'.
2956 *----------------------------------------------------------------------
2959 static inline char *
2960 ShorteningInt64Conversion(
2961 Double *dPtr, /* Original number to convert. */
2962 int convType, /* Type of conversion (shortest, Steele,
2963 * E format, F format). */
2964 Tcl_WideUInt bw, /* Integer significand. */
2965 int b2, int b5, /* Scale factor for the significand in the
2967 int m2plus, int m2minus, int m5,
2968 /* Scale factors for 1/2 ulp in the numerator
2969 * (will be different if bw == 1. */
2970 int s2, int s5, /* Scale factors for the denominator. */
2971 int k, /* Number of output digits before the decimal
2973 int len, /* Number of digits to allocate. */
2974 int ilim, /* Number of digits to convert if b >= s */
2975 int ilim1, /* Number of digits to convert if b < s */
2976 int *decpt, /* OUTPUT: Position of the decimal point. */
2977 char **endPtr) /* OUTPUT: Position of the terminal '\0' at
2978 * the end of the returned string. */
2980 char *retval = ckalloc(len + 1);
2981 /* Output buffer. */
2982 Tcl_WideUInt b = (bw * wuipow5[b5]) << b2;
2983 /* Numerator of the fraction being
2985 Tcl_WideUInt S = wuipow5[s5] << s2;
2986 /* Denominator of the fraction being
2988 Tcl_WideUInt mplus, mminus; /* Ranges for testing whether the result is
2989 * within roundoff of being exact. */
2990 int digit; /* Current output digit. */
2991 char *s = retval; /* Cursor in the output buffer. */
2992 int i; /* Current position in the output buffer. */
2995 * Adjust if the logarithm was guessed wrong.
3000 ++m2plus; ++m2minus; ++m5;
3006 * Compute roundoff ranges.
3009 mplus = wuipow5[m5] << m2plus;
3010 mminus = wuipow5[m5] << m2minus;
3013 * Loop through the digits.
3018 digit = (int)(b / S);
3020 Tcl_Panic("wrong digit!");
3025 * Does the current digit put us on the low side of the exact value
3026 * but within within roundoff of being exact?
3029 if (b < mplus || (b == mplus
3030 && convType != TCL_DD_STEELE0 && (dPtr->w.word1 & 1) == 0)) {
3032 * Make sure we shouldn't be rounding *up* instead, in case the
3033 * next number above is closer.
3036 if (2 * b > S || (2 * b == S && (digit & 1) != 0)) {
3040 s = BumpUp(s, retval, &k);
3046 * Stash the current digit.
3054 * Does one plus the current digit put us within roundoff of the
3058 if (b > S - mminus || (b == S - mminus
3059 && convType != TCL_DD_STEELE0 && (dPtr->w.word1 & 1) == 0)) {
3062 s = BumpUp(s, retval, &k);
3071 * Have we converted all the requested digits?
3076 if (2*b > S || (2*b == S && (digit & 1) != 0)) {
3077 s = BumpUp(s, retval, &k);
3083 * Advance to the next digit.
3088 mminus = 10 * mminus;
3093 * Endgame - store the location of the decimal point and the end of the
3106 *----------------------------------------------------------------------
3108 * StrictInt64Conversion --
3110 * Converts a double-precision number to a fixed-length string of 'ilim'
3111 * digits that reconverts exactly to the given number. ('ilim' should be
3112 * replaced with 'ilim1' in the case where log10(d) has been
3113 * overestimated). The numerator and denominator in David Gay's
3114 * conversion algorithm are known to fit in Tcl_WideUInt, giving
3115 * considerably faster arithmetic than mp_int's.
3118 * Returns the string of significant decimal digits, in newly allocated
3122 * Stores the location of the decimal point in '*decpt' and the location
3123 * of the terminal null byte in '*endPtr'.
3125 *----------------------------------------------------------------------
3128 static inline char *
3129 StrictInt64Conversion(
3130 Double *dPtr, /* Original number to convert. */
3131 int convType, /* Type of conversion (shortest, Steele,
3132 * E format, F format). */
3133 Tcl_WideUInt bw, /* Integer significand. */
3134 int b2, int b5, /* Scale factor for the significand in the
3136 int s2, int s5, /* Scale factors for the denominator. */
3137 int k, /* Number of output digits before the decimal
3139 int len, /* Number of digits to allocate. */
3140 int ilim, /* Number of digits to convert if b >= s */
3141 int ilim1, /* Number of digits to convert if b < s */
3142 int *decpt, /* OUTPUT: Position of the decimal point. */
3143 char **endPtr) /* OUTPUT: Position of the terminal '\0' at
3144 * the end of the returned string. */
3146 char *retval = ckalloc(len + 1);
3147 /* Output buffer. */
3148 Tcl_WideUInt b = (bw * wuipow5[b5]) << b2;
3149 /* Numerator of the fraction being
3151 Tcl_WideUInt S = wuipow5[s5] << s2;
3152 /* Denominator of the fraction being
3154 int digit; /* Current output digit. */
3155 char *s = retval; /* Cursor in the output buffer. */
3156 int i; /* Current position in the output buffer. */
3159 * Adjust if the logarithm was guessed wrong.
3169 * Loop through the digits.
3174 digit = (int)(b / S);
3176 Tcl_Panic("wrong digit!");
3181 * Have we converted all the requested digits?
3186 if (2*b > S || (2*b == S && (digit & 1) != 0)) {
3187 s = BumpUp(s, retval, &k);
3189 while (*--s == '0') {
3198 * Advance to the next digit.
3206 * Endgame - store the location of the decimal point and the end of the
3219 *----------------------------------------------------------------------
3221 * ShouldBankerRoundUpPowD --
3223 * Test whether bankers' rounding should round a digit up. Assumption is
3224 * made that the denominator of the fraction being tested is a power of
3228 * Returns 1 iff the fraction is more than 1/2, or if the fraction is
3229 * exactly 1/2 and the digit is odd.
3231 *----------------------------------------------------------------------
3235 ShouldBankerRoundUpPowD(
3236 mp_int *b, /* Numerator of the fraction. */
3237 int sd, /* Denominator is 2**(sd*MP_DIGIT_BIT). */
3238 int isodd) /* 1 if the digit is odd, 0 if even. */
3241 static const mp_digit topbit = ((mp_digit)1) << (MP_DIGIT_BIT - 1);
3243 if (b->used < sd || (b->dp[sd-1] & topbit) == 0) {
3246 if (b->dp[sd-1] != topbit) {
3249 for (i = sd-2; i >= 0; --i) {
3250 if (b->dp[i] != 0) {
3258 *----------------------------------------------------------------------
3260 * ShouldBankerRoundUpToNextPowD --
3262 * Tests whether bankers' rounding will round down in the "denominator is
3263 * a power of 2**MP_DIGIT" case.
3266 * Returns 1 if the rounding will be performed - which increases the
3267 * digit by one - and 0 otherwise.
3269 *----------------------------------------------------------------------
3273 ShouldBankerRoundUpToNextPowD(
3274 mp_int *b, /* Numerator of the fraction. */
3275 mp_int *m, /* Numerator of the rounding tolerance. */
3276 int sd, /* Common denominator is 2**(sd*MP_DIGIT_BIT). */
3277 int convType, /* Conversion type: STEELE defeats
3278 * round-to-even (not sure why one wants to do
3279 * this; I copied it from Gay). FIXME */
3280 int isodd, /* 1 if the integer significand is odd. */
3281 mp_int *temp) /* Work area for the calculation. */
3286 * Compare B and S-m - which is the same as comparing B+m and S - which we
3287 * do by computing b+m and doing a bitwhack compare against
3288 * 2**(MP_DIGIT_BIT*sd)
3292 if (temp->used <= sd) { /* Too few digits to be > s */
3295 if (temp->used > sd+1 || temp->dp[sd] > 1) {
3299 for (i = sd-1; i >= 0; --i) {
3301 if (temp->dp[i] != 0) { /* > s */
3305 if (convType == TCL_DD_STEELE0) {
3306 /* Biased rounding. */
3313 *----------------------------------------------------------------------
3315 * ShorteningBignumConversionPowD --
3317 * Converts a double-precision number to the shortest string of digits
3318 * that reconverts exactly to the given number, or to 'ilim' digits if
3319 * that will yield a shorter result. The denominator in David Gay's
3320 * conversion algorithm is known to be a power of 2**MP_DIGIT_BIT, and hence
3321 * the division in the main loop may be replaced by a digit shift and
3325 * Returns the string of significant decimal digits, in newly allocated
3329 * Stores the location of the decimal point in '*decpt' and the location
3330 * of the terminal null byte in '*endPtr'.
3332 *----------------------------------------------------------------------
3335 static inline char *
3336 ShorteningBignumConversionPowD(
3337 Double *dPtr, /* Original number to convert. */
3338 int convType, /* Type of conversion (shortest, Steele,
3339 * E format, F format). */
3340 Tcl_WideUInt bw, /* Integer significand. */
3341 int b2, int b5, /* Scale factor for the significand in the
3343 int m2plus, int m2minus, int m5,
3344 /* Scale factors for 1/2 ulp in the numerator
3345 * (will be different if bw == 1). */
3346 int sd, /* Scale factor for the denominator. */
3347 int k, /* Number of output digits before the decimal
3349 int len, /* Number of digits to allocate. */
3350 int ilim, /* Number of digits to convert if b >= s */
3351 int ilim1, /* Number of digits to convert if b < s */
3352 int *decpt, /* OUTPUT: Position of the decimal point. */
3353 char **endPtr) /* OUTPUT: Position of the terminal '\0' at
3354 * the end of the returned string. */
3356 char *retval = ckalloc(len + 1);
3357 /* Output buffer. */
3358 mp_int b; /* Numerator of the fraction being
3360 mp_int mplus, mminus; /* Bounds for roundoff. */
3361 mp_digit digit; /* Current output digit. */
3362 char *s = retval; /* Cursor in the output buffer. */
3363 int i; /* Index in the output buffer. */
3368 * b = bw * 2**b2 * 5**b5
3372 TclBNInitBignumFromWideUInt(&b, bw);
3373 mp_init_set(&mminus, 1);
3374 MulPow5(&b, b5, &b);
3375 mp_mul_2d(&b, b2, &b);
3378 * Adjust if the logarithm was guessed wrong.
3382 mp_mul_d(&b, 10, &b);
3383 ++m2plus; ++m2minus; ++m5;
3389 * mminus = 5**m5 * 2**m2minus
3390 * mplus = 5**m5 * 2**m2plus
3393 mp_mul_2d(&mminus, m2minus, &mminus);
3394 MulPow5(&mminus, m5, &mminus);
3395 if (m2plus > m2minus) {
3396 mp_init_copy(&mplus, &mminus);
3397 mp_mul_2d(&mplus, m2plus-m2minus, &mplus);
3402 * Loop through the digits. Do division and mod by s == 2**(sd*MP_DIGIT_BIT)
3403 * by mp_digit extraction.
3412 if (b.used > sd+1 || digit >= 10) {
3413 Tcl_Panic("wrong digit!");
3415 --b.used; mp_clamp(&b);
3419 * Does the current digit put us on the low side of the exact value
3420 * but within within roundoff of being exact?
3423 r1 = mp_cmp_mag(&b, (m2plus > m2minus)? &mplus : &mminus);
3424 if (r1 == MP_LT || (r1 == MP_EQ
3425 && convType != TCL_DD_STEELE0 && (dPtr->w.word1 & 1) == 0)) {
3427 * Make sure we shouldn't be rounding *up* instead, in case the
3428 * next number above is closer.
3431 if (ShouldBankerRoundUpPowD(&b, sd, digit&1)) {
3435 s = BumpUp(s, retval, &k);
3441 * Stash the last digit.
3449 * Does one plus the current digit put us within roundoff of the
3453 if (ShouldBankerRoundUpToNextPowD(&b, &mminus, sd, convType,
3454 dPtr->w.word1 & 1, &temp)) {
3457 s = BumpUp(s, retval, &k);
3466 * Have we converted all the requested digits?
3471 if (ShouldBankerRoundUpPowD(&b, sd, digit&1)) {
3472 s = BumpUp(s, retval, &k);
3478 * Advance to the next digit.
3481 mp_mul_d(&b, 10, &b);
3482 mp_mul_d(&mminus, 10, &mminus);
3483 if (m2plus > m2minus) {
3484 mp_mul_2d(&mminus, m2plus-m2minus, &mplus);
3490 * Endgame - store the location of the decimal point and the end of the
3494 if (m2plus > m2minus) {
3497 mp_clear_multi(&b, &mminus, &temp, NULL);
3507 *----------------------------------------------------------------------
3509 * StrictBignumConversionPowD --
3511 * Converts a double-precision number to a fixed-lengt string of 'ilim'
3512 * digits (or 'ilim1' if log10(d) has been overestimated). The
3513 * denominator in David Gay's conversion algorithm is known to be a power
3514 * of 2**MP_DIGIT_BIT, and hence the division in the main loop may be
3515 * replaced by a digit shift and mask.
3518 * Returns the string of significant decimal digits, in newly allocated
3522 * Stores the location of the decimal point in '*decpt' and the location
3523 * of the terminal null byte in '*endPtr'.
3525 *----------------------------------------------------------------------
3528 static inline char *
3529 StrictBignumConversionPowD(
3530 Double *dPtr, /* Original number to convert. */
3531 int convType, /* Type of conversion (shortest, Steele,
3532 * E format, F format). */
3533 Tcl_WideUInt bw, /* Integer significand. */
3534 int b2, int b5, /* Scale factor for the significand in the
3536 int sd, /* Scale factor for the denominator. */
3537 int k, /* Number of output digits before the decimal
3539 int len, /* Number of digits to allocate. */
3540 int ilim, /* Number of digits to convert if b >= s */
3541 int ilim1, /* Number of digits to convert if b < s */
3542 int *decpt, /* OUTPUT: Position of the decimal point. */
3543 char **endPtr) /* OUTPUT: Position of the terminal '\0' at
3544 * the end of the returned string. */
3546 char *retval = ckalloc(len + 1);
3547 /* Output buffer. */
3548 mp_int b; /* Numerator of the fraction being
3550 mp_digit digit; /* Current output digit. */
3551 char *s = retval; /* Cursor in the output buffer. */
3552 int i; /* Index in the output buffer. */
3556 * b = bw * 2**b2 * 5**b5
3559 TclBNInitBignumFromWideUInt(&b, bw);
3560 MulPow5(&b, b5, &b);
3561 mp_mul_2d(&b, b2, &b);
3564 * Adjust if the logarithm was guessed wrong.
3568 mp_mul_d(&b, 10, &b);
3575 * Loop through the digits. Do division and mod by s == 2**(sd*MP_DIGIT_BIT)
3576 * by mp_digit extraction.
3585 if (b.used > sd+1 || digit >= 10) {
3586 Tcl_Panic("wrong digit!");
3593 * Have we converted all the requested digits?
3598 if (ShouldBankerRoundUpPowD(&b, sd, digit&1)) {
3599 s = BumpUp(s, retval, &k);
3601 while (*--s == '0') {
3609 * Advance to the next digit.
3612 mp_mul_d(&b, 10, &b);
3617 * Endgame - store the location of the decimal point and the end of the
3621 mp_clear_multi(&b, &temp, NULL);
3631 *----------------------------------------------------------------------
3633 * ShouldBankerRoundUp --
3635 * Tests whether a digit should be rounded up or down when finishing
3636 * bignum-based floating point conversion.
3639 * Returns 1 if the number needs to be rounded up, 0 otherwise.
3641 *----------------------------------------------------------------------
3645 ShouldBankerRoundUp(
3646 mp_int *twor, /* 2x the remainder from thd division that
3647 * produced the last digit. */
3648 mp_int *S, /* Denominator. */
3649 int isodd) /* Flag == 1 if the last digit is odd. */
3651 int r = mp_cmp_mag(twor, S);
3661 Tcl_Panic("in ShouldBankerRoundUp, trichotomy fails!");
3666 *----------------------------------------------------------------------
3668 * ShouldBankerRoundUpToNext --
3670 * Tests whether the remainder is great enough to force rounding to the
3671 * next higher digit.
3674 * Returns 1 if the number should be rounded up, 0 otherwise.
3676 *----------------------------------------------------------------------
3680 ShouldBankerRoundUpToNext(
3681 mp_int *b, /* Remainder from the division that produced
3682 * the last digit. */
3683 mp_int *m, /* Numerator of the rounding tolerance. */
3684 mp_int *S, /* Denominator. */
3685 int convType, /* Conversion type: STEELE0 defeats
3686 * round-to-even. (Not sure why one would want
3687 * this; I coped it from Gay). FIXME */
3688 int isodd, /* 1 if the integer significand is odd. */
3689 mp_int *temp) /* Work area needed for the calculation. */
3694 * Compare b and S-m: this is the same as comparing B+m and S.
3698 r = mp_cmp_mag(temp, S);
3703 if (convType == TCL_DD_STEELE0) {
3711 Tcl_Panic("in ShouldBankerRoundUpToNext, trichotomy fails!");
3716 *----------------------------------------------------------------------
3718 * ShorteningBignumConversion --
3720 * Convert a floating point number to a variable-length digit string
3721 * using the multiprecision method.
3724 * Returns the string of digits.
3727 * Stores the position of the decimal point in *decpt. Stores a pointer
3728 * to the end of the number in *endPtr.
3730 *----------------------------------------------------------------------
3733 static inline char *
3734 ShorteningBignumConversion(
3735 Double *dPtr, /* Original number being converted. */
3736 int convType, /* Conversion type. */
3737 Tcl_WideUInt bw, /* Integer significand and exponent. */
3738 int b2, /* Scale factor for the significand. */
3739 int m2plus, int m2minus, /* Scale factors for 1/2 ulp in numerator. */
3740 int s2, int s5, /* Scale factors for denominator. */
3741 int k, /* Guessed position of the decimal point. */
3742 int len, /* Size of the digit buffer to allocate. */
3743 int ilim, /* Number of digits to convert if b >= s */
3744 int ilim1, /* Number of digits to convert if b < s */
3745 int *decpt, /* OUTPUT: Position of the decimal point. */
3746 char **endPtr) /* OUTPUT: Pointer to the end of the number */
3748 char *retval = ckalloc(len+1);
3749 /* Buffer of digits to return. */
3750 char *s = retval; /* Cursor in the return value. */
3751 mp_int b; /* Numerator of the result. */
3752 mp_int mminus; /* 1/2 ulp below the result. */
3753 mp_int mplus; /* 1/2 ulp above the result. */
3754 mp_int S; /* Denominator of the result. */
3755 mp_int dig; /* Current digit of the result. */
3756 int digit; /* Current digit of the result. */
3757 mp_int temp; /* Work area. */
3758 int minit = 1; /* Fudge factor for when we misguess k. */
3763 * b = bw * 2**b2 * 5**b5
3767 TclBNInitBignumFromWideUInt(&b, bw);
3768 mp_mul_2d(&b, b2, &b);
3770 MulPow5(&S, s5, &S); mp_mul_2d(&S, s2, &S);
3773 * Handle the case where we guess the position of the decimal point wrong.
3776 if (mp_cmp_mag(&b, &S) == MP_LT) {
3777 mp_mul_d(&b, 10, &b);
3784 * mminus = 2**m2minus * 5**m5
3787 mp_init_set(&mminus, minit);
3788 mp_mul_2d(&mminus, m2minus, &mminus);
3789 if (m2plus > m2minus) {
3790 mp_init_copy(&mplus, &mminus);
3791 mp_mul_2d(&mplus, m2plus-m2minus, &mplus);
3796 * Loop through the digits.
3802 mp_div(&b, &S, &dig, &b);
3803 if (dig.used > 1 || dig.dp[0] >= 10) {
3804 Tcl_Panic("wrong digit!");
3809 * Does the current digit leave us with a remainder small enough to
3813 r1 = mp_cmp_mag(&b, (m2plus > m2minus)? &mplus : &mminus);
3814 if (r1 == MP_LT || (r1 == MP_EQ
3815 && convType != TCL_DD_STEELE0 && (dPtr->w.word1 & 1) == 0)) {
3816 mp_mul_2d(&b, 1, &b);
3817 if (ShouldBankerRoundUp(&b, &S, digit&1)) {
3821 s = BumpUp(s, retval, &k);
3830 * Does the current digit leave us with a remainder large enough to
3831 * commit to rounding up to the next higher digit?
3834 if (ShouldBankerRoundUpToNext(&b, &mminus, &S, convType,
3835 dPtr->w.word1 & 1, &temp)) {
3839 s = BumpUp(s, retval, &k);
3847 * Have we converted all the requested digits?
3852 mp_mul_2d(&b, 1, &b);
3853 if (ShouldBankerRoundUp(&b, &S, digit&1)) {
3854 s = BumpUp(s, retval, &k);
3860 * Advance to the next digit.
3865 * Can possibly shorten the denominator.
3868 mp_mul_2d(&b, 1, &b);
3869 mp_mul_2d(&mminus, 1, &mminus);
3870 if (m2plus > m2minus) {
3871 mp_mul_2d(&mplus, 1, &mplus);
3873 mp_div_d(&S, 5, &S, NULL);
3877 * IDEA: It might possibly be a win to fall back to int64_t
3878 * arithmetic here if S < 2**64/10. But it's a win only for
3879 * a fairly narrow range of magnitudes so perhaps not worth
3880 * bothering. We already know that we shorten the
3881 * denominator by at least 1 mp_digit, perhaps 2, as we do
3882 * the conversion for 17 digits of significance.
3884 * 10**26 1 trip through loop before fallback possible
3901 * thereafter no gain.
3904 mp_mul_d(&b, 10, &b);
3905 mp_mul_d(&mminus, 10, &mminus);
3906 if (m2plus > m2minus) {
3907 mp_mul_2d(&mplus, 10, &mplus);
3915 * Endgame - store the location of the decimal point and the end of the
3919 if (m2plus > m2minus) {
3922 mp_clear_multi(&b, &mminus, &temp, &dig, &S, NULL);
3932 *----------------------------------------------------------------------
3934 * StrictBignumConversion --
3936 * Convert a floating point number to a fixed-length digit string using
3937 * the multiprecision method.
3940 * Returns the string of digits.
3943 * Stores the position of the decimal point in *decpt. Stores a pointer
3944 * to the end of the number in *endPtr.
3946 *----------------------------------------------------------------------
3949 static inline char *
3950 StrictBignumConversion(
3951 Double *dPtr, /* Original number being converted. */
3952 int convType, /* Conversion type. */
3953 Tcl_WideUInt bw, /* Integer significand and exponent. */
3954 int b2, /* Scale factor for the significand. */
3955 int s2, int s5, /* Scale factors for denominator. */
3956 int k, /* Guessed position of the decimal point. */
3957 int len, /* Size of the digit buffer to allocate. */
3958 int ilim, /* Number of digits to convert if b >= s */
3959 int ilim1, /* Number of digits to convert if b < s */
3960 int *decpt, /* OUTPUT: Position of the decimal point. */
3961 char **endPtr) /* OUTPUT: Pointer to the end of the number */
3963 char *retval = ckalloc(len+1);
3964 /* Buffer of digits to return. */
3965 char *s = retval; /* Cursor in the return value. */
3966 mp_int b; /* Numerator of the result. */
3967 mp_int S; /* Denominator of the result. */
3968 mp_int dig; /* Current digit of the result. */
3969 int digit; /* Current digit of the result. */
3970 mp_int temp; /* Work area. */
3971 int g; /* Size of the current digit ground. */
3975 * b = bw * 2**b2 * 5**b5
3979 mp_init_multi(&temp, &dig, NULL);
3980 TclBNInitBignumFromWideUInt(&b, bw);
3981 mp_mul_2d(&b, b2, &b);
3983 MulPow5(&S, s5, &S); mp_mul_2d(&S, s2, &S);
3986 * Handle the case where we guess the position of the decimal point wrong.
3989 if (mp_cmp_mag(&b, &S) == MP_LT) {
3990 mp_mul_d(&b, 10, &b);
3996 * Convert the leading digit.
4000 mp_div(&b, &S, &dig, &b);
4001 if (dig.used > 1 || dig.dp[0] >= 10) {
4002 Tcl_Panic("wrong digit!");
4007 * Is a single digit all that was requested?
4012 mp_mul_2d(&b, 1, &b);
4013 if (ShouldBankerRoundUp(&b, &S, digit&1)) {
4014 s = BumpUp(s, retval, &k);
4019 * Shift by a group of digits.
4023 if (g > DIGIT_GROUP) {
4027 mp_div_d(&S, dpow5[g], &S, NULL);
4029 } else if (s5 > 0) {
4030 mp_div_d(&S, dpow5[s5], &S, NULL);
4031 mp_mul_d(&b, dpow5[g - s5], &b);
4034 mp_mul_d(&b, dpow5[g], &b);
4036 mp_mul_2d(&b, g, &b);
4039 * As with the shortening bignum conversion, it's possible at this
4040 * point that we will have reduced the denominator to less than
4041 * 2**64/10, at which point it would be possible to fall back to
4042 * to int64_t arithmetic. But the potential payoff is tremendously
4043 * less - unless we're working in F format - because we know that
4044 * three groups of digits will always suffice for %#.17e, the
4045 * longest format that doesn't introduce empty precision.
4047 * Extract the next group of digits.
4050 mp_div(&b, &S, &dig, &b);
4052 Tcl_Panic("wrong digit!");
4055 for (j = g-1; j >= 0; --j) {
4058 *s++ = digit / t + '0';
4064 * Have we converted all the requested digits?
4068 mp_mul_2d(&b, 1, &b);
4069 if (ShouldBankerRoundUp(&b, &S, digit&1)) {
4070 s = BumpUp(s, retval, &k);
4076 while (*--s == '0') {
4082 * Endgame - store the location of the decimal point and the end of the
4086 mp_clear_multi(&b, &S, &temp, &dig, NULL);
4096 *----------------------------------------------------------------------
4098 * TclDoubleDigits --
4100 * Core of Tcl's conversion of double-precision floating point numbers to
4104 * Returns a newly-allocated string of digits.
4107 * Sets *decpt to the index of the character in the string before the
4108 * place that the decimal point should go. If 'endPtr' is not NULL, sets
4109 * endPtr to point to the terminating '\0' byte of the string. Sets *sign
4110 * to 1 if a minus sign should be printed with the number, or 0 if a plus
4111 * sign (or no sign) should appear.
4113 * This function is a service routine that produces the string of digits for
4114 * floating-point-to-decimal conversion. It can do a number of things
4115 * according to the 'flags' argument. Valid values for 'flags' include:
4116 * TCL_DD_SHORTEST - This is the default for floating point conversion if
4117 * ::tcl_precision is 0. It constructs the shortest string of
4118 * digits that will reconvert to the given number when scanned.
4119 * For floating point numbers that are exactly between two
4120 * decimal numbers, it resolves using the 'round to even' rule.
4121 * With this value, the 'ndigits' parameter is ignored.
4122 * TCL_DD_STEELE - This value is not recommended and may be removed in
4123 * the future. It follows the conversion algorithm outlined in
4124 * "How to Print Floating-Point Numbers Accurately" by Guy
4125 * L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90,
4126 * pp. 112-126]. This rule has the effect of rendering 1e23 as
4127 * 9.9999999999999999e22 - which is a 'better' approximation in
4128 * the sense that it will reconvert correctly even if a
4129 * subsequent input conversion is 'round up' or 'round down'
4130 * rather than 'round to nearest', but is surprising otherwise.
4131 * TCL_DD_E_FORMAT - This value is used to prepare numbers for %e format
4132 * conversion (or for default floating->string if tcl_precision
4133 * is not 0). It constructs a string of at most 'ndigits' digits,
4134 * choosing the one that is closest to the given number (and
4135 * resolving ties with 'round to even'). It is allowed to return
4136 * fewer than 'ndigits' if the number converts exactly; if the
4137 * TCL_DD_E_FORMAT|TCL_DD_SHORTEN_FLAG is supplied instead, it
4138 * also returns fewer digits if the shorter string will still
4139 * reconvert without loss to the given input number. In any case,
4140 * strings of trailing zeroes are suppressed.
4141 * TCL_DD_F_FORMAT - This value is used to prepare numbers for %f format
4142 * conversion. It requests that conversion proceed until
4143 * 'ndigits' digits after the decimal point have been converted.
4144 * It is possible for this format to result in a zero-length
4145 * string if the number is sufficiently small. Again, it is
4146 * permissible for TCL_DD_F_FORMAT to return fewer digits for a
4147 * number that converts exactly, and changing the argument to
4148 * TCL_DD_F_FORMAT|TCL_DD_SHORTEN_FLAG will allow the routine
4149 * also to return fewer digits if the shorter string will still
4150 * reconvert without loss to the given input number. Strings of
4151 * trailing zeroes are suppressed.
4153 * To any of these flags may be OR'ed TCL_DD_NO_QUICK; this flag requires
4154 * all calculations to be done in exact arithmetic. Normally, E and F
4155 * format with fewer than about 14 digits will be done with a quick
4156 * floating point approximation and fall back on the exact arithmetic
4157 * only if the input number is close enough to the midpoint between two
4158 * decimal strings that more precision is needed to resolve which string
4161 * The value stored in the 'decpt' argument on return may be negative
4162 * (indicating that the decimal point falls to the left of the string) or
4163 * greater than the length of the string. In addition, the value -9999 is used
4164 * as a sentinel to indicate that the string is one of the special values
4165 * "Infinity" and "NaN", and that no decimal point should be inserted.
4167 *----------------------------------------------------------------------
4172 double dv, /* Number to convert. */
4173 int ndigits, /* Number of digits requested. */
4174 int flags, /* Conversion flags. */
4175 int *decpt, /* OUTPUT: Position of the decimal point. */
4176 int *sign, /* OUTPUT: 1 if the result is negative. */
4177 char **endPtr) /* OUTPUT: If not NULL, receives a pointer to
4178 * one character beyond the end of the
4179 * returned string. */
4181 int convType = (flags & TCL_DD_CONVERSION_TYPE_MASK);
4182 /* Type of conversion being performed:
4183 * TCL_DD_SHORTEST0, TCL_DD_STEELE0,
4184 * TCL_DD_E_FORMAT, or TCL_DD_F_FORMAT. */
4185 Double d; /* Union for deconstructing doubles. */
4186 Tcl_WideUInt bw; /* Integer significand. */
4187 int be; /* Power of 2 by which b must be multiplied */
4188 int bbits; /* Number of bits needed to represent b. */
4189 int denorm; /* Flag == 1 iff the input number was
4191 int k; /* Estimate of floor(log10(d)). */
4192 int k_check; /* Flag == 1 if d is near enough to a power of
4193 * ten that k must be checked. */
4194 int b2, b5, s2, s5; /* Powers of 2 and 5 in the numerator and
4195 * denominator of intermediate results. */
4196 int ilim = -1, ilim1 = -1; /* Number of digits to convert, and number to
4197 * convert if log10(d) has been
4199 char *retval; /* Return value from this function. */
4203 * Put the input number into a union for bit-whacking.
4209 * Handle the cases of negative numbers (by taking the absolute value:
4210 * this includes -Inf and -NaN!), infinity, Not a Number, and zero.
4213 TakeAbsoluteValue(&d, sign);
4214 if ((d.w.word0 & EXP_MASK) == EXP_MASK) {
4215 return FormatInfAndNaN(&d, decpt, endPtr);
4218 return FormatZero(decpt, endPtr);
4222 * Unpack the floating point into a wide integer and an exponent.
4223 * Determine the number of bits that the big integer requires, and compute
4224 * a quick approximation (which may be one too high) of ceil(log10(d.d)).
4227 denorm = ((d.w.word0 & EXP_MASK) == 0);
4228 DoubleToExpAndSig(d.d, &bw, &be, &bbits);
4229 k = ApproximateLog10(bw, be, bbits);
4230 k = BetterLog10(d.d, k, &k_check);
4232 /* At this point, we have:
4233 * d is the number to convert.
4234 * bw are significand and exponent: d == bw*2**be,
4235 * bbits is the length of bw: 2**bbits-1 <= bw < 2**bbits
4236 * k is either ceil(log10(d)) or ceil(log10(d))+1. k_check is 0 if we
4237 * know that k is exactly ceil(log10(d)) and 1 if we need to check.
4238 * We want a rational number
4239 * r = b * 10**(1-k) = bw * 2**b2 * 5**b5 / (2**s2 / 5**s5),
4240 * with b2, b5, s2, s5 >= 0. Note that the most significant decimal
4241 * digit is floor(r) and that successive digits can be obtained by
4242 * setting r <- 10*floor(r) (or b <= 10 * (b % S)). Find appropriate
4246 ComputeScale(be, k, &b2, &b5, &s2, &s5);
4249 * Correct an incorrect caller-supplied 'ndigits'. Also determine:
4250 * i = The maximum number of decimal digits that will be returned in the
4251 * formatted string. This is k + 1 + ndigits for F format, 18 for
4252 * shortest and Steele, and ndigits for E format.
4253 * ilim = The number of significant digits to convert if k has been
4254 * guessed correctly. This is -1 for shortest and Steele (which
4255 * stop when all significance has been lost), 'ndigits' for E
4256 * format, and 'k + 1 + ndigits' for F format.
4257 * ilim1 = The minimum number of significant digits to convert if k has
4258 * been guessed 1 too high. This, too, is -1 for shortest and
4259 * Steele, and 'ndigits' for E format, but it's 'ndigits-1' for F
4263 SetPrecisionLimits(convType, k, &ndigits, &i, &ilim, &ilim1);
4266 * Try to do low-precision conversion in floating point rather than
4267 * resorting to expensive multiprecision arithmetic.
4270 if (ilim >= 0 && ilim <= QUICK_MAX && !(flags & TCL_DD_NO_QUICK)) {
4271 retval = QuickConversion(d.d, k, k_check, flags, i, ilim, ilim1,
4273 if (retval != NULL) {
4279 * For shortening conversions, determine the upper and lower bounds for
4280 * the remainder at which we can stop.
4281 * m+ = (2**m2plus * 5**m5) / (2**s2 * 5**s5) is the limit on the high
4283 * m- = (2**m2minus * 5**m5) / (2**s2 * 5**s5) is the limit on the low
4285 * We may need to increase s2 to put m2plus, m2minus, b2 over a common
4289 if (flags & TCL_DD_SHORTEN_FLAG) {
4296 * Find the quantity i so that (2**i*5**b5)/(2**s2*5**s5) is 1/2 unit
4297 * in the least significant place of the floating point number.
4301 i = be + EXPONENT_BIAS + (FP_PRECISION-1);
4303 i = 1 + FP_PRECISION - bbits;
4309 * Reduce the fractions to lowest terms, since the above calculation
4310 * may have left excess powers of 2 in numerator and denominator.
4313 CastOutPowersOf2(&b2, &m2minus, &s2);
4316 * In the special case where bw==1, the nearest floating point number
4317 * to it on the low side is 1/4 ulp below it. Adjust accordingly.
4321 if (!denorm && bw == 1) {
4327 if (s5+1 < N_LOG2POW5 && s2+1 + log2pow5[s5+1] <= 64) {
4329 * If 10*2**s2*5**s5 == 2**(s2+1)+5**(s5+1) fits in a 64-bit word,
4330 * then all our intermediate calculations can be done using exact
4331 * 64-bit arithmetic with no need for expensive multiprecision
4332 * operations. (This will be true for all numbers in the range
4333 * [1.0e-3 .. 1.0e+24]).
4336 return ShorteningInt64Conversion(&d, convType, bw, b2, b5, m2plus,
4337 m2minus, m5, s2, s5, k, len, ilim, ilim1, decpt, endPtr);
4338 } else if (s5 == 0) {
4340 * The denominator is a power of 2, so we can replace division by
4341 * digit shifts. First we round up s2 to a multiple of MP_DIGIT_BIT,
4342 * and adjust m2 and b2 accordingly. Then we launch into a version
4343 * of the comparison that's specialized for the 'power of mp_digit
4344 * in the denominator' case.
4347 if (s2 % MP_DIGIT_BIT != 0) {
4348 int delta = MP_DIGIT_BIT - (s2 % MP_DIGIT_BIT);
4355 return ShorteningBignumConversionPowD(&d, convType, bw, b2, b5,
4356 m2plus, m2minus, m5, s2/MP_DIGIT_BIT, k, len, ilim, ilim1,
4360 * Alas, there's no helpful special case; use full-up bignum
4361 * arithmetic for the conversion.
4364 return ShorteningBignumConversion(&d, convType, bw, b2, m2plus,
4365 m2minus, s2, s5, k, len, ilim, ilim1, decpt, endPtr);
4369 * Non-shortening conversion.
4375 * Reduce numerator and denominator to lowest terms.
4378 if (b2 >= s2 && s2 > 0) {
4380 } else if (s2 >= b2 && b2 > 0) {
4384 if (s5+1 < N_LOG2POW5 && s2+1 + log2pow5[s5+1] <= 64) {
4386 * If 10*2**s2*5**s5 == 2**(s2+1)+5**(s5+1) fits in a 64-bit word,
4387 * then all our intermediate calculations can be done using exact
4388 * 64-bit arithmetic with no need for expensive multiprecision
4392 return StrictInt64Conversion(&d, convType, bw, b2, b5, s2, s5, k,
4393 len, ilim, ilim1, decpt, endPtr);
4394 } else if (s5 == 0) {
4396 * The denominator is a power of 2, so we can replace division by
4397 * digit shifts. First we round up s2 to a multiple of MP_DIGIT_BIT,
4398 * and adjust m2 and b2 accordingly. Then we launch into a version
4399 * of the comparison that's specialized for the 'power of mp_digit
4400 * in the denominator' case.
4403 if (s2 % MP_DIGIT_BIT != 0) {
4404 int delta = MP_DIGIT_BIT - (s2 % MP_DIGIT_BIT);
4409 return StrictBignumConversionPowD(&d, convType, bw, b2, b5,
4410 s2/MP_DIGIT_BIT, k, len, ilim, ilim1, decpt, endPtr);
4413 * There are no helpful special cases, but at least we know in
4414 * advance how many digits we will convert. We can run the
4415 * conversion in steps of DIGIT_GROUP digits, so as to have many
4416 * fewer mp_int divisions.
4419 return StrictBignumConversion(&d, convType, bw, b2, s2, s5, k,
4420 len, ilim, ilim1, decpt, endPtr);
4426 *----------------------------------------------------------------------
4428 * TclInitDoubleConversion --
4430 * Initializes constants that are needed for conversions to and from
4437 * The log base 2 of the floating point radix, the number of bits in a
4438 * double mantissa, and a table of the powers of five and ten are
4439 * computed and stored.
4441 *----------------------------------------------------------------------
4445 TclInitDoubleConversion(void)
4451 #ifdef IEEE_FLOATING_POINT
4457 #if defined(__sgi) && defined(_COMPILER_VERSION)
4458 union fpc_csr mipsCR;
4460 mipsCR.fc_word = get_fpc_csr();
4461 mipsCR.fc_struct.flush = 0;
4462 set_fpc_csr(mipsCR.fc_word);
4466 * Initialize table of powers of 10 expressed as wide integers.
4469 maxpow10_wide = (int)
4470 floor(sizeof(Tcl_WideUInt) * CHAR_BIT * log(2.) / log(10.));
4471 pow10_wide = (Tcl_WideUInt *)
4472 ckalloc((maxpow10_wide + 1) * sizeof(Tcl_WideUInt));
4474 for (i = 0; i < maxpow10_wide; ++i) {
4481 * Determine how many bits of precision a double has, and how many decimal
4482 * digits that represents.
4485 if (frexp((double) FLT_RADIX, &log2FLT_RADIX) != 0.5) {
4486 Tcl_Panic("This code doesn't work on a decimal machine!");
4489 mantBits = DBL_MANT_DIG * log2FLT_RADIX;
4493 * Initialize a table of powers of ten that can be exactly represented in
4497 x = (int) (DBL_MANT_DIG * log((double) FLT_RADIX) / log(5.0));
4503 for (i=0 ; i<=mmaxpow ; ++i) {
4509 * Initialize a table of large powers of five.
4512 for (i=0; i<9; ++i) {
4516 for (i=0; i<8; ++i) {
4517 mp_sqr(pow5+i, pow5+i+1);
4519 mp_init_set_int(pow5_13, 1220703125);
4520 for (i = 1; i < 5; ++i) {
4521 mp_init(pow5_13 + i);
4522 mp_sqr(pow5_13 + i - 1, pow5_13 + i);
4526 * Determine the number of decimal digits to the left and right of the
4527 * decimal point in the largest and smallest double, the smallest double
4528 * that differs from zero, and the number of mp_digits needed to represent
4529 * the significand of a double.
4532 maxDigits = (int) ((DBL_MAX_EXP * log((double) FLT_RADIX)
4533 + 0.5 * log(10.)) / log(10.));
4534 minDigits = (int) floor((DBL_MIN_EXP - DBL_MANT_DIG)
4535 * log((double) FLT_RADIX) / log(10.));
4536 log10_DIGIT_MAX = (int) floor(MP_DIGIT_BIT * log(2.) / log(10.));
4539 * Nokia 770's software-emulated floating point is "middle endian": the
4540 * bytes within a 32-bit word are little-endian (like the native
4541 * integers), but the two words of a 'double' are presented most
4542 * significant word first.
4545 #ifdef IEEE_FLOATING_POINT
4546 bitwhack.dv = 1.000000238418579;
4547 /* 3ff0 0000 4000 0000 */
4548 if ((bitwhack.iv >> 32) == 0x3FF00000) {
4550 } else if ((bitwhack.iv & 0xFFFFFFFF) == 0x3FF00000) {
4553 Tcl_Panic("unknown floating point word order on this machine");
4559 *----------------------------------------------------------------------
4561 * TclFinalizeDoubleConversion --
4563 * Cleans up this file on exit.
4569 * Memory allocated by TclInitDoubleConversion is freed.
4571 *----------------------------------------------------------------------
4575 TclFinalizeDoubleConversion(void)
4580 for (i=0; i<9; ++i) {
4583 for (i=0; i < 5; ++i) {
4584 mp_clear(pow5_13 + i);
4589 *----------------------------------------------------------------------
4591 * Tcl_InitBignumFromDouble --
4593 * Extracts the integer part of a double and converts it to an arbitrary
4594 * precision integer.
4600 * Initializes the bignum supplied, and stores the converted number in
4603 *----------------------------------------------------------------------
4607 Tcl_InitBignumFromDouble(
4608 Tcl_Interp *interp, /* For error message. */
4609 double d, /* Number to convert. */
4610 mp_int *b) /* Place to store the result. */
4616 * Infinite values can't convert to bignum.
4619 if (TclIsInfinite(d)) {
4620 if (interp != NULL) {
4621 const char *s = "integer value too large to represent";
4623 Tcl_SetObjResult(interp, Tcl_NewStringObj(s, -1));
4624 Tcl_SetErrorCode(interp, "ARITH", "IOVERFLOW", s, NULL);
4629 fract = frexp(d,&expt);
4634 Tcl_WideInt w = (Tcl_WideInt) ldexp(fract, mantBits);
4635 int shift = expt - mantBits;
4637 TclBNInitBignumFromWideInt(b, w);
4639 mp_div_2d(b, -shift, b, NULL);
4640 } else if (shift > 0) {
4641 mp_mul_2d(b, shift, b);
4648 *----------------------------------------------------------------------
4650 * TclBignumToDouble --
4652 * Convert an arbitrary-precision integer to a native floating point
4656 * Returns the converted number. Sets errno to ERANGE if the number is
4657 * too large to convert.
4659 *----------------------------------------------------------------------
4664 const mp_int *a) /* Integer to convert. */
4667 int bits, shift, i, lsb;
4672 * We need a 'mantBits'-bit significand. Determine what shift will
4676 bits = mp_count_bits(a);
4677 if (bits > DBL_MAX_EXP*log2FLT_RADIX) {
4685 shift = mantBits - bits;
4688 * If shift > 0, shift the significand left by the requisite number of
4689 * bits. If shift == 0, the significand is already exactly 'mantBits'
4690 * in length. If shift < 0, we will need to shift the significand right
4691 * by the requisite number of bits, and round it. If the '1-shift'
4692 * least significant bits are 0, but the 'shift'th bit is nonzero,
4693 * then the significand lies exactly between two values and must be
4694 * 'rounded to even'.
4700 } else if (shift > 0) {
4701 mp_mul_2d(a, shift, &b);
4702 } else if (shift < 0) {
4703 lsb = mp_cnt_lsb(a);
4704 if (lsb == -1-shift) {
4710 mp_div_2d(a, -shift, &b, NULL);
4713 mp_sub_d(&b, 1, &b);
4715 mp_add_d(&b, 1, &b);
4724 mp_div_2d(a, -1-shift, &b, NULL);
4726 mp_sub_d(&b, 1, &b);
4728 mp_add_d(&b, 1, &b);
4730 mp_div_2d(&b, 1, &b, NULL);
4735 * Accumulate the result, one mp_digit at a time.
4739 for (i=b.used-1 ; i>=0 ; --i) {
4740 r = ldexp(r, MP_DIGIT_BIT) + b.dp[i];
4745 * Scale the result to the correct number of bits.
4748 r = ldexp(r, bits - mantBits);
4751 * Return the result with the appropriate sign.
4762 *----------------------------------------------------------------------
4766 * Computes the smallest floating point number that is at least the
4770 * Returns the floating point number.
4772 *----------------------------------------------------------------------
4777 const mp_int *a) /* Integer to convert. */
4783 if (mp_cmp_d(a, 0) == MP_LT) {
4787 int bits = mp_count_bits(a);
4789 if (bits > DBL_MAX_EXP*log2FLT_RADIX) {
4792 int i, exact = 1, shift = mantBits - bits;
4795 mp_mul_2d(a, shift, &b);
4796 } else if (shift < 0) {
4799 mp_div_2d(a, -shift, &b, &d);
4800 exact = mp_iszero(&d);
4806 mp_add_d(&b, 1, &b);
4808 for (i=b.used-1 ; i>=0 ; --i) {
4809 r = ldexp(r, MP_DIGIT_BIT) + b.dp[i];
4811 r = ldexp(r, bits - mantBits);
4819 *----------------------------------------------------------------------
4823 * Computes the largest floating point number less than or equal to the
4827 * Returns the floating point value.
4829 *----------------------------------------------------------------------
4834 const mp_int *a) /* Integer to convert. */
4840 if (mp_cmp_d(a, 0) == MP_LT) {
4844 int bits = mp_count_bits(a);
4846 if (bits > DBL_MAX_EXP*log2FLT_RADIX) {
4849 int i, shift = mantBits - bits;
4852 mp_mul_2d(a, shift, &b);
4853 } else if (shift < 0) {
4854 mp_div_2d(a, -shift, &b, NULL);
4858 for (i=b.used-1 ; i>=0 ; --i) {
4859 r = ldexp(r, MP_DIGIT_BIT) + b.dp[i];
4861 r = ldexp(r, bits - mantBits);
4869 *----------------------------------------------------------------------
4871 * BignumToBiasedFrExp --
4873 * Convert an arbitrary-precision integer to a native floating point
4874 * number in the range [0.5,1) times a power of two. NOTE: Intentionally
4875 * converts to a number that's a few ulp too small, so that
4876 * RefineApproximation will not overflow near the high end of the
4877 * machine's arithmetic range.
4880 * Returns the converted number.
4883 * Stores the exponent of two in 'machexp'.
4885 *----------------------------------------------------------------------
4889 BignumToBiasedFrExp(
4890 const mp_int *a, /* Integer to convert. */
4891 int *machexp) /* Power of two. */
4900 * Determine how many bits we need, and extract that many from the input.
4901 * Round to nearest unit in the last place.
4904 bits = mp_count_bits(a);
4905 shift = mantBits - 2 - bits;
4908 mp_mul_2d(a, shift, &b);
4909 } else if (shift < 0) {
4910 mp_div_2d(a, -shift, &b, NULL);
4916 * Accumulate the result, one mp_digit at a time.
4920 for (i=b.used-1; i>=0; --i) {
4921 r = ldexp(r, MP_DIGIT_BIT) + b.dp[i];
4926 * Return the result with the appropriate sign.
4929 *machexp = bits - mantBits + 2;
4930 return (mp_isneg(a) ? -r : r);
4934 *----------------------------------------------------------------------
4936 * Pow10TimesFrExp --
4938 * Multiply a power of ten by a number expressed as fraction and
4942 * Returns the significand of the result.
4945 * Overwrites the 'machexp' parameter with the exponent of the result.
4947 * Assumes that 'exponent' is such that 10**exponent would be a double, even
4948 * though 'fraction*10**(machexp+exponent)' might overflow.
4950 *----------------------------------------------------------------------
4955 int exponent, /* Power of 10 to multiply by. */
4956 double fraction, /* Significand of multiplicand. */
4957 int *machexp) /* On input, exponent of multiplicand. On
4958 * output, exponent of result. */
4961 int expt = *machexp;
4962 double retval = fraction;
4966 * Multiply by 10**exponent.
4969 retval = frexp(retval * pow10vals[exponent&0xF], &j);
4971 for (i=4; i<9; ++i) {
4972 if (exponent & (1<<i)) {
4973 retval = frexp(retval * pow_10_2_n[i], &j);
4977 } else if (exponent < 0) {
4979 * Divide by 10**-exponent.
4982 retval = frexp(retval / pow10vals[(-exponent) & 0xF], &j);
4984 for (i=4; i<9; ++i) {
4985 if ((-exponent) & (1<<i)) {
4986 retval = frexp(retval / pow_10_2_n[i], &j);
4997 *----------------------------------------------------------------------
5001 * Do an 'ldexp' operation, but handle denormals gracefully.
5004 * Returns the appropriately scaled value.
5006 * On some platforms, 'ldexp' fails when presented with a number too
5007 * small to represent as a normalized double. This routine does 'ldexp'
5008 * in two steps for those numbers, to return correctly denormalized
5011 *----------------------------------------------------------------------
5019 int minexpt = DBL_MIN_EXP * log2FLT_RADIX;
5020 volatile double a, b, retval;
5022 if (expt < minexpt) {
5023 a = ldexp(fract, expt - mantBits - minexpt);
5024 b = ldexp(1.0, mantBits + minexpt);
5027 retval = ldexp(fract, expt);
5033 *----------------------------------------------------------------------
5037 * Makes the string representation of a "Not a Number"
5043 * Stores the string representation in the supplied buffer, which must be
5044 * at least TCL_DOUBLE_SPACE characters.
5046 *----------------------------------------------------------------------
5051 double value, /* The Not-a-Number to format. */
5052 char *buffer) /* String representation. */
5054 #ifndef IEEE_FLOATING_POINT
5055 strcpy(buffer, "NaN");
5063 bitwhack.dv = value;
5065 bitwhack.iv = Nokia770Twiddle(bitwhack.iv);
5067 if (bitwhack.iv & ((Tcl_WideUInt) 1 << 63)) {
5068 bitwhack.iv &= ~ ((Tcl_WideUInt) 1 << 63);
5074 bitwhack.iv &= (((Tcl_WideUInt) 1) << 51) - 1;
5075 if (bitwhack.iv != 0) {
5076 sprintf(buffer, "(%" TCL_LL_MODIFIER "x)", bitwhack.iv);
5080 #endif /* IEEE_FLOATING_POINT */
5084 *----------------------------------------------------------------------
5086 * Nokia770Twiddle --
5088 * Transpose the two words of a number for Nokia 770 floating point
5091 *----------------------------------------------------------------------
5093 #ifdef IEEE_FLOATING_POINT
5096 Tcl_WideUInt w) /* Number to transpose. */
5098 return (((w >> 32) & 0xFFFFFFFF) | (w << 32));
5103 *----------------------------------------------------------------------
5105 * TclNokia770Doubles --
5107 * Transpose the two words of a number for Nokia 770 floating point
5110 *----------------------------------------------------------------------
5114 TclNokia770Doubles(void)