1 /****************************************************************
3 * The author of this software is David M. Gay.
5 * Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose without fee is hereby granted, provided that this entire notice
9 * is included in all copies of any software which is or includes a copy
10 * or modification of this software and in all copies of the supporting
11 * documentation for such software.
13 * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
14 * WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
15 * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
16 * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
18 ***************************************************************/
21 #define freedtoa __freedtoa
24 /* Please send bug reports to David M. Gay (dmg at acm dot org,
25 * with " at " changed at "@" and " dot " changed to "."). */
27 /* On a machine with IEEE extended-precision registers, it is
28 * necessary to specify double-precision (53-bit) rounding precision
29 * before invoking strtod or dtoa. If the machine uses (the equivalent
30 * of) Intel 80x87 arithmetic, the call
31 * _control87(PC_53, MCW_PC);
32 * does this with many compilers. Whether this or another call is
33 * appropriate depends on the compiler; for this to work, it may be
34 * necessary to #include "float.h" or another system-dependent header
38 /* strtod for IEEE-, VAX-, and IBM-arithmetic machines.
40 * This strtod returns a nearest machine number to the input decimal
41 * string (or sets errno to ERANGE). With IEEE arithmetic, ties are
42 * broken by the IEEE round-even rule. Otherwise ties are broken by
43 * biased rounding (add half and chop).
45 * Inspired loosely by William D. Clinger's paper "How to Read Floating
46 * Point Numbers Accurately" [Proc. ACM SIGPLAN '90, pp. 92-101].
50 * 1. We only require IEEE, IBM, or VAX double-precision
51 * arithmetic (not IEEE double-extended).
52 * 2. We get by with floating-point arithmetic in a case that
53 * Clinger missed -- when we're computing d * 10^n
54 * for a small integer d and the integer n is not too
55 * much larger than 22 (the maximum integer k for which
56 * we can represent 10^k exactly), we may be able to
57 * compute (d*10^k) * 10^(e-k) with just one roundoff.
58 * 3. Rather than a bit-at-a-time adjustment of the binary
59 * result in the hard case, we use floating-point
60 * arithmetic to determine the adjustment to within
61 * one bit; only in really hard cases do we need to
62 * compute a second residual.
63 * 4. Because of 3., we don't need a large table of powers of 10
64 * for ten-to-e (just some small tables, e.g. of 10^k
69 * #define IEEE_8087 for IEEE-arithmetic machines where the least
70 * significant byte has the lowest address.
71 * #define IEEE_MC68k for IEEE-arithmetic machines where the most
72 * significant byte has the lowest address.
73 * #define Long int on machines with 32-bit ints and 64-bit longs.
74 * #define IBM for IBM mainframe-style floating-point arithmetic.
75 * #define VAX for VAX-style floating-point arithmetic (D_floating).
76 * #define No_leftright to omit left-right logic in fast floating-point
77 * computation of dtoa.
78 * #define Honor_FLT_ROUNDS if FLT_ROUNDS can assume the values 2 or 3
79 * and strtod and dtoa should round accordingly.
80 * #define Check_FLT_ROUNDS if FLT_ROUNDS can assume the values 2 or 3
81 * and Honor_FLT_ROUNDS is not #defined.
82 * #define RND_PRODQUOT to use rnd_prod and rnd_quot (assembly routines
83 * that use extended-precision instructions to compute rounded
84 * products and quotients) with IBM.
85 * #define ROUND_BIASED for IEEE-format with biased rounding.
86 * #define Inaccurate_Divide for IEEE-format with correctly rounded
87 * products but inaccurate quotients, e.g., for Intel i860.
88 * #define NO_LONG_LONG on machines that do not have a "long long"
89 * integer type (of >= 64 bits). On such machines, you can
90 * #define Just_16 to store 16 bits per 32-bit Long when doing
91 * high-precision integer arithmetic. Whether this speeds things
92 * up or slows things down depends on the machine and the number
93 * being converted. If long long is available and the name is
94 * something other than "long long", #define Llong to be the name,
95 * and if "unsigned Llong" does not work as an unsigned version of
96 * Llong, #define #ULLong to be the corresponding unsigned type.
97 * #define KR_headers for old-style C function headers.
98 * #define Bad_float_h if your system lacks a float.h or if it does not
99 * define some or all of DBL_DIG, DBL_MAX_10_EXP, DBL_MAX_EXP,
100 * FLT_RADIX, FLT_ROUNDS, and DBL_MAX.
101 * #define MALLOC your_malloc, where your_malloc(n) acts like malloc(n)
102 * if memory is available and otherwise does something you deem
103 * appropriate. If MALLOC is undefined, malloc will be invoked
104 * directly -- and assumed always to succeed.
105 * #define Omit_Private_Memory to omit logic (added Jan. 1998) for making
106 * memory allocations from a private pool of memory when possible.
107 * When used, the private pool is PRIVATE_MEM bytes long: 2304 bytes,
108 * unless #defined to be a different length. This default length
109 * suffices to get rid of MALLOC calls except for unusual cases,
110 * such as decimal-to-binary conversion of a very long string of
111 * digits. The longest string dtoa can return is about 751 bytes
112 * long. For conversions by strtod of strings of 800 digits and
113 * all dtoa conversions in single-threaded executions with 8-byte
114 * pointers, PRIVATE_MEM >= 7400 appears to suffice; with 4-byte
115 * pointers, PRIVATE_MEM >= 7112 appears adequate.
116 * #define INFNAN_CHECK on IEEE systems to cause strtod to check for
117 * Infinity and NaN (case insensitively). On some systems (e.g.,
118 * some HP systems), it may be necessary to #define NAN_WORD0
119 * appropriately -- to the most significant word of a quiet NaN.
120 * (On HP Series 700/800 machines, -DNAN_WORD0=0x7ff40000 works.)
121 * When INFNAN_CHECK is #defined and No_Hex_NaN is not #defined,
122 * strtod also accepts (case insensitively) strings of the form
123 * NaN(x), where x is a string of hexadecimal digits and spaces;
124 * if there is only one string of hexadecimal digits, it is taken
125 * for the 52 fraction bits of the resulting NaN; if there are two
126 * or more strings of hex digits, the first is for the high 20 bits,
127 * the second and subsequent for the low 32 bits, with intervening
128 * white space ignored; but if this results in none of the 52
129 * fraction bits being on (an IEEE Infinity symbol), then NAN_WORD0
130 * and NAN_WORD1 are used instead.
131 * #define MULTIPLE_THREADS if the system offers preemptively scheduled
132 * multiple threads. In this case, you must provide (or suitably
133 * #define) two locks, acquired by ACQUIRE_DTOA_LOCK(n) and freed
134 * by FREE_DTOA_LOCK(n) for n = 0 or 1. (The second lock, accessed
135 * in pow5mult, ensures lazy evaluation of only one copy of high
136 * powers of 5; omitting this lock would introduce a small
137 * probability of wasting memory, but would otherwise be harmless.)
138 * You must also invoke freedtoa(s) to free the value s returned by
139 * dtoa. You may do so whether or not MULTIPLE_THREADS is #defined.
140 * #define NO_IEEE_Scale to disable new (Feb. 1997) logic in strtod that
141 * avoids underflows on inputs whose result does not underflow.
142 * If you #define NO_IEEE_Scale on a machine that uses IEEE-format
143 * floating-point numbers and flushes underflows to zero rather
144 * than implementing gradual underflow, then you must also #define
146 * #define YES_ALIAS to permit aliasing certain double values with
147 * arrays of ULongs. This leads to slightly better code with
148 * some compilers and was always used prior to 19990916, but it
149 * is not strictly legal and can cause trouble with aggressively
150 * optimizing compilers (e.g., gcc 2.95.1 under -O2).
151 * #define USE_LOCALE to use the current locale's decimal_point value.
152 * #define SET_INEXACT if IEEE arithmetic is being used and extra
153 * computation should be done to set the inexact flag when the
154 * result is inexact and avoid setting inexact when the result
155 * is exact. In this case, dtoa.c must be compiled in
156 * an environment, perhaps provided by #include "dtoa.c" in a
157 * suitable wrapper, that defines two functions,
158 * int get_inexact(void);
159 * void clear_inexact(void);
160 * such that get_inexact() returns a nonzero value if the
161 * inexact bit is already set, and clear_inexact() sets the
162 * inexact bit to 0. When SET_INEXACT is #defined, strtod
163 * also does extra computations to set the underflow and overflow
164 * flags when appropriate (i.e., when the result is tiny and
165 * inexact or when it is a numeric value rounded to +-infinity).
166 * #define NO_ERRNO if strtod should not assign errno = ERANGE when
167 * the result overflows to +-Infinity or underflows to 0.
169 #if defined(i386) || defined(mips) && defined(MIPSEL) || defined (__arm__)
173 #elif defined(__x86_64__) || defined(__alpha__)
177 #elif defined(__ia64)
185 #elif defined(__hppa)
194 #define ULong guint32
198 #define Bug(x) {fprintf(stderr, "%s\n", x); exit(1);}
211 extern char *MALLOC();
213 extern void *MALLOC(size_t);
216 #define MALLOC malloc
219 #ifndef Omit_Private_Memory
221 #define PRIVATE_MEM 2304
223 #define PRIVATE_mem ((PRIVATE_MEM+sizeof(double)-1)/sizeof(double))
224 static double private_mem[PRIVATE_mem], *pmem_next = private_mem;
228 #undef Avoid_Underflow
242 #define DBL_MAX_10_EXP 308
243 #define DBL_MAX_EXP 1024
245 #endif /*IEEE_Arith*/
249 #define DBL_MAX_10_EXP 75
250 #define DBL_MAX_EXP 63
252 #define DBL_MAX 7.2370055773322621e+75
257 #define DBL_MAX_10_EXP 38
258 #define DBL_MAX_EXP 127
260 #define DBL_MAX 1.7014118346046923e+38
264 #define LONG_MAX 2147483647
267 #else /* ifndef Bad_float_h */
269 #endif /* Bad_float_h */
281 #define CONST /* blank */
287 #if defined(IEEE_8087) + defined(IEEE_MC68k) + defined(VAX) + defined(IBM) != 1
288 Exactly one of IEEE_8087, IEEE_MC68k, VAX, or IBM should be defined.
291 typedef union { double d; ULong L[2]; } U;
296 #define word0(x) ((ULong *)&x)[1]
297 #define word1(x) ((ULong *)&x)[0]
299 #define word0(x) ((ULong *)&x)[0]
300 #define word1(x) ((ULong *)&x)[1]
304 #define word0(x) ((U*)&x)->L[1]
305 #define word1(x) ((U*)&x)->L[0]
307 #define word0(x) ((U*)&x)->L[0]
308 #define word1(x) ((U*)&x)->L[1]
310 #define dval(x) ((U*)&x)->d
313 /* The following definition of Storeinc is appropriate for MIPS processors.
314 * An alternative that might be better on some machines is
315 * #define Storeinc(a,b,c) (*a++ = b << 16 | c & 0xffff)
317 #if defined(IEEE_8087) + defined(VAX)
318 #define Storeinc(a,b,c) do { (((unsigned short *)a)[1] = (unsigned short)b, \
319 ((unsigned short *)a)[0] = (unsigned short)c, a++) } while (0)
321 #define Storeinc(a,b,c) do { (((unsigned short *)a)[0] = (unsigned short)b, \
322 ((unsigned short *)a)[1] = (unsigned short)c, a++) } while (0)
325 /* #define P DBL_MANT_DIG */
326 /* Ten_pmax = floor(P*log(2)/log(5)) */
327 /* Bletch = (highest power of 2 < DBL_MAX_10_EXP) / 16 */
328 /* Quick_max = floor((P-1)*log(FLT_RADIX)/log(10) - 1) */
329 /* Int_max = floor(P*log(FLT_RADIX)/log(10) - 1) */
333 #define Exp_shift1 20
334 #define Exp_msk1 0x100000
335 #define Exp_msk11 0x100000
336 #define Exp_mask 0x7ff00000
340 #define Exp_1 0x3ff00000
341 #define Exp_11 0x3ff00000
343 #define Frac_mask 0xfffff
344 #define Frac_mask1 0xfffff
347 #define Bndry_mask 0xfffff
348 #define Bndry_mask1 0xfffff
350 #define Sign_bit 0x80000000
356 #ifndef NO_IEEE_Scale
357 #define Avoid_Underflow
358 #ifdef Flush_Denorm /* debugging option */
359 #undef Sudden_Underflow
365 #define Flt_Rounds FLT_ROUNDS
369 #endif /*Flt_Rounds*/
371 #ifdef Honor_FLT_ROUNDS
372 #define Rounding rounding
373 #undef Check_FLT_ROUNDS
374 #define Check_FLT_ROUNDS
376 #define Rounding Flt_Rounds
379 #else /* ifndef IEEE_Arith */
380 #undef Check_FLT_ROUNDS
381 #undef Honor_FLT_ROUNDS
383 #undef Sudden_Underflow
384 #define Sudden_Underflow
389 #define Exp_shift1 24
390 #define Exp_msk1 0x1000000
391 #define Exp_msk11 0x1000000
392 #define Exp_mask 0x7f000000
395 #define Exp_1 0x41000000
396 #define Exp_11 0x41000000
397 #define Ebits 8 /* exponent has 7 bits, but 8 is the right value in b2d */
398 #define Frac_mask 0xffffff
399 #define Frac_mask1 0xffffff
402 #define Bndry_mask 0xefffff
403 #define Bndry_mask1 0xffffff
405 #define Sign_bit 0x80000000
407 #define Tiny0 0x100000
416 #define Exp_msk1 0x80
417 #define Exp_msk11 0x800000
418 #define Exp_mask 0x7f80
421 #define Exp_1 0x40800000
422 #define Exp_11 0x4080
424 #define Frac_mask 0x7fffff
425 #define Frac_mask1 0xffff007f
428 #define Bndry_mask 0xffff007f
429 #define Bndry_mask1 0xffff007f
431 #define Sign_bit 0x8000
437 #endif /* IBM, VAX */
438 #endif /* IEEE_Arith */
445 #define rounded_product(a,b) a = rnd_prod(a, b)
446 #define rounded_quotient(a,b) a = rnd_quot(a, b)
448 extern double rnd_prod(), rnd_quot();
450 extern double rnd_prod(double, double), rnd_quot(double, double);
453 #define rounded_product(a,b) a *= b
454 #define rounded_quotient(a,b) a /= b
457 #define Big0 (Frac_mask1 | Exp_msk1*(DBL_MAX_EXP+Bias-1))
458 #define Big1 0xffffffff
465 #define FFFFFFFF ((((unsigned long)0xffff)<<16)|(unsigned long)0xffff)
467 #define FFFFFFFF 0xffffffffUL
474 /* When Pack_32 is not defined, we store 16 bits per 32-bit Long.
475 * This makes some inner loops simpler and sometimes saves work
476 * during multiplications, but it often seems to make things slightly
477 * slower. Hence the default is now to store 32 bits per Long.
480 #else /* long long available */
482 #define Llong long long
485 #define ULLong unsigned Llong
487 #endif /* NO_LONG_LONG */
489 #ifndef MULTIPLE_THREADS
490 #define ACQUIRE_DTOA_LOCK(n) /*nothing*/
491 #define FREE_DTOA_LOCK(n) /*nothing*/
497 extern "C" double strtod(const char *s00, char **se);
498 extern "C" char *dtoa(double d, int mode, int ndigits,
499 int *decpt, int *sign, char **rve);
505 int k, maxwds, sign, wds;
509 typedef struct Bigint Bigint;
511 static Bigint *freelist[Kmax+1];
523 #ifndef Omit_Private_Memory
527 ACQUIRE_DTOA_LOCK(0);
528 if ((rv = freelist[k])) {
529 freelist[k] = rv->next;
533 #ifdef Omit_Private_Memory
534 rv = (Bigint *)MALLOC(sizeof(Bigint) + (x-1)*sizeof(ULong));
536 len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1)
538 if (pmem_next - private_mem + len <= PRIVATE_mem) {
539 rv = (Bigint*)pmem_next;
543 rv = (Bigint*)MALLOC(len*sizeof(double));
549 rv->sign = rv->wds = 0;
562 ACQUIRE_DTOA_LOCK(0);
563 v->next = freelist[v->k];
569 #define Bcopy(x,y) memcpy((char *)&x->sign, (char *)&y->sign, \
570 y->wds*sizeof(Long) + 2*sizeof(int))
575 (b, m, a) Bigint *b; int m, a;
577 (Bigint *b, int m, int a) /* multiply by m and add a */
598 y = *x * (ULLong)m + carry;
604 y = (xi & 0xffff) * m + carry;
605 z = (xi >> 16) * m + (y >> 16);
607 *x++ = (z << 16) + (y & 0xffff);
617 if (wds >= b->maxwds) {
632 (s, nd0, nd, y9) CONST char *s; int nd0, nd; ULong y9;
634 (CONST char *s, int nd0, int nd, ULong y9)
642 for(k = 0, y = 1; x > y; y <<= 1, k++) ;
649 b->x[0] = y9 & 0xffff;
650 b->wds = (b->x[1] = y9 >> 16) ? 2 : 1;
656 do b = multadd(b, 10, *s++ - '0');
663 b = multadd(b, 10, *s++ - '0');
670 (x) register ULong x;
677 if (!(x & 0xffff0000)) {
681 if (!(x & 0xff000000)) {
685 if (!(x & 0xf0000000)) {
689 if (!(x & 0xc0000000)) {
693 if (!(x & 0x80000000)) {
695 if (!(x & 0x40000000))
710 register ULong x = *y;
768 (a, b) Bigint *a, *b;
770 (Bigint *a, Bigint *b)
775 ULong *x, *xa, *xae, *xb, *xbe, *xc, *xc0;
786 if (a->wds < b->wds) {
798 for(x = c->x, xa = x + wc; x < xa; x++)
806 for(; xb < xbe; xc0++) {
812 z = *x++ * (ULLong)y + *xc + carry;
814 *xc++ = z & FFFFFFFF;
822 for(; xb < xbe; xb++, xc0++) {
823 if (y = *xb & 0xffff) {
828 z = (*x & 0xffff) * y + (*xc & 0xffff) + carry;
830 z2 = (*x++ >> 16) * y + (*xc >> 16) + carry;
843 z = (*x & 0xffff) * y + (*xc >> 16) + carry;
846 z2 = (*x++ >> 16) * y + (*xc & 0xffff) + carry;
854 for(; xb < xbe; xc0++) {
860 z = *x++ * y + *xc + carry;
870 for(xc0 = c->x, xc = xc0 + wc; wc > 0 && !*--xc; --wc) ;
880 (b, k) Bigint *b; int k;
885 Bigint *b1, *p5, *p51;
887 static int p05[3] = { 5, 25, 125 };
890 b = multadd(b, p05[i-1], 0);
896 #ifdef MULTIPLE_THREADS
897 ACQUIRE_DTOA_LOCK(1);
916 if (!(p51 = p5->next)) {
917 #ifdef MULTIPLE_THREADS
918 ACQUIRE_DTOA_LOCK(1);
919 if (!(p51 = p5->next)) {
920 p51 = p5->next = mult(p5,p5);
925 p51 = p5->next = mult(p5,p5);
937 (b, k) Bigint *b; int k;
944 ULong *x, *x1, *xe, z;
953 for(i = b->maxwds; n1 > i; i <<= 1)
957 for(i = 0; i < n; i++)
978 *x1++ = *x << k & 0xffff | z;
997 (a, b) Bigint *a, *b;
999 (Bigint *a, Bigint *b)
1002 ULong *xa, *xa0, *xb, *xb0;
1008 if (i > 1 && !a->x[i-1])
1009 Bug("cmp called with a->x[a->wds-1] == 0");
1010 if (j > 1 && !b->x[j-1])
1011 Bug("cmp called with b->x[b->wds-1] == 0");
1021 return *xa < *xb ? -1 : 1;
1031 (a, b) Bigint *a, *b;
1033 (Bigint *a, Bigint *b)
1038 ULong *xa, *xae, *xb, *xbe, *xc;
1075 y = (ULLong)*xa++ - *xb++ - borrow;
1076 borrow = y >> 32 & (ULong)1;
1077 *xc++ = y & FFFFFFFF;
1082 borrow = y >> 32 & (ULong)1;
1083 *xc++ = y & FFFFFFFF;
1088 y = (*xa & 0xffff) - (*xb & 0xffff) - borrow;
1089 borrow = (y & 0x10000) >> 16;
1090 z = (*xa++ >> 16) - (*xb++ >> 16) - borrow;
1091 borrow = (z & 0x10000) >> 16;
1096 y = (*xa & 0xffff) - borrow;
1097 borrow = (y & 0x10000) >> 16;
1098 z = (*xa++ >> 16) - borrow;
1099 borrow = (z & 0x10000) >> 16;
1104 y = *xa++ - *xb++ - borrow;
1105 borrow = (y & 0x10000) >> 16;
1111 borrow = (y & 0x10000) >> 16;
1133 L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1;
1134 #ifndef Avoid_Underflow
1135 #ifndef Sudden_Underflow
1144 #ifndef Avoid_Underflow
1145 #ifndef Sudden_Underflow
1148 L = -L >> Exp_shift;
1149 if (L < Exp_shift) {
1150 word0(a) = 0x80000 >> L;
1156 word1(a) = L >= 31 ? 1 : 1 << 31 - L;
1167 (a, e) Bigint *a; int *e;
1172 ULong *xa, *xa0, w, y, z;
1186 if (!y) Bug("zero y in b2d");
1192 d0 = Exp_1 | y >> Ebits - k;
1193 w = xa > xa0 ? *--xa : 0;
1194 d1 = y << (32-Ebits) + k | w >> Ebits - k;
1197 z = xa > xa0 ? *--xa : 0;
1199 d0 = Exp_1 | y << k | z >> 32 - k;
1200 y = xa > xa0 ? *--xa : 0;
1201 d1 = z << k | y >> 32 - k;
1208 if (k < Ebits + 16) {
1209 z = xa > xa0 ? *--xa : 0;
1210 d0 = Exp_1 | y << k - Ebits | z >> Ebits + 16 - k;
1211 w = xa > xa0 ? *--xa : 0;
1212 y = xa > xa0 ? *--xa : 0;
1213 d1 = z << k + 16 - Ebits | w << k - Ebits | y >> 16 + Ebits - k;
1216 z = xa > xa0 ? *--xa : 0;
1217 w = xa > xa0 ? *--xa : 0;
1219 d0 = Exp_1 | y << k + 16 | z << k | w >> 16 - k;
1220 y = xa > xa0 ? *--xa : 0;
1221 d1 = w << k + 16 | y << k;
1225 word0(d) = d0 >> 16 | d0 << 16;
1226 word1(d) = d1 >> 16 | d1 << 16;
1237 (d, e, bits) double d; int *e, *bits;
1239 (double d, int *e, int *bits)
1245 #ifndef Sudden_Underflow
1250 d0 = word0(d) >> 16 | word0(d) << 16;
1251 d1 = word1(d) >> 16 | word1(d) << 16;
1265 d0 &= 0x7fffffff; /* clear sign bit, which we ignore */
1266 #ifdef Sudden_Underflow
1267 de = (int)(d0 >> Exp_shift);
1272 if ((de = (int)(d0 >> Exp_shift)))
1277 if ((k = lo0bits(&y))) {
1278 x[0] = y | z << 32 - k;
1283 #ifndef Sudden_Underflow
1286 b->wds = (x[1] = z) ? 2 : 1;
1291 Bug("Zero passed to d2b");
1295 #ifndef Sudden_Underflow
1303 if (k = lo0bits(&y))
1305 x[0] = y | z << 32 - k & 0xffff;
1306 x[1] = z >> k - 16 & 0xffff;
1312 x[1] = y >> 16 | z << 16 - k & 0xffff;
1313 x[2] = z >> k & 0xffff;
1328 Bug("Zero passed to d2b");
1346 #ifndef Sudden_Underflow
1350 *e = (de - Bias - (P-1) << 2) + k;
1351 *bits = 4*P + 8 - k - hi0bits(word0(d) & Frac_mask);
1353 *e = de - Bias - (P-1) + k;
1356 #ifndef Sudden_Underflow
1359 *e = de - Bias - (P-1) + 1 + k;
1361 *bits = 32*i - hi0bits(x[i-1]);
1363 *bits = (i+2)*16 - hi0bits(x[i]);
1375 (a, b) Bigint *a, *b;
1377 (Bigint *a, Bigint *b)
1383 dval(da) = b2d(a, &ka);
1384 dval(db) = b2d(b, &kb);
1386 k = ka - kb + 32*(a->wds - b->wds);
1388 k = ka - kb + 16*(a->wds - b->wds);
1392 word0(da) += (k >> 2)*Exp_msk1;
1398 word0(db) += (k >> 2)*Exp_msk1;
1404 word0(da) += k*Exp_msk1;
1407 word0(db) += k*Exp_msk1;
1410 return dval(da) / dval(db);
1415 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
1416 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
1425 bigtens[] = { 1e16, 1e32, 1e64, 1e128, 1e256 };
1426 static CONST double tinytens[] = { 1e-16, 1e-32, 1e-64, 1e-128,
1427 #ifdef Avoid_Underflow
1428 9007199254740992.*9007199254740992.e-256
1429 /* = 2^106 * 1e-53 */
1434 /* The factor of 2^53 in tinytens[4] helps us avoid setting the underflow */
1435 /* flag unnecessarily. It leads to a song and dance at the end of strtod. */
1436 #define Scale_Bit 0x10
1440 bigtens[] = { 1e16, 1e32, 1e64 };
1441 static CONST double tinytens[] = { 1e-16, 1e-32, 1e-64 };
1444 bigtens[] = { 1e16, 1e32 };
1445 static CONST double tinytens[] = { 1e-16, 1e-32 };
1457 #define NAN_WORD0 0x7ff80000
1467 (sp, t) char **sp, *t;
1469 (CONST char **sp, char *t)
1473 CONST char *s = *sp;
1476 if ((c = *++s) >= 'A' && c <= 'Z')
1489 (rvp, sp) double *rvp; CONST char **sp;
1491 (double *rvp, CONST char **sp)
1496 int havedig, udx0, xshift;
1499 havedig = xshift = 0;
1502 while(c = *(CONST unsigned char*)++s) {
1503 if (c >= '0' && c <= '9')
1505 else if (c >= 'a' && c <= 'f')
1507 else if (c >= 'A' && c <= 'F')
1509 else if (c <= ' ') {
1510 if (udx0 && havedig) {
1516 else if (/*(*/ c == ')' && havedig) {
1521 return; /* invalid form: don't change *sp */
1529 x[0] = (x[0] << 4) | (x[1] >> 28);
1530 x[1] = (x[1] << 4) | c;
1532 if ((x[0] &= 0xfffff) || x[1]) {
1533 word0(*rvp) = Exp_mask | x[0];
1537 #endif /*No_Hex_NaN*/
1538 #endif /* INFNAN_CHECK */
1543 (s00, se) CONST char *s00; char **se;
1545 (CONST char *s00, char **se)
1548 #ifdef Avoid_Underflow
1551 int bb2, bb5, bbe, bd2, bd5, bbbits, bs2, c, dsign,
1552 e, e1, esign, i, j, k, nd, nd0, nf, nz, nz0, sign;
1553 CONST char *s, *s0, *s1;
1554 double aadj, aadj1, adj, rv, rv0;
1557 Bigint *bb, *bb1, *bd, *bd0, *bs, *delta;
1559 int inexact, oldinexact;
1561 #ifdef Honor_FLT_ROUNDS
1568 sign = nz0 = nz = 0;
1570 for(s = s00;;s++) switch(*s) {
1593 while(*++s == '0') ;
1599 for(nd = nf = 0; (c = *s) >= '0' && c <= '9'; nd++, s++)
1606 s1 = localeconv()->decimal_point;
1627 for(; c == '0'; c = *++s)
1629 if (c > '0' && c <= '9') {
1637 for(; c >= '0' && c <= '9'; c = *++s) {
1642 for(i = 1; i < nz; i++)
1645 else if (nd <= DBL_DIG + 1)
1649 else if (nd <= DBL_DIG + 1)
1657 if (c == 'e' || c == 'E') {
1658 if (!nd && !nz && !nz0) {
1669 if (c >= '0' && c <= '9') {
1672 if (c > '0' && c <= '9') {
1675 while((c = *++s) >= '0' && c <= '9')
1677 if (s - s1 > 8 || L > 19999)
1678 /* Avoid confusion from exponents
1679 * so large that e might overflow.
1681 e = 19999; /* safe for 16 bit ints */
1696 /* Check for Nan and Infinity */
1700 if (match(&s,"nf")) {
1702 if (!match(&s,"inity"))
1704 word0(rv) = 0x7ff00000;
1711 if (match(&s, "an")) {
1712 word0(rv) = NAN_WORD0;
1713 word1(rv) = NAN_WORD1;
1715 if (*s == '(') /*)*/
1721 #endif /* INFNAN_CHECK */
1730 /* Now we have nd0 digits, starting at s0, followed by a
1731 * decimal point, followed by nd-nd0 digits. The number we're
1732 * after is the integer represented by those digits times
1737 k = nd < DBL_DIG + 1 ? nd : DBL_DIG + 1;
1742 oldinexact = get_inexact();
1744 dval(rv) = tens[k - 9] * dval(rv) + z;
1748 #ifndef RND_PRODQUOT
1749 #ifndef Honor_FLT_ROUNDS
1757 if (e <= Ten_pmax) {
1759 goto vax_ovfl_check;
1761 #ifdef Honor_FLT_ROUNDS
1762 /* round correctly FLT_ROUNDS = 2 or 3 */
1768 /* rv = */ rounded_product(dval(rv), tens[e]);
1773 if (e <= Ten_pmax + i) {
1774 /* A fancier test would sometimes let us do
1775 * this for larger i values.
1777 #ifdef Honor_FLT_ROUNDS
1778 /* round correctly FLT_ROUNDS = 2 or 3 */
1785 dval(rv) *= tens[i];
1787 /* VAX exponent range is so narrow we must
1788 * worry about overflow here...
1791 word0(rv) -= P*Exp_msk1;
1792 /* rv = */ rounded_product(dval(rv), tens[e]);
1793 if ((word0(rv) & Exp_mask)
1794 > Exp_msk1*(DBL_MAX_EXP+Bias-1-P))
1796 word0(rv) += P*Exp_msk1;
1798 /* rv = */ rounded_product(dval(rv), tens[e]);
1803 #ifndef Inaccurate_Divide
1804 else if (e >= -Ten_pmax) {
1805 #ifdef Honor_FLT_ROUNDS
1806 /* round correctly FLT_ROUNDS = 2 or 3 */
1812 /* rv = */ rounded_quotient(dval(rv), tens[-e]);
1823 oldinexact = get_inexact();
1825 #ifdef Avoid_Underflow
1828 #ifdef Honor_FLT_ROUNDS
1829 if ((rounding = Flt_Rounds) >= 2) {
1831 rounding = rounding == 2 ? 0 : 2;
1837 #endif /*IEEE_Arith*/
1839 /* Get starting approximation = rv * 10**e1 */
1843 dval(rv) *= tens[i];
1845 if (e1 > DBL_MAX_10_EXP) {
1850 /* Can't trust HUGE_VAL */
1852 #ifdef Honor_FLT_ROUNDS
1854 case 0: /* toward 0 */
1855 case 3: /* toward -infinity */
1860 word0(rv) = Exp_mask;
1863 #else /*Honor_FLT_ROUNDS*/
1864 word0(rv) = Exp_mask;
1866 #endif /*Honor_FLT_ROUNDS*/
1868 /* set overflow bit */
1870 dval(rv0) *= dval(rv0);
1872 #else /*IEEE_Arith*/
1875 #endif /*IEEE_Arith*/
1881 for(j = 0; e1 > 1; j++, e1 >>= 1)
1883 dval(rv) *= bigtens[j];
1884 /* The last multiplication could overflow. */
1885 word0(rv) -= P*Exp_msk1;
1886 dval(rv) *= bigtens[j];
1887 if ((z = word0(rv) & Exp_mask)
1888 > Exp_msk1*(DBL_MAX_EXP+Bias-P))
1890 if (z > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) {
1891 /* set to largest number */
1892 /* (Can't trust DBL_MAX) */
1897 word0(rv) += P*Exp_msk1;
1903 dval(rv) /= tens[i];
1905 if (e1 >= 1 << n_bigtens)
1907 #ifdef Avoid_Underflow
1910 for(j = 0; e1 > 0; j++, e1 >>= 1)
1912 dval(rv) *= tinytens[j];
1913 if (scale && (j = 2*P + 1 - ((word0(rv) & Exp_mask)
1914 >> Exp_shift)) > 0) {
1915 /* scaled rv is denormal; zap j low bits */
1919 word0(rv) = (P+2)*Exp_msk1;
1921 word0(rv) &= 0xffffffff << j-32;
1924 word1(rv) &= 0xffffffff << j;
1927 for(j = 0; e1 > 1; j++, e1 >>= 1)
1929 dval(rv) *= tinytens[j];
1930 /* The last multiplication could underflow. */
1931 dval(rv0) = dval(rv);
1932 dval(rv) *= tinytens[j];
1934 dval(rv) = 2.*dval(rv0);
1935 dval(rv) *= tinytens[j];
1947 #ifndef Avoid_Underflow
1950 /* The refinement below will clean
1951 * this approximation up.
1958 /* Now the hard part -- adjusting rv to the correct value.*/
1960 /* Put digits into bd: true value = bd * 10^e */
1962 bd0 = s2b(s0, nd0, nd, y);
1965 bd = Balloc(bd0->k);
1967 bb = d2b(dval(rv), &bbe, &bbbits); /* rv = bb * 2^bbe */
1983 #ifdef Honor_FLT_ROUNDS
1987 #ifdef Avoid_Underflow
1989 i = j + bbbits - 1; /* logb(rv) */
1990 if (i < Emin) /* denormal */
1994 #else /*Avoid_Underflow*/
1995 #ifdef Sudden_Underflow
1997 j = 1 + 4*P - 3 - bbbits + ((bbe + bbbits - 1) & 3);
2001 #else /*Sudden_Underflow*/
2003 i = j + bbbits - 1; /* logb(rv) */
2004 if (i < Emin) /* denormal */
2008 #endif /*Sudden_Underflow*/
2009 #endif /*Avoid_Underflow*/
2012 #ifdef Avoid_Underflow
2015 i = bb2 < bd2 ? bb2 : bd2;
2024 bs = pow5mult(bs, bb5);
2030 bb = lshift(bb, bb2);
2032 bd = pow5mult(bd, bd5);
2034 bd = lshift(bd, bd2);
2036 bs = lshift(bs, bs2);
2037 delta = diff(bb, bd);
2038 dsign = delta->sign;
2041 #ifdef Honor_FLT_ROUNDS
2042 if (rounding != 1) {
2044 /* Error is less than an ulp */
2045 if (!delta->x[0] && delta->wds <= 1) {
2061 && !(word0(rv) & Frac_mask)) {
2062 y = word0(rv) & Exp_mask;
2063 #ifdef Avoid_Underflow
2064 if (!scale || y > 2*P*Exp_msk1)
2069 delta = lshift(delta,Log2P);
2070 if (cmp(delta, bs) <= 0)
2075 #ifdef Avoid_Underflow
2076 if (scale && (y = word0(rv) & Exp_mask)
2078 word0(adj) += (2*P+1)*Exp_msk1 - y;
2080 #ifdef Sudden_Underflow
2081 if ((word0(rv) & Exp_mask) <=
2083 word0(rv) += P*Exp_msk1;
2084 dval(rv) += adj*ulp(dval(rv));
2085 word0(rv) -= P*Exp_msk1;
2088 #endif /*Sudden_Underflow*/
2089 #endif /*Avoid_Underflow*/
2090 dval(rv) += adj*ulp(dval(rv));
2094 adj = ratio(delta, bs);
2097 if (adj <= 0x7ffffffe) {
2098 /* adj = rounding ? ceil(adj) : floor(adj); */
2101 if (!((rounding>>1) ^ dsign))
2106 #ifdef Avoid_Underflow
2107 if (scale && (y = word0(rv) & Exp_mask) <= 2*P*Exp_msk1)
2108 word0(adj) += (2*P+1)*Exp_msk1 - y;
2110 #ifdef Sudden_Underflow
2111 if ((word0(rv) & Exp_mask) <= P*Exp_msk1) {
2112 word0(rv) += P*Exp_msk1;
2113 adj *= ulp(dval(rv));
2118 word0(rv) -= P*Exp_msk1;
2121 #endif /*Sudden_Underflow*/
2122 #endif /*Avoid_Underflow*/
2123 adj *= ulp(dval(rv));
2130 #endif /*Honor_FLT_ROUNDS*/
2133 /* Error is less than half an ulp -- check for
2134 * special case of mantissa a power of two.
2136 if (dsign || word1(rv) || word0(rv) & Bndry_mask
2138 #ifdef Avoid_Underflow
2139 || (word0(rv) & Exp_mask) <= (2*P+1)*Exp_msk1
2141 || (word0(rv) & Exp_mask) <= Exp_msk1
2146 if (!delta->x[0] && delta->wds <= 1)
2151 if (!delta->x[0] && delta->wds <= 1) {
2158 delta = lshift(delta,Log2P);
2159 if (cmp(delta, bs) > 0)
2164 /* exactly half-way between */
2166 if ((word0(rv) & Bndry_mask1) == Bndry_mask1
2168 #ifdef Avoid_Underflow
2169 (scale && (y = word0(rv) & Exp_mask) <= 2*P*Exp_msk1)
2170 ? (0xffffffff & (0xffffffff << (2*P+1-(y>>Exp_shift)))) :
2173 /*boundary case -- increment exponent*/
2174 word0(rv) = (word0(rv) & Exp_mask)
2181 #ifdef Avoid_Underflow
2187 else if (!(word0(rv) & Bndry_mask) && !word1(rv)) {
2189 /* boundary case -- decrement exponent */
2190 #ifdef Sudden_Underflow /*{{*/
2191 L = word0(rv) & Exp_mask;
2195 #ifdef Avoid_Underflow
2196 if (L <= (scale ? (2*P+1)*Exp_msk1 : Exp_msk1))
2199 #endif /*Avoid_Underflow*/
2203 #else /*Sudden_Underflow}{*/
2204 #ifdef Avoid_Underflow
2206 L = word0(rv) & Exp_mask;
2207 if (L <= (2*P+1)*Exp_msk1) {
2208 if (L > (P+2)*Exp_msk1)
2209 /* round even ==> */
2212 /* rv = smallest denormal */
2216 #endif /*Avoid_Underflow*/
2217 L = (word0(rv) & Exp_mask) - Exp_msk1;
2218 #endif /*Sudden_Underflow}}*/
2219 word0(rv) = L | Bndry_mask1;
2220 word1(rv) = 0xffffffff;
2227 #ifndef ROUND_BIASED
2228 if (!(word1(rv) & LSB))
2232 dval(rv) += ulp(dval(rv));
2233 #ifndef ROUND_BIASED
2235 dval(rv) -= ulp(dval(rv));
2236 #ifndef Sudden_Underflow
2241 #ifdef Avoid_Underflow
2247 if ((aadj = ratio(delta, bs)) <= 2.) {
2250 else if (word1(rv) || word0(rv) & Bndry_mask) {
2251 #ifndef Sudden_Underflow
2252 if (word1(rv) == Tiny1 && !word0(rv))
2259 /* special case -- power of FLT_RADIX to be */
2260 /* rounded down... */
2262 if (aadj < 2./FLT_RADIX)
2263 aadj = 1./FLT_RADIX;
2271 aadj1 = dsign ? aadj : -aadj;
2272 #ifdef Check_FLT_ROUNDS
2274 case 2: /* towards +infinity */
2277 case 0: /* towards 0 */
2278 case 3: /* towards -infinity */
2282 if (Flt_Rounds == 0)
2284 #endif /*Check_FLT_ROUNDS*/
2286 y = word0(rv) & Exp_mask;
2288 /* Check for overflow */
2290 if (y == Exp_msk1*(DBL_MAX_EXP+Bias-1)) {
2291 dval(rv0) = dval(rv);
2292 word0(rv) -= P*Exp_msk1;
2293 adj = aadj1 * ulp(dval(rv));
2295 if ((word0(rv) & Exp_mask) >=
2296 Exp_msk1*(DBL_MAX_EXP+Bias-P)) {
2297 if (word0(rv0) == Big0 && word1(rv0) == Big1)
2304 word0(rv) += P*Exp_msk1;
2307 #ifdef Avoid_Underflow
2308 if (scale && y <= 2*P*Exp_msk1) {
2309 if (aadj <= 0x7fffffff) {
2310 if ((z = aadj) <= 0)
2313 aadj1 = dsign ? aadj : -aadj;
2315 word0(aadj1) += (2*P+1)*Exp_msk1 - y;
2317 adj = aadj1 * ulp(dval(rv));
2320 #ifdef Sudden_Underflow
2321 if ((word0(rv) & Exp_mask) <= P*Exp_msk1) {
2322 dval(rv0) = dval(rv);
2323 word0(rv) += P*Exp_msk1;
2324 adj = aadj1 * ulp(dval(rv));
2327 if ((word0(rv) & Exp_mask) < P*Exp_msk1)
2329 if ((word0(rv) & Exp_mask) <= P*Exp_msk1)
2332 if (word0(rv0) == Tiny0
2333 && word1(rv0) == Tiny1)
2340 word0(rv) -= P*Exp_msk1;
2343 adj = aadj1 * ulp(dval(rv));
2346 #else /*Sudden_Underflow*/
2347 /* Compute adj so that the IEEE rounding rules will
2348 * correctly round rv + adj in some half-way cases.
2349 * If rv * ulp(rv) is denormalized (i.e.,
2350 * y <= (P-1)*Exp_msk1), we must adjust aadj to avoid
2351 * trouble from bits lost to denormalization;
2352 * example: 1.2e-307 .
2354 if (y <= (P-1)*Exp_msk1 && aadj > 1.) {
2355 aadj1 = (double)(int)(aadj + 0.5);
2359 adj = aadj1 * ulp(dval(rv));
2361 #endif /*Sudden_Underflow*/
2362 #endif /*Avoid_Underflow*/
2364 z = word0(rv) & Exp_mask;
2366 #ifdef Avoid_Underflow
2370 /* Can we stop now? */
2373 /* The tolerances below are conservative. */
2374 if (dsign || word1(rv) || word0(rv) & Bndry_mask) {
2375 if (aadj < .4999999 || aadj > .5000001)
2378 else if (aadj < .4999999/FLT_RADIX)
2391 word0(rv0) = Exp_1 + (70 << Exp_shift);
2396 else if (!oldinexact)
2399 #ifdef Avoid_Underflow
2401 word0(rv0) = Exp_1 - 2*P*Exp_msk1;
2403 dval(rv) *= dval(rv0);
2405 /* try to avoid the bug of testing an 8087 register value */
2406 if (word0(rv) == 0 && word1(rv) == 0)
2410 #endif /* Avoid_Underflow */
2412 if (inexact && !(word0(rv) & Exp_mask)) {
2413 /* set underflow bit */
2415 dval(rv0) *= dval(rv0);
2427 return sign ? -dval(rv) : dval(rv);
2433 (b, S) Bigint *b, *S;
2435 (Bigint *b, Bigint *S)
2439 ULong *bx, *bxe, q, *sx, *sxe;
2441 ULLong borrow, carry, y, ys;
2443 ULong borrow, carry, y, ys;
2451 /*debug*/ if (b->wds > n)
2452 /*debug*/ Bug("oversize b in quorem");
2460 q = *bxe / (*sxe + 1); /* ensure q <= true quotient */
2462 /*debug*/ if (q > 9)
2463 /*debug*/ Bug("oversized quotient in quorem");
2470 ys = *sx++ * (ULLong)q + carry;
2472 y = *bx - (ys & FFFFFFFF) - borrow;
2473 borrow = y >> 32 & (ULong)1;
2474 *bx++ = y & FFFFFFFF;
2478 ys = (si & 0xffff) * q + carry;
2479 zs = (si >> 16) * q + (ys >> 16);
2481 y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
2482 borrow = (y & 0x10000) >> 16;
2483 z = (*bx >> 16) - (zs & 0xffff) - borrow;
2484 borrow = (z & 0x10000) >> 16;
2487 ys = *sx++ * q + carry;
2489 y = *bx - (ys & 0xffff) - borrow;
2490 borrow = (y & 0x10000) >> 16;
2498 while(--bxe > bx && !*bxe)
2503 if (cmp(b, S) >= 0) {
2513 y = *bx - (ys & FFFFFFFF) - borrow;
2514 borrow = y >> 32 & (ULong)1;
2515 *bx++ = y & FFFFFFFF;
2519 ys = (si & 0xffff) + carry;
2520 zs = (si >> 16) + (ys >> 16);
2522 y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
2523 borrow = (y & 0x10000) >> 16;
2524 z = (*bx >> 16) - (zs & 0xffff) - borrow;
2525 borrow = (z & 0x10000) >> 16;
2530 y = *bx - (ys & 0xffff) - borrow;
2531 borrow = (y & 0x10000) >> 16;
2540 while(--bxe > bx && !*bxe)
2548 #ifndef MULTIPLE_THREADS
2549 static char *dtoa_result;
2563 sizeof(Bigint) - sizeof(ULong) - sizeof(int) + j <= i;
2566 r = (int*)Balloc(k);
2569 #ifndef MULTIPLE_THREADS
2577 nrv_alloc(s, rve, n) char *s, **rve; int n;
2579 nrv_alloc(char *s, char **rve, int n)
2584 t = rv = rv_alloc(n);
2585 while((*t = *s++)) t++;
2591 /* freedtoa(s) must be used to free values s returned by dtoa
2592 * when MULTIPLE_THREADS is #defined. It should be used in all cases,
2593 * but for consistency with earlier versions of dtoa, it is optional
2594 * when MULTIPLE_THREADS is not defined.
2597 void freedtoa (char *s);
2601 freedtoa(s) char *s;
2606 Bigint *b = (Bigint *)((int *)s - 1);
2607 b->maxwds = 1 << (b->k = *(int*)b);
2609 #ifndef MULTIPLE_THREADS
2610 if (s == dtoa_result)
2616 /* dtoa for IEEE arithmetic (dmg): convert double to ASCII string.
2618 * Inspired by "How to Print Floating-Point Numbers Accurately" by
2619 * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 112-126].
2622 * 1. Rather than iterating, we use a simple numeric overestimate
2623 * to determine k = floor(log10(d)). We scale relevant
2624 * quantities using O(log2(k)) rather than O(k) multiplications.
2625 * 2. For some modes > 2 (corresponding to ecvt and fcvt), we don't
2626 * try to generate digits strictly left to right. Instead, we
2627 * compute with fewer bits and propagate the carry if necessary
2628 * when rounding the final digit up. This is often faster.
2629 * 3. Under the assumption that input will be rounded nearest,
2630 * mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22.
2631 * That is, we allow equality in stopping tests when the
2632 * round-nearest rule will give the same floating-point value
2633 * as would satisfaction of the stopping test with strict
2635 * 4. We remove common factors of powers of 2 from relevant
2637 * 5. When converting floating-point integers less than 1e16,
2638 * we use floating-point arithmetic rather than resorting
2639 * to multiple-precision integers.
2640 * 6. When asked to produce fewer than 15 digits, we first try
2641 * to get by with floating-point arithmetic; we resort to
2642 * multiple-precision integer arithmetic only if we cannot
2643 * guarantee that the floating-point calculation has given
2644 * the correctly rounded result. For k requested digits and
2645 * "uniformly" distributed input, the probability is
2646 * something like 10^(k-15) that we must resort to the Long
2653 (d, mode, ndigits, decpt, sign, rve)
2654 double d; int mode, ndigits, *decpt, *sign; char **rve;
2656 (double d, int mode, int ndigits, int *decpt, int *sign, char **rve)
2659 /* Arguments ndigits, decpt, sign are similar to those
2660 of ecvt and fcvt; trailing zeros are suppressed from
2661 the returned string. If not null, *rve is set to point
2662 to the end of the return value. If d is +-Infinity or NaN,
2663 then *decpt is set to 9999.
2666 0 ==> shortest string that yields d when read in
2667 and rounded to nearest.
2668 1 ==> like 0, but with Steele & White stopping rule;
2669 e.g. with IEEE P754 arithmetic , mode 0 gives
2670 1e23 whereas mode 1 gives 9.999999999999999e22.
2671 2 ==> max(1,ndigits) significant digits. This gives a
2672 return value similar to that of ecvt, except
2673 that trailing zeros are suppressed.
2674 3 ==> through ndigits past the decimal point. This
2675 gives a return value similar to that from fcvt,
2676 except that trailing zeros are suppressed, and
2677 ndigits can be negative.
2678 4,5 ==> similar to 2 and 3, respectively, but (in
2679 round-nearest mode) with the tests of mode 0 to
2680 possibly return a shorter string that rounds to d.
2681 With IEEE arithmetic and compilation with
2682 -DHonor_FLT_ROUNDS, modes 4 and 5 behave the same
2683 as modes 2 and 3 when FLT_ROUNDS != 1.
2684 6-9 ==> Debugging modes similar to mode - 4: don't try
2685 fast floating-point estimate (if applicable).
2687 Values of mode other than 0-9 are treated as mode 0.
2689 Sufficient space is allocated to the return value
2690 to hold the suppressed trailing zeros.
2693 int bbits, b2, b5, be, dig, i, ieps, ilim, ilim0, ilim1,
2694 j, j1, k, k0, k_check, leftright, m2, m5, s2, s5,
2695 spec_case, try_quick;
2697 #ifndef Sudden_Underflow
2701 Bigint *b, *b1, *delta, *mlo, *mhi, *S;
2704 #ifdef Honor_FLT_ROUNDS
2708 int inexact, oldinexact;
2711 #ifndef MULTIPLE_THREADS
2713 freedtoa(dtoa_result);
2718 if (word0(d) & Sign_bit) {
2719 /* set sign for everything, including 0's and NaNs */
2721 word0(d) &= ~Sign_bit; /* clear sign bit */
2726 #if defined(IEEE_Arith) + defined(VAX)
2728 if ((word0(d) & Exp_mask) == Exp_mask)
2730 if (word0(d) == 0x8000)
2733 /* Infinity or NaN */
2736 if (!word1(d) && !(word0(d) & 0xfffff))
2737 return nrv_alloc("Infinity", rve, 8);
2739 return nrv_alloc("NaN", rve, 3);
2743 dval(d) += 0; /* normalize */
2747 return nrv_alloc("0", rve, 1);
2751 try_quick = oldinexact = get_inexact();
2754 #ifdef Honor_FLT_ROUNDS
2755 if ((rounding = Flt_Rounds) >= 2) {
2757 rounding = rounding == 2 ? 0 : 2;
2764 b = d2b(dval(d), &be, &bbits);
2765 #ifdef Sudden_Underflow
2766 i = (int)(word0(d) >> Exp_shift1 & (Exp_mask>>Exp_shift1));
2768 if (i = (int)(word0(d) >> Exp_shift1 & (Exp_mask>>Exp_shift1))) {
2771 word0(d2) &= Frac_mask1;
2772 word0(d2) |= Exp_11;
2774 if (j = 11 - hi0bits(word0(d2) & Frac_mask))
2778 /* log(x) ~=~ log(1.5) + (x-1.5)/1.5
2779 * log10(x) = log(x) / log(10)
2780 * ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10))
2781 * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2)
2783 * This suggests computing an approximation k to log10(d) by
2785 * k = (i - Bias)*0.301029995663981
2786 * + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 );
2788 * We want k to be too large rather than too small.
2789 * The error in the first-order Taylor series approximation
2790 * is in our favor, so we just round up the constant enough
2791 * to compensate for any error in the multiplication of
2792 * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077,
2793 * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14,
2794 * adding 1e-13 to the constant term more than suffices.
2795 * Hence we adjust the constant term to 0.1760912590558.
2796 * (We could get a more accurate k by invoking log10,
2797 * but this is probably not worthwhile.)
2805 #ifndef Sudden_Underflow
2809 /* d is denormalized */
2811 i = bbits + be + (Bias + (P-1) - 1);
2812 x = i > 32 ? word0(d) << 64 - i | word1(d) >> i - 32
2813 : word1(d) << 32 - i;
2815 word0(d2) -= 31*Exp_msk1; /* adjust exponent */
2816 i -= (Bias + (P-1) - 1) + 1;
2820 ds = (dval(d2)-1.5)*0.289529654602168 + 0.1760912590558 + i*0.301029995663981;
2822 if (ds < 0. && ds != k)
2823 k--; /* want k = floor(ds) */
2825 if (k >= 0 && k <= Ten_pmax) {
2826 if (dval(d) < tens[k])
2849 if (mode < 0 || mode > 9)
2853 #ifdef Check_FLT_ROUNDS
2854 try_quick = Rounding == 1;
2858 #endif /*SET_INEXACT*/
2878 ilim = ilim1 = i = ndigits;
2884 i = ndigits + k + 1;
2890 s = s0 = rv_alloc(i);
2892 #ifdef Honor_FLT_ROUNDS
2893 if (mode > 1 && rounding != 1)
2897 if (ilim >= 0 && ilim <= Quick_max && try_quick) {
2899 /* Try to get by with floating-point arithmetic. */
2905 ieps = 2; /* conservative */
2910 /* prevent overflows */
2912 dval(d) /= bigtens[n_bigtens-1];
2915 for(; j; j >>= 1, i++)
2923 dval(d) *= tens[j1 & 0xf];
2924 for(j = j1 >> 4; j; j >>= 1, i++)
2927 dval(d) *= bigtens[i];
2930 if (k_check && dval(d) < 1. && ilim > 0) {
2938 dval(eps) = ieps*dval(d) + 7.;
2939 word0(eps) -= (P-1)*Exp_msk1;
2943 if (dval(d) > dval(eps))
2945 if (dval(d) < -dval(eps))
2949 #ifndef No_leftright
2951 /* Use Steele & White method of only
2952 * generating digits needed.
2954 dval(eps) = 0.5/tens[ilim-1] - dval(eps);
2958 *s++ = '0' + (int)L;
2959 if (dval(d) < dval(eps))
2961 if (1. - dval(d) < dval(eps))
2971 /* Generate ilim digits, then fix them up. */
2972 dval(eps) *= tens[ilim-1];
2973 for(i = 1;; i++, dval(d) *= 10.) {
2974 L = (Long)(dval(d));
2975 if (!(dval(d) -= L))
2977 *s++ = '0' + (int)L;
2979 if (dval(d) > 0.5 + dval(eps))
2981 else if (dval(d) < 0.5 - dval(eps)) {
2989 #ifndef No_leftright
2999 /* Do we have a "small" integer? */
3001 if (be >= 0 && k <= Int_max) {
3004 if (ndigits < 0 && ilim <= 0) {
3006 if (ilim < 0 || dval(d) <= 5*ds)
3010 for(i = 1;; i++, dval(d) *= 10.) {
3011 L = (Long)(dval(d) / ds);
3013 #ifdef Check_FLT_ROUNDS
3014 /* If FLT_ROUNDS == 2, L will usually be high by 1 */
3020 *s++ = '0' + (int)L;
3028 #ifdef Honor_FLT_ROUNDS
3032 case 2: goto bump_up;
3036 if (dval(d) > ds || dval(d) == ds && L & 1) {
3057 #ifndef Sudden_Underflow
3058 denorm ? be + (Bias + (P-1) - 1 + 1) :
3061 1 + 4*P - 3 - bbits + ((bbits + be - 1) & 3);
3069 if (m2 > 0 && s2 > 0) {
3070 i = m2 < s2 ? m2 : s2;
3078 mhi = pow5mult(mhi, m5);
3087 b = pow5mult(b, b5);
3091 S = pow5mult(S, s5);
3093 /* Check for special case that d is a normalized power of 2. */
3096 if ((mode < 2 || leftright)
3097 #ifdef Honor_FLT_ROUNDS
3101 if (!word1(d) && !(word0(d) & Bndry_mask)
3102 #ifndef Sudden_Underflow
3103 && word0(d) & (Exp_mask & ~Exp_msk1)
3106 /* The special case */
3113 /* Arrange for convenient computation of quotients:
3114 * shift left if necessary so divisor has 4 leading 0 bits.
3116 * Perhaps we should just compute leading 28 bits of S once
3117 * and for all and pass them and a shift to quorem, so it
3118 * can do shifts and ors to compute the numerator for q.
3121 if (i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0x1f)
3124 if (i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0xf)
3146 b = multadd(b, 10, 0); /* we botched the k estimate */
3148 mhi = multadd(mhi, 10, 0);
3152 if (ilim <= 0 && (mode == 3 || mode == 5)) {
3153 if (ilim < 0 || cmp(b,S = multadd(S,5,0)) <= 0) {
3154 /* no digits, fcvt style */
3166 mhi = lshift(mhi, m2);
3168 /* Compute mlo -- check for special case
3169 * that d is a normalized power of 2.
3174 mhi = Balloc(mhi->k);
3176 mhi = lshift(mhi, Log2P);
3180 dig = quorem(b,S) + '0';
3181 /* Do we yet have the shortest decimal string
3182 * that will round to d?
3185 delta = diff(S, mhi);
3186 j1 = delta->sign ? 1 : cmp(b, delta);
3188 #ifndef ROUND_BIASED
3189 if (j1 == 0 && mode != 1 && !(word1(d) & 1)
3190 #ifdef Honor_FLT_ROUNDS
3199 else if (!b->x[0] && b->wds <= 1)
3206 if (j < 0 || j == 0 && mode != 1
3207 #ifndef ROUND_BIASED
3211 if (!b->x[0] && b->wds <= 1) {
3217 #ifdef Honor_FLT_ROUNDS
3220 case 0: goto accept_dig;
3221 case 2: goto keep_dig;
3223 #endif /*Honor_FLT_ROUNDS*/
3227 if ((j1 > 0 || j1 == 0 && dig & 1)
3236 #ifdef Honor_FLT_ROUNDS
3240 if (dig == '9') { /* possible if i == 1 */
3248 #ifdef Honor_FLT_ROUNDS
3254 b = multadd(b, 10, 0);
3256 mlo = mhi = multadd(mhi, 10, 0);
3258 mlo = multadd(mlo, 10, 0);
3259 mhi = multadd(mhi, 10, 0);
3265 *s++ = dig = quorem(b,S) + '0';
3266 if (!b->x[0] && b->wds <= 1) {
3274 b = multadd(b, 10, 0);
3277 /* Round off last digit */
3279 #ifdef Honor_FLT_ROUNDS
3281 case 0: goto trimzeros;
3282 case 2: goto roundoff;
3287 if (j > 0 || j == 0 && dig & 1) {
3305 if (mlo && mlo != mhi)
3313 word0(d) = Exp_1 + (70 << Exp_shift);
3318 else if (!oldinexact)