remove old metaclass demos
[python/dscho.git] / Python / dtoa.c
blob82434bccc2ff42bf335c352493ed96b8f8d0e8f8
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 ***************************************************************/
20 /****************************************************************
21 * This is dtoa.c by David M. Gay, downloaded from
22 * http://www.netlib.org/fp/dtoa.c on April 15, 2009 and modified for
23 * inclusion into the Python core by Mark E. T. Dickinson and Eric V. Smith.
25 * Please remember to check http://www.netlib.org/fp regularly (and especially
26 * before any Python release) for bugfixes and updates.
28 * The major modifications from Gay's original code are as follows:
30 * 0. The original code has been specialized to Python's needs by removing
31 * many of the #ifdef'd sections. In particular, code to support VAX and
32 * IBM floating-point formats, hex NaNs, hex floats, locale-aware
33 * treatment of the decimal point, and setting of the inexact flag have
34 * been removed.
36 * 1. We use PyMem_Malloc and PyMem_Free in place of malloc and free.
38 * 2. The public functions strtod, dtoa and freedtoa all now have
39 * a _Py_dg_ prefix.
41 * 3. Instead of assuming that PyMem_Malloc always succeeds, we thread
42 * PyMem_Malloc failures through the code. The functions
44 * Balloc, multadd, s2b, i2b, mult, pow5mult, lshift, diff, d2b
46 * of return type *Bigint all return NULL to indicate a malloc failure.
47 * Similarly, rv_alloc and nrv_alloc (return type char *) return NULL on
48 * failure. bigcomp now has return type int (it used to be void) and
49 * returns -1 on failure and 0 otherwise. _Py_dg_dtoa returns NULL
50 * on failure. _Py_dg_strtod indicates failure due to malloc failure
51 * by returning -1.0, setting errno=ENOMEM and *se to s00.
53 * 4. The static variable dtoa_result has been removed. Callers of
54 * _Py_dg_dtoa are expected to call _Py_dg_freedtoa to free
55 * the memory allocated by _Py_dg_dtoa.
57 * 5. The code has been reformatted to better fit with Python's
58 * C style guide (PEP 7).
60 * 6. A bug in the memory allocation has been fixed: to avoid FREEing memory
61 * that hasn't been MALLOC'ed, private_mem should only be used when k <=
62 * Kmax.
64 * 7. _Py_dg_strtod has been modified so that it doesn't accept strings with
65 * leading whitespace.
67 ***************************************************************/
69 /* Please send bug reports for the original dtoa.c code to David M. Gay (dmg
70 * at acm dot org, with " at " changed at "@" and " dot " changed to ".").
71 * Please report bugs for this modified version using the Python issue tracker
72 * (http://bugs.python.org). */
74 /* On a machine with IEEE extended-precision registers, it is
75 * necessary to specify double-precision (53-bit) rounding precision
76 * before invoking strtod or dtoa. If the machine uses (the equivalent
77 * of) Intel 80x87 arithmetic, the call
78 * _control87(PC_53, MCW_PC);
79 * does this with many compilers. Whether this or another call is
80 * appropriate depends on the compiler; for this to work, it may be
81 * necessary to #include "float.h" or another system-dependent header
82 * file.
85 /* strtod for IEEE-, VAX-, and IBM-arithmetic machines.
87 * This strtod returns a nearest machine number to the input decimal
88 * string (or sets errno to ERANGE). With IEEE arithmetic, ties are
89 * broken by the IEEE round-even rule. Otherwise ties are broken by
90 * biased rounding (add half and chop).
92 * Inspired loosely by William D. Clinger's paper "How to Read Floating
93 * Point Numbers Accurately" [Proc. ACM SIGPLAN '90, pp. 92-101].
95 * Modifications:
97 * 1. We only require IEEE, IBM, or VAX double-precision
98 * arithmetic (not IEEE double-extended).
99 * 2. We get by with floating-point arithmetic in a case that
100 * Clinger missed -- when we're computing d * 10^n
101 * for a small integer d and the integer n is not too
102 * much larger than 22 (the maximum integer k for which
103 * we can represent 10^k exactly), we may be able to
104 * compute (d*10^k) * 10^(e-k) with just one roundoff.
105 * 3. Rather than a bit-at-a-time adjustment of the binary
106 * result in the hard case, we use floating-point
107 * arithmetic to determine the adjustment to within
108 * one bit; only in really hard cases do we need to
109 * compute a second residual.
110 * 4. Because of 3., we don't need a large table of powers of 10
111 * for ten-to-e (just some small tables, e.g. of 10^k
112 * for 0 <= k <= 22).
115 /* Linking of Python's #defines to Gay's #defines starts here. */
117 #include "Python.h"
119 /* if PY_NO_SHORT_FLOAT_REPR is defined, then don't even try to compile
120 the following code */
121 #ifndef PY_NO_SHORT_FLOAT_REPR
123 #include "float.h"
125 #define MALLOC PyMem_Malloc
126 #define FREE PyMem_Free
128 /* This code should also work for ARM mixed-endian format on little-endian
129 machines, where doubles have byte order 45670123 (in increasing address
130 order, 0 being the least significant byte). */
131 #ifdef DOUBLE_IS_LITTLE_ENDIAN_IEEE754
132 # define IEEE_8087
133 #endif
134 #if defined(DOUBLE_IS_BIG_ENDIAN_IEEE754) || \
135 defined(DOUBLE_IS_ARM_MIXED_ENDIAN_IEEE754)
136 # define IEEE_MC68k
137 #endif
138 #if defined(IEEE_8087) + defined(IEEE_MC68k) != 1
139 #error "Exactly one of IEEE_8087 or IEEE_MC68k should be defined."
140 #endif
142 /* The code below assumes that the endianness of integers matches the
143 endianness of the two 32-bit words of a double. Check this. */
144 #if defined(WORDS_BIGENDIAN) && (defined(DOUBLE_IS_LITTLE_ENDIAN_IEEE754) || \
145 defined(DOUBLE_IS_ARM_MIXED_ENDIAN_IEEE754))
146 #error "doubles and ints have incompatible endianness"
147 #endif
149 #if !defined(WORDS_BIGENDIAN) && defined(DOUBLE_IS_BIG_ENDIAN_IEEE754)
150 #error "doubles and ints have incompatible endianness"
151 #endif
154 #if defined(HAVE_UINT32_T) && defined(HAVE_INT32_T)
155 typedef PY_UINT32_T ULong;
156 typedef PY_INT32_T Long;
157 #else
158 #error "Failed to find an exact-width 32-bit integer type"
159 #endif
161 #if defined(HAVE_UINT64_T)
162 #define ULLong PY_UINT64_T
163 #else
164 #undef ULLong
165 #endif
167 #undef DEBUG
168 #ifdef Py_DEBUG
169 #define DEBUG
170 #endif
172 /* End Python #define linking */
174 #ifdef DEBUG
175 #define Bug(x) {fprintf(stderr, "%s\n", x); exit(1);}
176 #endif
178 #ifndef PRIVATE_MEM
179 #define PRIVATE_MEM 2304
180 #endif
181 #define PRIVATE_mem ((PRIVATE_MEM+sizeof(double)-1)/sizeof(double))
182 static double private_mem[PRIVATE_mem], *pmem_next = private_mem;
184 #ifdef __cplusplus
185 extern "C" {
186 #endif
188 typedef union { double d; ULong L[2]; } U;
190 #ifdef IEEE_8087
191 #define word0(x) (x)->L[1]
192 #define word1(x) (x)->L[0]
193 #else
194 #define word0(x) (x)->L[0]
195 #define word1(x) (x)->L[1]
196 #endif
197 #define dval(x) (x)->d
199 #ifndef STRTOD_DIGLIM
200 #define STRTOD_DIGLIM 40
201 #endif
203 #ifdef DIGLIM_DEBUG
204 extern int strtod_diglim;
205 #else
206 #define strtod_diglim STRTOD_DIGLIM
207 #endif
209 /* The following definition of Storeinc is appropriate for MIPS processors.
210 * An alternative that might be better on some machines is
211 * #define Storeinc(a,b,c) (*a++ = b << 16 | c & 0xffff)
213 #if defined(IEEE_8087)
214 #define Storeinc(a,b,c) (((unsigned short *)a)[1] = (unsigned short)b, \
215 ((unsigned short *)a)[0] = (unsigned short)c, a++)
216 #else
217 #define Storeinc(a,b,c) (((unsigned short *)a)[0] = (unsigned short)b, \
218 ((unsigned short *)a)[1] = (unsigned short)c, a++)
219 #endif
221 /* #define P DBL_MANT_DIG */
222 /* Ten_pmax = floor(P*log(2)/log(5)) */
223 /* Bletch = (highest power of 2 < DBL_MAX_10_EXP) / 16 */
224 /* Quick_max = floor((P-1)*log(FLT_RADIX)/log(10) - 1) */
225 /* Int_max = floor(P*log(FLT_RADIX)/log(10) - 1) */
227 #define Exp_shift 20
228 #define Exp_shift1 20
229 #define Exp_msk1 0x100000
230 #define Exp_msk11 0x100000
231 #define Exp_mask 0x7ff00000
232 #define P 53
233 #define Nbits 53
234 #define Bias 1023
235 #define Emax 1023
236 #define Emin (-1022)
237 #define Exp_1 0x3ff00000
238 #define Exp_11 0x3ff00000
239 #define Ebits 11
240 #define Frac_mask 0xfffff
241 #define Frac_mask1 0xfffff
242 #define Ten_pmax 22
243 #define Bletch 0x10
244 #define Bndry_mask 0xfffff
245 #define Bndry_mask1 0xfffff
246 #define LSB 1
247 #define Sign_bit 0x80000000
248 #define Log2P 1
249 #define Tiny0 0
250 #define Tiny1 1
251 #define Quick_max 14
252 #define Int_max 14
254 #ifndef Flt_Rounds
255 #ifdef FLT_ROUNDS
256 #define Flt_Rounds FLT_ROUNDS
257 #else
258 #define Flt_Rounds 1
259 #endif
260 #endif /*Flt_Rounds*/
262 #define Rounding Flt_Rounds
264 #define Big0 (Frac_mask1 | Exp_msk1*(DBL_MAX_EXP+Bias-1))
265 #define Big1 0xffffffff
267 #ifndef NAN_WORD0
268 #define NAN_WORD0 0x7ff80000
269 #endif
271 #ifndef NAN_WORD1
272 #define NAN_WORD1 0
273 #endif
276 /* struct BCinfo is used to pass information from _Py_dg_strtod to bigcomp */
278 typedef struct BCinfo BCinfo;
279 struct
280 BCinfo {
281 int dp0, dp1, dplen, dsign, e0, inexact;
282 int nd, nd0, rounding, scale, uflchk;
285 #define FFFFFFFF 0xffffffffUL
287 #define Kmax 7
289 /* struct Bigint is used to represent arbitrary-precision integers. These
290 integers are stored in sign-magnitude format, with the magnitude stored as
291 an array of base 2**32 digits. Bigints are always normalized: if x is a
292 Bigint then x->wds >= 1, and either x->wds == 1 or x[wds-1] is nonzero.
294 The Bigint fields are as follows:
296 - next is a header used by Balloc and Bfree to keep track of lists
297 of freed Bigints; it's also used for the linked list of
298 powers of 5 of the form 5**2**i used by pow5mult.
299 - k indicates which pool this Bigint was allocated from
300 - maxwds is the maximum number of words space was allocated for
301 (usually maxwds == 2**k)
302 - sign is 1 for negative Bigints, 0 for positive. The sign is unused
303 (ignored on inputs, set to 0 on outputs) in almost all operations
304 involving Bigints: a notable exception is the diff function, which
305 ignores signs on inputs but sets the sign of the output correctly.
306 - wds is the actual number of significant words
307 - x contains the vector of words (digits) for this Bigint, from least
308 significant (x[0]) to most significant (x[wds-1]).
311 struct
312 Bigint {
313 struct Bigint *next;
314 int k, maxwds, sign, wds;
315 ULong x[1];
318 typedef struct Bigint Bigint;
320 /* Memory management: memory is allocated from, and returned to, Kmax+1 pools
321 of memory, where pool k (0 <= k <= Kmax) is for Bigints b with b->maxwds ==
322 1 << k. These pools are maintained as linked lists, with freelist[k]
323 pointing to the head of the list for pool k.
325 On allocation, if there's no free slot in the appropriate pool, MALLOC is
326 called to get more memory. This memory is not returned to the system until
327 Python quits. There's also a private memory pool that's allocated from
328 in preference to using MALLOC.
330 For Bigints with more than (1 << Kmax) digits (which implies at least 1233
331 decimal digits), memory is directly allocated using MALLOC, and freed using
332 FREE.
334 XXX: it would be easy to bypass this memory-management system and
335 translate each call to Balloc into a call to PyMem_Malloc, and each
336 Bfree to PyMem_Free. Investigate whether this has any significant
337 performance on impact. */
339 static Bigint *freelist[Kmax+1];
341 /* Allocate space for a Bigint with up to 1<<k digits */
343 static Bigint *
344 Balloc(int k)
346 int x;
347 Bigint *rv;
348 unsigned int len;
350 if (k <= Kmax && (rv = freelist[k]))
351 freelist[k] = rv->next;
352 else {
353 x = 1 << k;
354 len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1)
355 /sizeof(double);
356 if (k <= Kmax && pmem_next - private_mem + len <= PRIVATE_mem) {
357 rv = (Bigint*)pmem_next;
358 pmem_next += len;
360 else {
361 rv = (Bigint*)MALLOC(len*sizeof(double));
362 if (rv == NULL)
363 return NULL;
365 rv->k = k;
366 rv->maxwds = x;
368 rv->sign = rv->wds = 0;
369 return rv;
372 /* Free a Bigint allocated with Balloc */
374 static void
375 Bfree(Bigint *v)
377 if (v) {
378 if (v->k > Kmax)
379 FREE((void*)v);
380 else {
381 v->next = freelist[v->k];
382 freelist[v->k] = v;
387 #define Bcopy(x,y) memcpy((char *)&x->sign, (char *)&y->sign, \
388 y->wds*sizeof(Long) + 2*sizeof(int))
390 /* Multiply a Bigint b by m and add a. Either modifies b in place and returns
391 a pointer to the modified b, or Bfrees b and returns a pointer to a copy.
392 On failure, return NULL. In this case, b will have been already freed. */
394 static Bigint *
395 multadd(Bigint *b, int m, int a) /* multiply by m and add a */
397 int i, wds;
398 #ifdef ULLong
399 ULong *x;
400 ULLong carry, y;
401 #else
402 ULong carry, *x, y;
403 ULong xi, z;
404 #endif
405 Bigint *b1;
407 wds = b->wds;
408 x = b->x;
409 i = 0;
410 carry = a;
411 do {
412 #ifdef ULLong
413 y = *x * (ULLong)m + carry;
414 carry = y >> 32;
415 *x++ = (ULong)(y & FFFFFFFF);
416 #else
417 xi = *x;
418 y = (xi & 0xffff) * m + carry;
419 z = (xi >> 16) * m + (y >> 16);
420 carry = z >> 16;
421 *x++ = (z << 16) + (y & 0xffff);
422 #endif
424 while(++i < wds);
425 if (carry) {
426 if (wds >= b->maxwds) {
427 b1 = Balloc(b->k+1);
428 if (b1 == NULL){
429 Bfree(b);
430 return NULL;
432 Bcopy(b1, b);
433 Bfree(b);
434 b = b1;
436 b->x[wds++] = (ULong)carry;
437 b->wds = wds;
439 return b;
442 /* convert a string s containing nd decimal digits (possibly containing a
443 decimal separator at position nd0, which is ignored) to a Bigint. This
444 function carries on where the parsing code in _Py_dg_strtod leaves off: on
445 entry, y9 contains the result of converting the first 9 digits. Returns
446 NULL on failure. */
448 static Bigint *
449 s2b(const char *s, int nd0, int nd, ULong y9, int dplen)
451 Bigint *b;
452 int i, k;
453 Long x, y;
455 x = (nd + 8) / 9;
456 for(k = 0, y = 1; x > y; y <<= 1, k++) ;
457 b = Balloc(k);
458 if (b == NULL)
459 return NULL;
460 b->x[0] = y9;
461 b->wds = 1;
463 i = 9;
464 if (9 < nd0) {
465 s += 9;
466 do {
467 b = multadd(b, 10, *s++ - '0');
468 if (b == NULL)
469 return NULL;
470 } while(++i < nd0);
471 s += dplen;
473 else
474 s += dplen + 9;
475 for(; i < nd; i++) {
476 b = multadd(b, 10, *s++ - '0');
477 if (b == NULL)
478 return NULL;
480 return b;
483 /* count leading 0 bits in the 32-bit integer x. */
485 static int
486 hi0bits(ULong x)
488 int k = 0;
490 if (!(x & 0xffff0000)) {
491 k = 16;
492 x <<= 16;
494 if (!(x & 0xff000000)) {
495 k += 8;
496 x <<= 8;
498 if (!(x & 0xf0000000)) {
499 k += 4;
500 x <<= 4;
502 if (!(x & 0xc0000000)) {
503 k += 2;
504 x <<= 2;
506 if (!(x & 0x80000000)) {
507 k++;
508 if (!(x & 0x40000000))
509 return 32;
511 return k;
514 /* count trailing 0 bits in the 32-bit integer y, and shift y right by that
515 number of bits. */
517 static int
518 lo0bits(ULong *y)
520 int k;
521 ULong x = *y;
523 if (x & 7) {
524 if (x & 1)
525 return 0;
526 if (x & 2) {
527 *y = x >> 1;
528 return 1;
530 *y = x >> 2;
531 return 2;
533 k = 0;
534 if (!(x & 0xffff)) {
535 k = 16;
536 x >>= 16;
538 if (!(x & 0xff)) {
539 k += 8;
540 x >>= 8;
542 if (!(x & 0xf)) {
543 k += 4;
544 x >>= 4;
546 if (!(x & 0x3)) {
547 k += 2;
548 x >>= 2;
550 if (!(x & 1)) {
551 k++;
552 x >>= 1;
553 if (!x)
554 return 32;
556 *y = x;
557 return k;
560 /* convert a small nonnegative integer to a Bigint */
562 static Bigint *
563 i2b(int i)
565 Bigint *b;
567 b = Balloc(1);
568 if (b == NULL)
569 return NULL;
570 b->x[0] = i;
571 b->wds = 1;
572 return b;
575 /* multiply two Bigints. Returns a new Bigint, or NULL on failure. Ignores
576 the signs of a and b. */
578 static Bigint *
579 mult(Bigint *a, Bigint *b)
581 Bigint *c;
582 int k, wa, wb, wc;
583 ULong *x, *xa, *xae, *xb, *xbe, *xc, *xc0;
584 ULong y;
585 #ifdef ULLong
586 ULLong carry, z;
587 #else
588 ULong carry, z;
589 ULong z2;
590 #endif
592 if (a->wds < b->wds) {
593 c = a;
594 a = b;
595 b = c;
597 k = a->k;
598 wa = a->wds;
599 wb = b->wds;
600 wc = wa + wb;
601 if (wc > a->maxwds)
602 k++;
603 c = Balloc(k);
604 if (c == NULL)
605 return NULL;
606 for(x = c->x, xa = x + wc; x < xa; x++)
607 *x = 0;
608 xa = a->x;
609 xae = xa + wa;
610 xb = b->x;
611 xbe = xb + wb;
612 xc0 = c->x;
613 #ifdef ULLong
614 for(; xb < xbe; xc0++) {
615 if ((y = *xb++)) {
616 x = xa;
617 xc = xc0;
618 carry = 0;
619 do {
620 z = *x++ * (ULLong)y + *xc + carry;
621 carry = z >> 32;
622 *xc++ = (ULong)(z & FFFFFFFF);
624 while(x < xae);
625 *xc = (ULong)carry;
628 #else
629 for(; xb < xbe; xb++, xc0++) {
630 if (y = *xb & 0xffff) {
631 x = xa;
632 xc = xc0;
633 carry = 0;
634 do {
635 z = (*x & 0xffff) * y + (*xc & 0xffff) + carry;
636 carry = z >> 16;
637 z2 = (*x++ >> 16) * y + (*xc >> 16) + carry;
638 carry = z2 >> 16;
639 Storeinc(xc, z2, z);
641 while(x < xae);
642 *xc = carry;
644 if (y = *xb >> 16) {
645 x = xa;
646 xc = xc0;
647 carry = 0;
648 z2 = *xc;
649 do {
650 z = (*x & 0xffff) * y + (*xc >> 16) + carry;
651 carry = z >> 16;
652 Storeinc(xc, z, z2);
653 z2 = (*x++ >> 16) * y + (*xc & 0xffff) + carry;
654 carry = z2 >> 16;
656 while(x < xae);
657 *xc = z2;
660 #endif
661 for(xc0 = c->x, xc = xc0 + wc; wc > 0 && !*--xc; --wc) ;
662 c->wds = wc;
663 return c;
666 /* p5s is a linked list of powers of 5 of the form 5**(2**i), i >= 2 */
668 static Bigint *p5s;
670 /* multiply the Bigint b by 5**k. Returns a pointer to the result, or NULL on
671 failure; if the returned pointer is distinct from b then the original
672 Bigint b will have been Bfree'd. Ignores the sign of b. */
674 static Bigint *
675 pow5mult(Bigint *b, int k)
677 Bigint *b1, *p5, *p51;
678 int i;
679 static int p05[3] = { 5, 25, 125 };
681 if ((i = k & 3)) {
682 b = multadd(b, p05[i-1], 0);
683 if (b == NULL)
684 return NULL;
687 if (!(k >>= 2))
688 return b;
689 p5 = p5s;
690 if (!p5) {
691 /* first time */
692 p5 = i2b(625);
693 if (p5 == NULL) {
694 Bfree(b);
695 return NULL;
697 p5s = p5;
698 p5->next = 0;
700 for(;;) {
701 if (k & 1) {
702 b1 = mult(b, p5);
703 Bfree(b);
704 b = b1;
705 if (b == NULL)
706 return NULL;
708 if (!(k >>= 1))
709 break;
710 p51 = p5->next;
711 if (!p51) {
712 p51 = mult(p5,p5);
713 if (p51 == NULL) {
714 Bfree(b);
715 return NULL;
717 p51->next = 0;
718 p5->next = p51;
720 p5 = p51;
722 return b;
725 /* shift a Bigint b left by k bits. Return a pointer to the shifted result,
726 or NULL on failure. If the returned pointer is distinct from b then the
727 original b will have been Bfree'd. Ignores the sign of b. */
729 static Bigint *
730 lshift(Bigint *b, int k)
732 int i, k1, n, n1;
733 Bigint *b1;
734 ULong *x, *x1, *xe, z;
736 n = k >> 5;
737 k1 = b->k;
738 n1 = n + b->wds + 1;
739 for(i = b->maxwds; n1 > i; i <<= 1)
740 k1++;
741 b1 = Balloc(k1);
742 if (b1 == NULL) {
743 Bfree(b);
744 return NULL;
746 x1 = b1->x;
747 for(i = 0; i < n; i++)
748 *x1++ = 0;
749 x = b->x;
750 xe = x + b->wds;
751 if (k &= 0x1f) {
752 k1 = 32 - k;
753 z = 0;
754 do {
755 *x1++ = *x << k | z;
756 z = *x++ >> k1;
758 while(x < xe);
759 if ((*x1 = z))
760 ++n1;
762 else do
763 *x1++ = *x++;
764 while(x < xe);
765 b1->wds = n1 - 1;
766 Bfree(b);
767 return b1;
770 /* Do a three-way compare of a and b, returning -1 if a < b, 0 if a == b and
771 1 if a > b. Ignores signs of a and b. */
773 static int
774 cmp(Bigint *a, Bigint *b)
776 ULong *xa, *xa0, *xb, *xb0;
777 int i, j;
779 i = a->wds;
780 j = b->wds;
781 #ifdef DEBUG
782 if (i > 1 && !a->x[i-1])
783 Bug("cmp called with a->x[a->wds-1] == 0");
784 if (j > 1 && !b->x[j-1])
785 Bug("cmp called with b->x[b->wds-1] == 0");
786 #endif
787 if (i -= j)
788 return i;
789 xa0 = a->x;
790 xa = xa0 + j;
791 xb0 = b->x;
792 xb = xb0 + j;
793 for(;;) {
794 if (*--xa != *--xb)
795 return *xa < *xb ? -1 : 1;
796 if (xa <= xa0)
797 break;
799 return 0;
802 /* Take the difference of Bigints a and b, returning a new Bigint. Returns
803 NULL on failure. The signs of a and b are ignored, but the sign of the
804 result is set appropriately. */
806 static Bigint *
807 diff(Bigint *a, Bigint *b)
809 Bigint *c;
810 int i, wa, wb;
811 ULong *xa, *xae, *xb, *xbe, *xc;
812 #ifdef ULLong
813 ULLong borrow, y;
814 #else
815 ULong borrow, y;
816 ULong z;
817 #endif
819 i = cmp(a,b);
820 if (!i) {
821 c = Balloc(0);
822 if (c == NULL)
823 return NULL;
824 c->wds = 1;
825 c->x[0] = 0;
826 return c;
828 if (i < 0) {
829 c = a;
830 a = b;
831 b = c;
832 i = 1;
834 else
835 i = 0;
836 c = Balloc(a->k);
837 if (c == NULL)
838 return NULL;
839 c->sign = i;
840 wa = a->wds;
841 xa = a->x;
842 xae = xa + wa;
843 wb = b->wds;
844 xb = b->x;
845 xbe = xb + wb;
846 xc = c->x;
847 borrow = 0;
848 #ifdef ULLong
849 do {
850 y = (ULLong)*xa++ - *xb++ - borrow;
851 borrow = y >> 32 & (ULong)1;
852 *xc++ = (ULong)(y & FFFFFFFF);
854 while(xb < xbe);
855 while(xa < xae) {
856 y = *xa++ - borrow;
857 borrow = y >> 32 & (ULong)1;
858 *xc++ = (ULong)(y & FFFFFFFF);
860 #else
861 do {
862 y = (*xa & 0xffff) - (*xb & 0xffff) - borrow;
863 borrow = (y & 0x10000) >> 16;
864 z = (*xa++ >> 16) - (*xb++ >> 16) - borrow;
865 borrow = (z & 0x10000) >> 16;
866 Storeinc(xc, z, y);
868 while(xb < xbe);
869 while(xa < xae) {
870 y = (*xa & 0xffff) - borrow;
871 borrow = (y & 0x10000) >> 16;
872 z = (*xa++ >> 16) - borrow;
873 borrow = (z & 0x10000) >> 16;
874 Storeinc(xc, z, y);
876 #endif
877 while(!*--xc)
878 wa--;
879 c->wds = wa;
880 return c;
883 /* Given a positive normal double x, return the difference between x and the next
884 double up. Doesn't give correct results for subnormals. */
886 static double
887 ulp(U *x)
889 Long L;
890 U u;
892 L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1;
893 word0(&u) = L;
894 word1(&u) = 0;
895 return dval(&u);
898 /* Convert a Bigint to a double plus an exponent */
900 static double
901 b2d(Bigint *a, int *e)
903 ULong *xa, *xa0, w, y, z;
904 int k;
905 U d;
907 xa0 = a->x;
908 xa = xa0 + a->wds;
909 y = *--xa;
910 #ifdef DEBUG
911 if (!y) Bug("zero y in b2d");
912 #endif
913 k = hi0bits(y);
914 *e = 32 - k;
915 if (k < Ebits) {
916 word0(&d) = Exp_1 | y >> (Ebits - k);
917 w = xa > xa0 ? *--xa : 0;
918 word1(&d) = y << ((32-Ebits) + k) | w >> (Ebits - k);
919 goto ret_d;
921 z = xa > xa0 ? *--xa : 0;
922 if (k -= Ebits) {
923 word0(&d) = Exp_1 | y << k | z >> (32 - k);
924 y = xa > xa0 ? *--xa : 0;
925 word1(&d) = z << k | y >> (32 - k);
927 else {
928 word0(&d) = Exp_1 | y;
929 word1(&d) = z;
931 ret_d:
932 return dval(&d);
935 /* Convert a double to a Bigint plus an exponent. Return NULL on failure.
937 Given a finite nonzero double d, return an odd Bigint b and exponent *e
938 such that fabs(d) = b * 2**e. On return, *bbits gives the number of
939 significant bits of e; that is, 2**(*bbits-1) <= b < 2**(*bbits).
941 If d is zero, then b == 0, *e == -1010, *bbits = 0.
945 static Bigint *
946 d2b(U *d, int *e, int *bits)
948 Bigint *b;
949 int de, k;
950 ULong *x, y, z;
951 int i;
953 b = Balloc(1);
954 if (b == NULL)
955 return NULL;
956 x = b->x;
958 z = word0(d) & Frac_mask;
959 word0(d) &= 0x7fffffff; /* clear sign bit, which we ignore */
960 if ((de = (int)(word0(d) >> Exp_shift)))
961 z |= Exp_msk1;
962 if ((y = word1(d))) {
963 if ((k = lo0bits(&y))) {
964 x[0] = y | z << (32 - k);
965 z >>= k;
967 else
968 x[0] = y;
970 b->wds = (x[1] = z) ? 2 : 1;
972 else {
973 k = lo0bits(&z);
974 x[0] = z;
976 b->wds = 1;
977 k += 32;
979 if (de) {
980 *e = de - Bias - (P-1) + k;
981 *bits = P - k;
983 else {
984 *e = de - Bias - (P-1) + 1 + k;
985 *bits = 32*i - hi0bits(x[i-1]);
987 return b;
990 /* Compute the ratio of two Bigints, as a double. The result may have an
991 error of up to 2.5 ulps. */
993 static double
994 ratio(Bigint *a, Bigint *b)
996 U da, db;
997 int k, ka, kb;
999 dval(&da) = b2d(a, &ka);
1000 dval(&db) = b2d(b, &kb);
1001 k = ka - kb + 32*(a->wds - b->wds);
1002 if (k > 0)
1003 word0(&da) += k*Exp_msk1;
1004 else {
1005 k = -k;
1006 word0(&db) += k*Exp_msk1;
1008 return dval(&da) / dval(&db);
1011 static const double
1012 tens[] = {
1013 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
1014 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
1015 1e20, 1e21, 1e22
1018 static const double
1019 bigtens[] = { 1e16, 1e32, 1e64, 1e128, 1e256 };
1020 static const double tinytens[] = { 1e-16, 1e-32, 1e-64, 1e-128,
1021 9007199254740992.*9007199254740992.e-256
1022 /* = 2^106 * 1e-256 */
1024 /* The factor of 2^53 in tinytens[4] helps us avoid setting the underflow */
1025 /* flag unnecessarily. It leads to a song and dance at the end of strtod. */
1026 #define Scale_Bit 0x10
1027 #define n_bigtens 5
1029 /* case insensitive string match, for recognising 'inf[inity]' and
1030 'nan' strings. */
1032 static int
1033 match(const char **sp, char *t)
1035 int c, d;
1036 const char *s = *sp;
1038 while((d = *t++)) {
1039 if ((c = *++s) >= 'A' && c <= 'Z')
1040 c += 'a' - 'A';
1041 if (c != d)
1042 return 0;
1044 *sp = s + 1;
1045 return 1;
1048 #define ULbits 32
1049 #define kshift 5
1050 #define kmask 31
1053 static int
1054 dshift(Bigint *b, int p2)
1056 int rv = hi0bits(b->x[b->wds-1]) - 4;
1057 if (p2 > 0)
1058 rv -= p2;
1059 return rv & kmask;
1062 /* special case of Bigint division. The quotient is always in the range 0 <=
1063 quotient < 10, and on entry the divisor S is normalized so that its top 4
1064 bits (28--31) are zero and bit 27 is set. */
1066 static int
1067 quorem(Bigint *b, Bigint *S)
1069 int n;
1070 ULong *bx, *bxe, q, *sx, *sxe;
1071 #ifdef ULLong
1072 ULLong borrow, carry, y, ys;
1073 #else
1074 ULong borrow, carry, y, ys;
1075 ULong si, z, zs;
1076 #endif
1078 n = S->wds;
1079 #ifdef DEBUG
1080 /*debug*/ if (b->wds > n)
1081 /*debug*/ Bug("oversize b in quorem");
1082 #endif
1083 if (b->wds < n)
1084 return 0;
1085 sx = S->x;
1086 sxe = sx + --n;
1087 bx = b->x;
1088 bxe = bx + n;
1089 q = *bxe / (*sxe + 1); /* ensure q <= true quotient */
1090 #ifdef DEBUG
1091 /*debug*/ if (q > 9)
1092 /*debug*/ Bug("oversized quotient in quorem");
1093 #endif
1094 if (q) {
1095 borrow = 0;
1096 carry = 0;
1097 do {
1098 #ifdef ULLong
1099 ys = *sx++ * (ULLong)q + carry;
1100 carry = ys >> 32;
1101 y = *bx - (ys & FFFFFFFF) - borrow;
1102 borrow = y >> 32 & (ULong)1;
1103 *bx++ = (ULong)(y & FFFFFFFF);
1104 #else
1105 si = *sx++;
1106 ys = (si & 0xffff) * q + carry;
1107 zs = (si >> 16) * q + (ys >> 16);
1108 carry = zs >> 16;
1109 y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
1110 borrow = (y & 0x10000) >> 16;
1111 z = (*bx >> 16) - (zs & 0xffff) - borrow;
1112 borrow = (z & 0x10000) >> 16;
1113 Storeinc(bx, z, y);
1114 #endif
1116 while(sx <= sxe);
1117 if (!*bxe) {
1118 bx = b->x;
1119 while(--bxe > bx && !*bxe)
1120 --n;
1121 b->wds = n;
1124 if (cmp(b, S) >= 0) {
1125 q++;
1126 borrow = 0;
1127 carry = 0;
1128 bx = b->x;
1129 sx = S->x;
1130 do {
1131 #ifdef ULLong
1132 ys = *sx++ + carry;
1133 carry = ys >> 32;
1134 y = *bx - (ys & FFFFFFFF) - borrow;
1135 borrow = y >> 32 & (ULong)1;
1136 *bx++ = (ULong)(y & FFFFFFFF);
1137 #else
1138 si = *sx++;
1139 ys = (si & 0xffff) + carry;
1140 zs = (si >> 16) + (ys >> 16);
1141 carry = zs >> 16;
1142 y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
1143 borrow = (y & 0x10000) >> 16;
1144 z = (*bx >> 16) - (zs & 0xffff) - borrow;
1145 borrow = (z & 0x10000) >> 16;
1146 Storeinc(bx, z, y);
1147 #endif
1149 while(sx <= sxe);
1150 bx = b->x;
1151 bxe = bx + n;
1152 if (!*bxe) {
1153 while(--bxe > bx && !*bxe)
1154 --n;
1155 b->wds = n;
1158 return q;
1162 /* return 0 on success, -1 on failure */
1164 static int
1165 bigcomp(U *rv, const char *s0, BCinfo *bc)
1167 Bigint *b, *d;
1168 int b2, bbits, d2, dd, dig, dsign, i, j, nd, nd0, p2, p5, speccase;
1170 dsign = bc->dsign;
1171 nd = bc->nd;
1172 nd0 = bc->nd0;
1173 p5 = nd + bc->e0 - 1;
1174 speccase = 0;
1175 if (rv->d == 0.) { /* special case: value near underflow-to-zero */
1176 /* threshold was rounded to zero */
1177 b = i2b(1);
1178 if (b == NULL)
1179 return -1;
1180 p2 = Emin - P + 1;
1181 bbits = 1;
1182 word0(rv) = (P+2) << Exp_shift;
1183 i = 0;
1185 speccase = 1;
1186 --p2;
1187 dsign = 0;
1188 goto have_i;
1191 else
1193 b = d2b(rv, &p2, &bbits);
1194 if (b == NULL)
1195 return -1;
1197 p2 -= bc->scale;
1198 /* floor(log2(rv)) == bbits - 1 + p2 */
1199 /* Check for denormal case. */
1200 i = P - bbits;
1201 if (i > (j = P - Emin - 1 + p2)) {
1202 i = j;
1205 b = lshift(b, ++i);
1206 if (b == NULL)
1207 return -1;
1208 b->x[0] |= 1;
1210 have_i:
1211 p2 -= p5 + i;
1212 d = i2b(1);
1213 if (d == NULL) {
1214 Bfree(b);
1215 return -1;
1217 /* Arrange for convenient computation of quotients:
1218 * shift left if necessary so divisor has 4 leading 0 bits.
1220 if (p5 > 0) {
1221 d = pow5mult(d, p5);
1222 if (d == NULL) {
1223 Bfree(b);
1224 return -1;
1227 else if (p5 < 0) {
1228 b = pow5mult(b, -p5);
1229 if (b == NULL) {
1230 Bfree(d);
1231 return -1;
1234 if (p2 > 0) {
1235 b2 = p2;
1236 d2 = 0;
1238 else {
1239 b2 = 0;
1240 d2 = -p2;
1242 i = dshift(d, d2);
1243 if ((b2 += i) > 0) {
1244 b = lshift(b, b2);
1245 if (b == NULL) {
1246 Bfree(d);
1247 return -1;
1250 if ((d2 += i) > 0) {
1251 d = lshift(d, d2);
1252 if (d == NULL) {
1253 Bfree(b);
1254 return -1;
1258 /* Now b/d = exactly half-way between the two floating-point values */
1259 /* on either side of the input string. Compute first digit of b/d. */
1261 if (!(dig = quorem(b,d))) {
1262 b = multadd(b, 10, 0); /* very unlikely */
1263 if (b == NULL) {
1264 Bfree(d);
1265 return -1;
1267 dig = quorem(b,d);
1270 /* Compare b/d with s0 */
1272 assert(nd > 0);
1273 dd = 9999; /* silence gcc compiler warning */
1274 for(i = 0; i < nd0; ) {
1275 if ((dd = s0[i++] - '0' - dig))
1276 goto ret;
1277 if (!b->x[0] && b->wds == 1) {
1278 if (i < nd)
1279 dd = 1;
1280 goto ret;
1282 b = multadd(b, 10, 0);
1283 if (b == NULL) {
1284 Bfree(d);
1285 return -1;
1287 dig = quorem(b,d);
1289 for(j = bc->dp1; i++ < nd;) {
1290 if ((dd = s0[j++] - '0' - dig))
1291 goto ret;
1292 if (!b->x[0] && b->wds == 1) {
1293 if (i < nd)
1294 dd = 1;
1295 goto ret;
1297 b = multadd(b, 10, 0);
1298 if (b == NULL) {
1299 Bfree(d);
1300 return -1;
1302 dig = quorem(b,d);
1304 if (b->x[0] || b->wds > 1)
1305 dd = -1;
1306 ret:
1307 Bfree(b);
1308 Bfree(d);
1309 if (speccase) {
1310 if (dd <= 0)
1311 rv->d = 0.;
1313 else if (dd < 0) {
1314 if (!dsign) /* does not happen for round-near */
1315 retlow1:
1316 dval(rv) -= ulp(rv);
1318 else if (dd > 0) {
1319 if (dsign) {
1320 rethi1:
1321 dval(rv) += ulp(rv);
1324 else {
1325 /* Exact half-way case: apply round-even rule. */
1326 if (word1(rv) & 1) {
1327 if (dsign)
1328 goto rethi1;
1329 goto retlow1;
1333 return 0;
1336 double
1337 _Py_dg_strtod(const char *s00, char **se)
1339 int bb2, bb5, bbe, bd2, bd5, bbbits, bs2, c, e, e1, error;
1340 int esign, i, j, k, nd, nd0, nf, nz, nz0, sign;
1341 const char *s, *s0, *s1;
1342 double aadj, aadj1;
1343 Long L;
1344 U aadj2, adj, rv, rv0;
1345 ULong y, z;
1346 BCinfo bc;
1347 Bigint *bb, *bb1, *bd, *bd0, *bs, *delta;
1349 sign = nz0 = nz = bc.dplen = bc.uflchk = 0;
1350 dval(&rv) = 0.;
1351 for(s = s00;;s++) switch(*s) {
1352 case '-':
1353 sign = 1;
1354 /* no break */
1355 case '+':
1356 if (*++s)
1357 goto break2;
1358 /* no break */
1359 case 0:
1360 goto ret0;
1361 /* modify original dtoa.c so that it doesn't accept leading whitespace
1362 case '\t':
1363 case '\n':
1364 case '\v':
1365 case '\f':
1366 case '\r':
1367 case ' ':
1368 continue;
1370 default:
1371 goto break2;
1373 break2:
1374 if (*s == '0') {
1375 nz0 = 1;
1376 while(*++s == '0') ;
1377 if (!*s)
1378 goto ret;
1380 s0 = s;
1381 y = z = 0;
1382 for(nd = nf = 0; (c = *s) >= '0' && c <= '9'; nd++, s++)
1383 if (nd < 9)
1384 y = 10*y + c - '0';
1385 else if (nd < 16)
1386 z = 10*z + c - '0';
1387 nd0 = nd;
1388 bc.dp0 = bc.dp1 = s - s0;
1389 if (c == '.') {
1390 c = *++s;
1391 bc.dp1 = s - s0;
1392 bc.dplen = bc.dp1 - bc.dp0;
1393 if (!nd) {
1394 for(; c == '0'; c = *++s)
1395 nz++;
1396 if (c > '0' && c <= '9') {
1397 s0 = s;
1398 nf += nz;
1399 nz = 0;
1400 goto have_dig;
1402 goto dig_done;
1404 for(; c >= '0' && c <= '9'; c = *++s) {
1405 have_dig:
1406 nz++;
1407 if (c -= '0') {
1408 nf += nz;
1409 for(i = 1; i < nz; i++)
1410 if (nd++ < 9)
1411 y *= 10;
1412 else if (nd <= DBL_DIG + 1)
1413 z *= 10;
1414 if (nd++ < 9)
1415 y = 10*y + c;
1416 else if (nd <= DBL_DIG + 1)
1417 z = 10*z + c;
1418 nz = 0;
1422 dig_done:
1423 e = 0;
1424 if (c == 'e' || c == 'E') {
1425 if (!nd && !nz && !nz0) {
1426 goto ret0;
1428 s00 = s;
1429 esign = 0;
1430 switch(c = *++s) {
1431 case '-':
1432 esign = 1;
1433 case '+':
1434 c = *++s;
1436 if (c >= '0' && c <= '9') {
1437 while(c == '0')
1438 c = *++s;
1439 if (c > '0' && c <= '9') {
1440 L = c - '0';
1441 s1 = s;
1442 while((c = *++s) >= '0' && c <= '9')
1443 L = 10*L + c - '0';
1444 if (s - s1 > 8 || L > 19999)
1445 /* Avoid confusion from exponents
1446 * so large that e might overflow.
1448 e = 19999; /* safe for 16 bit ints */
1449 else
1450 e = (int)L;
1451 if (esign)
1452 e = -e;
1454 else
1455 e = 0;
1457 else
1458 s = s00;
1460 if (!nd) {
1461 if (!nz && !nz0) {
1462 /* Check for Nan and Infinity */
1463 if (!bc.dplen)
1464 switch(c) {
1465 case 'i':
1466 case 'I':
1467 if (match(&s,"nf")) {
1468 --s;
1469 if (!match(&s,"inity"))
1470 ++s;
1471 word0(&rv) = 0x7ff00000;
1472 word1(&rv) = 0;
1473 goto ret;
1475 break;
1476 case 'n':
1477 case 'N':
1478 if (match(&s, "an")) {
1479 word0(&rv) = NAN_WORD0;
1480 word1(&rv) = NAN_WORD1;
1481 goto ret;
1484 ret0:
1485 s = s00;
1486 sign = 0;
1488 goto ret;
1490 bc.e0 = e1 = e -= nf;
1492 /* Now we have nd0 digits, starting at s0, followed by a
1493 * decimal point, followed by nd-nd0 digits. The number we're
1494 * after is the integer represented by those digits times
1495 * 10**e */
1497 if (!nd0)
1498 nd0 = nd;
1499 k = nd < DBL_DIG + 1 ? nd : DBL_DIG + 1;
1500 dval(&rv) = y;
1501 if (k > 9) {
1502 dval(&rv) = tens[k - 9] * dval(&rv) + z;
1504 bd0 = 0;
1505 if (nd <= DBL_DIG
1506 && Flt_Rounds == 1
1508 if (!e)
1509 goto ret;
1510 if (e > 0) {
1511 if (e <= Ten_pmax) {
1512 dval(&rv) *= tens[e];
1513 goto ret;
1515 i = DBL_DIG - nd;
1516 if (e <= Ten_pmax + i) {
1517 /* A fancier test would sometimes let us do
1518 * this for larger i values.
1520 e -= i;
1521 dval(&rv) *= tens[i];
1522 dval(&rv) *= tens[e];
1523 goto ret;
1526 else if (e >= -Ten_pmax) {
1527 dval(&rv) /= tens[-e];
1528 goto ret;
1531 e1 += nd - k;
1533 bc.scale = 0;
1535 /* Get starting approximation = rv * 10**e1 */
1537 if (e1 > 0) {
1538 if ((i = e1 & 15))
1539 dval(&rv) *= tens[i];
1540 if (e1 &= ~15) {
1541 if (e1 > DBL_MAX_10_EXP) {
1542 ovfl:
1543 errno = ERANGE;
1544 /* Can't trust HUGE_VAL */
1545 word0(&rv) = Exp_mask;
1546 word1(&rv) = 0;
1547 goto ret;
1549 e1 >>= 4;
1550 for(j = 0; e1 > 1; j++, e1 >>= 1)
1551 if (e1 & 1)
1552 dval(&rv) *= bigtens[j];
1553 /* The last multiplication could overflow. */
1554 word0(&rv) -= P*Exp_msk1;
1555 dval(&rv) *= bigtens[j];
1556 if ((z = word0(&rv) & Exp_mask)
1557 > Exp_msk1*(DBL_MAX_EXP+Bias-P))
1558 goto ovfl;
1559 if (z > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) {
1560 /* set to largest number */
1561 /* (Can't trust DBL_MAX) */
1562 word0(&rv) = Big0;
1563 word1(&rv) = Big1;
1565 else
1566 word0(&rv) += P*Exp_msk1;
1569 else if (e1 < 0) {
1570 e1 = -e1;
1571 if ((i = e1 & 15))
1572 dval(&rv) /= tens[i];
1573 if (e1 >>= 4) {
1574 if (e1 >= 1 << n_bigtens)
1575 goto undfl;
1576 if (e1 & Scale_Bit)
1577 bc.scale = 2*P;
1578 for(j = 0; e1 > 0; j++, e1 >>= 1)
1579 if (e1 & 1)
1580 dval(&rv) *= tinytens[j];
1581 if (bc.scale && (j = 2*P + 1 - ((word0(&rv) & Exp_mask)
1582 >> Exp_shift)) > 0) {
1583 /* scaled rv is denormal; clear j low bits */
1584 if (j >= 32) {
1585 word1(&rv) = 0;
1586 if (j >= 53)
1587 word0(&rv) = (P+2)*Exp_msk1;
1588 else
1589 word0(&rv) &= 0xffffffff << (j-32);
1591 else
1592 word1(&rv) &= 0xffffffff << j;
1594 if (!dval(&rv)) {
1595 undfl:
1596 dval(&rv) = 0.;
1597 errno = ERANGE;
1598 goto ret;
1603 /* Now the hard part -- adjusting rv to the correct value.*/
1605 /* Put digits into bd: true value = bd * 10^e */
1607 bc.nd = nd;
1608 bc.nd0 = nd0; /* Only needed if nd > strtod_diglim, but done here */
1609 /* to silence an erroneous warning about bc.nd0 */
1610 /* possibly not being initialized. */
1611 if (nd > strtod_diglim) {
1612 /* ASSERT(strtod_diglim >= 18); 18 == one more than the */
1613 /* minimum number of decimal digits to distinguish double values */
1614 /* in IEEE arithmetic. */
1615 i = j = 18;
1616 if (i > nd0)
1617 j += bc.dplen;
1618 for(;;) {
1619 if (--j <= bc.dp1 && j >= bc.dp0)
1620 j = bc.dp0 - 1;
1621 if (s0[j] != '0')
1622 break;
1623 --i;
1625 e += nd - i;
1626 nd = i;
1627 if (nd0 > nd)
1628 nd0 = nd;
1629 if (nd < 9) { /* must recompute y */
1630 y = 0;
1631 for(i = 0; i < nd0; ++i)
1632 y = 10*y + s0[i] - '0';
1633 for(j = bc.dp1; i < nd; ++i)
1634 y = 10*y + s0[j++] - '0';
1637 bd0 = s2b(s0, nd0, nd, y, bc.dplen);
1638 if (bd0 == NULL)
1639 goto failed_malloc;
1641 for(;;) {
1642 bd = Balloc(bd0->k);
1643 if (bd == NULL) {
1644 Bfree(bd0);
1645 goto failed_malloc;
1647 Bcopy(bd, bd0);
1648 bb = d2b(&rv, &bbe, &bbbits); /* rv = bb * 2^bbe */
1649 if (bb == NULL) {
1650 Bfree(bd);
1651 Bfree(bd0);
1652 goto failed_malloc;
1654 bs = i2b(1);
1655 if (bs == NULL) {
1656 Bfree(bb);
1657 Bfree(bd);
1658 Bfree(bd0);
1659 goto failed_malloc;
1662 if (e >= 0) {
1663 bb2 = bb5 = 0;
1664 bd2 = bd5 = e;
1666 else {
1667 bb2 = bb5 = -e;
1668 bd2 = bd5 = 0;
1670 if (bbe >= 0)
1671 bb2 += bbe;
1672 else
1673 bd2 -= bbe;
1674 bs2 = bb2;
1675 j = bbe - bc.scale;
1676 i = j + bbbits - 1; /* logb(rv) */
1677 if (i < Emin) /* denormal */
1678 j += P - Emin;
1679 else
1680 j = P + 1 - bbbits;
1681 bb2 += j;
1682 bd2 += j;
1683 bd2 += bc.scale;
1684 i = bb2 < bd2 ? bb2 : bd2;
1685 if (i > bs2)
1686 i = bs2;
1687 if (i > 0) {
1688 bb2 -= i;
1689 bd2 -= i;
1690 bs2 -= i;
1692 if (bb5 > 0) {
1693 bs = pow5mult(bs, bb5);
1694 if (bs == NULL) {
1695 Bfree(bb);
1696 Bfree(bd);
1697 Bfree(bd0);
1698 goto failed_malloc;
1700 bb1 = mult(bs, bb);
1701 Bfree(bb);
1702 bb = bb1;
1703 if (bb == NULL) {
1704 Bfree(bs);
1705 Bfree(bd);
1706 Bfree(bd0);
1707 goto failed_malloc;
1710 if (bb2 > 0) {
1711 bb = lshift(bb, bb2);
1712 if (bb == NULL) {
1713 Bfree(bs);
1714 Bfree(bd);
1715 Bfree(bd0);
1716 goto failed_malloc;
1719 if (bd5 > 0) {
1720 bd = pow5mult(bd, bd5);
1721 if (bd == NULL) {
1722 Bfree(bb);
1723 Bfree(bs);
1724 Bfree(bd0);
1725 goto failed_malloc;
1728 if (bd2 > 0) {
1729 bd = lshift(bd, bd2);
1730 if (bd == NULL) {
1731 Bfree(bb);
1732 Bfree(bs);
1733 Bfree(bd0);
1734 goto failed_malloc;
1737 if (bs2 > 0) {
1738 bs = lshift(bs, bs2);
1739 if (bs == NULL) {
1740 Bfree(bb);
1741 Bfree(bd);
1742 Bfree(bd0);
1743 goto failed_malloc;
1746 delta = diff(bb, bd);
1747 if (delta == NULL) {
1748 Bfree(bb);
1749 Bfree(bs);
1750 Bfree(bd);
1751 Bfree(bd0);
1752 goto failed_malloc;
1754 bc.dsign = delta->sign;
1755 delta->sign = 0;
1756 i = cmp(delta, bs);
1757 if (bc.nd > nd && i <= 0) {
1758 if (bc.dsign)
1759 break; /* Must use bigcomp(). */
1761 bc.nd = nd;
1762 i = -1; /* Discarded digits make delta smaller. */
1766 if (i < 0) {
1767 /* Error is less than half an ulp -- check for
1768 * special case of mantissa a power of two.
1770 if (bc.dsign || word1(&rv) || word0(&rv) & Bndry_mask
1771 || (word0(&rv) & Exp_mask) <= (2*P+1)*Exp_msk1
1773 break;
1775 if (!delta->x[0] && delta->wds <= 1) {
1776 /* exact result */
1777 break;
1779 delta = lshift(delta,Log2P);
1780 if (delta == NULL) {
1781 Bfree(bb);
1782 Bfree(bs);
1783 Bfree(bd);
1784 Bfree(bd0);
1785 goto failed_malloc;
1787 if (cmp(delta, bs) > 0)
1788 goto drop_down;
1789 break;
1791 if (i == 0) {
1792 /* exactly half-way between */
1793 if (bc.dsign) {
1794 if ((word0(&rv) & Bndry_mask1) == Bndry_mask1
1795 && word1(&rv) == (
1796 (bc.scale &&
1797 (y = word0(&rv) & Exp_mask) <= 2*P*Exp_msk1) ?
1798 (0xffffffff & (0xffffffff << (2*P+1-(y>>Exp_shift)))) :
1799 0xffffffff)) {
1800 /*boundary case -- increment exponent*/
1801 word0(&rv) = (word0(&rv) & Exp_mask)
1802 + Exp_msk1
1804 word1(&rv) = 0;
1805 bc.dsign = 0;
1806 break;
1809 else if (!(word0(&rv) & Bndry_mask) && !word1(&rv)) {
1810 drop_down:
1811 /* boundary case -- decrement exponent */
1812 if (bc.scale) {
1813 L = word0(&rv) & Exp_mask;
1814 if (L <= (2*P+1)*Exp_msk1) {
1815 if (L > (P+2)*Exp_msk1)
1816 /* round even ==> */
1817 /* accept rv */
1818 break;
1819 /* rv = smallest denormal */
1820 if (bc.nd >nd) {
1821 bc.uflchk = 1;
1822 break;
1824 goto undfl;
1827 L = (word0(&rv) & Exp_mask) - Exp_msk1;
1828 word0(&rv) = L | Bndry_mask1;
1829 word1(&rv) = 0xffffffff;
1830 break;
1832 if (!(word1(&rv) & LSB))
1833 break;
1834 if (bc.dsign)
1835 dval(&rv) += ulp(&rv);
1836 else {
1837 dval(&rv) -= ulp(&rv);
1838 if (!dval(&rv)) {
1839 if (bc.nd >nd) {
1840 bc.uflchk = 1;
1841 break;
1843 goto undfl;
1846 bc.dsign = 1 - bc.dsign;
1847 break;
1849 if ((aadj = ratio(delta, bs)) <= 2.) {
1850 if (bc.dsign)
1851 aadj = aadj1 = 1.;
1852 else if (word1(&rv) || word0(&rv) & Bndry_mask) {
1853 if (word1(&rv) == Tiny1 && !word0(&rv)) {
1854 if (bc.nd >nd) {
1855 bc.uflchk = 1;
1856 break;
1858 goto undfl;
1860 aadj = 1.;
1861 aadj1 = -1.;
1863 else {
1864 /* special case -- power of FLT_RADIX to be */
1865 /* rounded down... */
1867 if (aadj < 2./FLT_RADIX)
1868 aadj = 1./FLT_RADIX;
1869 else
1870 aadj *= 0.5;
1871 aadj1 = -aadj;
1874 else {
1875 aadj *= 0.5;
1876 aadj1 = bc.dsign ? aadj : -aadj;
1877 if (Flt_Rounds == 0)
1878 aadj1 += 0.5;
1880 y = word0(&rv) & Exp_mask;
1882 /* Check for overflow */
1884 if (y == Exp_msk1*(DBL_MAX_EXP+Bias-1)) {
1885 dval(&rv0) = dval(&rv);
1886 word0(&rv) -= P*Exp_msk1;
1887 adj.d = aadj1 * ulp(&rv);
1888 dval(&rv) += adj.d;
1889 if ((word0(&rv) & Exp_mask) >=
1890 Exp_msk1*(DBL_MAX_EXP+Bias-P)) {
1891 if (word0(&rv0) == Big0 && word1(&rv0) == Big1)
1892 goto ovfl;
1893 word0(&rv) = Big0;
1894 word1(&rv) = Big1;
1895 goto cont;
1897 else
1898 word0(&rv) += P*Exp_msk1;
1900 else {
1901 if (bc.scale && y <= 2*P*Exp_msk1) {
1902 if (aadj <= 0x7fffffff) {
1903 if ((z = (ULong)aadj) <= 0)
1904 z = 1;
1905 aadj = z;
1906 aadj1 = bc.dsign ? aadj : -aadj;
1908 dval(&aadj2) = aadj1;
1909 word0(&aadj2) += (2*P+1)*Exp_msk1 - y;
1910 aadj1 = dval(&aadj2);
1912 adj.d = aadj1 * ulp(&rv);
1913 dval(&rv) += adj.d;
1915 z = word0(&rv) & Exp_mask;
1916 if (bc.nd == nd) {
1917 if (!bc.scale)
1918 if (y == z) {
1919 /* Can we stop now? */
1920 L = (Long)aadj;
1921 aadj -= L;
1922 /* The tolerances below are conservative. */
1923 if (bc.dsign || word1(&rv) || word0(&rv) & Bndry_mask) {
1924 if (aadj < .4999999 || aadj > .5000001)
1925 break;
1927 else if (aadj < .4999999/FLT_RADIX)
1928 break;
1931 cont:
1932 Bfree(bb);
1933 Bfree(bd);
1934 Bfree(bs);
1935 Bfree(delta);
1937 Bfree(bb);
1938 Bfree(bd);
1939 Bfree(bs);
1940 Bfree(bd0);
1941 Bfree(delta);
1942 if (bc.nd > nd) {
1943 error = bigcomp(&rv, s0, &bc);
1944 if (error)
1945 goto failed_malloc;
1948 if (bc.scale) {
1949 word0(&rv0) = Exp_1 - 2*P*Exp_msk1;
1950 word1(&rv0) = 0;
1951 dval(&rv) *= dval(&rv0);
1952 /* try to avoid the bug of testing an 8087 register value */
1953 if (!(word0(&rv) & Exp_mask))
1954 errno = ERANGE;
1956 ret:
1957 if (se)
1958 *se = (char *)s;
1959 return sign ? -dval(&rv) : dval(&rv);
1961 failed_malloc:
1962 if (se)
1963 *se = (char *)s00;
1964 errno = ENOMEM;
1965 return -1.0;
1968 static char *
1969 rv_alloc(int i)
1971 int j, k, *r;
1973 j = sizeof(ULong);
1974 for(k = 0;
1975 sizeof(Bigint) - sizeof(ULong) - sizeof(int) + j <= (unsigned)i;
1976 j <<= 1)
1977 k++;
1978 r = (int*)Balloc(k);
1979 if (r == NULL)
1980 return NULL;
1981 *r = k;
1982 return (char *)(r+1);
1985 static char *
1986 nrv_alloc(char *s, char **rve, int n)
1988 char *rv, *t;
1990 rv = rv_alloc(n);
1991 if (rv == NULL)
1992 return NULL;
1993 t = rv;
1994 while((*t = *s++)) t++;
1995 if (rve)
1996 *rve = t;
1997 return rv;
2000 /* freedtoa(s) must be used to free values s returned by dtoa
2001 * when MULTIPLE_THREADS is #defined. It should be used in all cases,
2002 * but for consistency with earlier versions of dtoa, it is optional
2003 * when MULTIPLE_THREADS is not defined.
2006 void
2007 _Py_dg_freedtoa(char *s)
2009 Bigint *b = (Bigint *)((int *)s - 1);
2010 b->maxwds = 1 << (b->k = *(int*)b);
2011 Bfree(b);
2014 /* dtoa for IEEE arithmetic (dmg): convert double to ASCII string.
2016 * Inspired by "How to Print Floating-Point Numbers Accurately" by
2017 * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 112-126].
2019 * Modifications:
2020 * 1. Rather than iterating, we use a simple numeric overestimate
2021 * to determine k = floor(log10(d)). We scale relevant
2022 * quantities using O(log2(k)) rather than O(k) multiplications.
2023 * 2. For some modes > 2 (corresponding to ecvt and fcvt), we don't
2024 * try to generate digits strictly left to right. Instead, we
2025 * compute with fewer bits and propagate the carry if necessary
2026 * when rounding the final digit up. This is often faster.
2027 * 3. Under the assumption that input will be rounded nearest,
2028 * mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22.
2029 * That is, we allow equality in stopping tests when the
2030 * round-nearest rule will give the same floating-point value
2031 * as would satisfaction of the stopping test with strict
2032 * inequality.
2033 * 4. We remove common factors of powers of 2 from relevant
2034 * quantities.
2035 * 5. When converting floating-point integers less than 1e16,
2036 * we use floating-point arithmetic rather than resorting
2037 * to multiple-precision integers.
2038 * 6. When asked to produce fewer than 15 digits, we first try
2039 * to get by with floating-point arithmetic; we resort to
2040 * multiple-precision integer arithmetic only if we cannot
2041 * guarantee that the floating-point calculation has given
2042 * the correctly rounded result. For k requested digits and
2043 * "uniformly" distributed input, the probability is
2044 * something like 10^(k-15) that we must resort to the Long
2045 * calculation.
2048 /* Additional notes (METD): (1) returns NULL on failure. (2) to avoid memory
2049 leakage, a successful call to _Py_dg_dtoa should always be matched by a
2050 call to _Py_dg_freedtoa. */
2052 char *
2053 _Py_dg_dtoa(double dd, int mode, int ndigits,
2054 int *decpt, int *sign, char **rve)
2056 /* Arguments ndigits, decpt, sign are similar to those
2057 of ecvt and fcvt; trailing zeros are suppressed from
2058 the returned string. If not null, *rve is set to point
2059 to the end of the return value. If d is +-Infinity or NaN,
2060 then *decpt is set to 9999.
2062 mode:
2063 0 ==> shortest string that yields d when read in
2064 and rounded to nearest.
2065 1 ==> like 0, but with Steele & White stopping rule;
2066 e.g. with IEEE P754 arithmetic , mode 0 gives
2067 1e23 whereas mode 1 gives 9.999999999999999e22.
2068 2 ==> max(1,ndigits) significant digits. This gives a
2069 return value similar to that of ecvt, except
2070 that trailing zeros are suppressed.
2071 3 ==> through ndigits past the decimal point. This
2072 gives a return value similar to that from fcvt,
2073 except that trailing zeros are suppressed, and
2074 ndigits can be negative.
2075 4,5 ==> similar to 2 and 3, respectively, but (in
2076 round-nearest mode) with the tests of mode 0 to
2077 possibly return a shorter string that rounds to d.
2078 With IEEE arithmetic and compilation with
2079 -DHonor_FLT_ROUNDS, modes 4 and 5 behave the same
2080 as modes 2 and 3 when FLT_ROUNDS != 1.
2081 6-9 ==> Debugging modes similar to mode - 4: don't try
2082 fast floating-point estimate (if applicable).
2084 Values of mode other than 0-9 are treated as mode 0.
2086 Sufficient space is allocated to the return value
2087 to hold the suppressed trailing zeros.
2090 int bbits, b2, b5, be, dig, i, ieps, ilim, ilim0, ilim1,
2091 j, j1, k, k0, k_check, leftright, m2, m5, s2, s5,
2092 spec_case, try_quick;
2093 Long L;
2094 int denorm;
2095 ULong x;
2096 Bigint *b, *b1, *delta, *mlo, *mhi, *S;
2097 U d2, eps, u;
2098 double ds;
2099 char *s, *s0;
2101 /* set pointers to NULL, to silence gcc compiler warnings and make
2102 cleanup easier on error */
2103 mlo = mhi = b = S = 0;
2104 s0 = 0;
2106 u.d = dd;
2107 if (word0(&u) & Sign_bit) {
2108 /* set sign for everything, including 0's and NaNs */
2109 *sign = 1;
2110 word0(&u) &= ~Sign_bit; /* clear sign bit */
2112 else
2113 *sign = 0;
2115 /* quick return for Infinities, NaNs and zeros */
2116 if ((word0(&u) & Exp_mask) == Exp_mask)
2118 /* Infinity or NaN */
2119 *decpt = 9999;
2120 if (!word1(&u) && !(word0(&u) & 0xfffff))
2121 return nrv_alloc("Infinity", rve, 8);
2122 return nrv_alloc("NaN", rve, 3);
2124 if (!dval(&u)) {
2125 *decpt = 1;
2126 return nrv_alloc("0", rve, 1);
2129 /* compute k = floor(log10(d)). The computation may leave k
2130 one too large, but should never leave k too small. */
2131 b = d2b(&u, &be, &bbits);
2132 if (b == NULL)
2133 goto failed_malloc;
2134 if ((i = (int)(word0(&u) >> Exp_shift1 & (Exp_mask>>Exp_shift1)))) {
2135 dval(&d2) = dval(&u);
2136 word0(&d2) &= Frac_mask1;
2137 word0(&d2) |= Exp_11;
2139 /* log(x) ~=~ log(1.5) + (x-1.5)/1.5
2140 * log10(x) = log(x) / log(10)
2141 * ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10))
2142 * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2)
2144 * This suggests computing an approximation k to log10(d) by
2146 * k = (i - Bias)*0.301029995663981
2147 * + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 );
2149 * We want k to be too large rather than too small.
2150 * The error in the first-order Taylor series approximation
2151 * is in our favor, so we just round up the constant enough
2152 * to compensate for any error in the multiplication of
2153 * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077,
2154 * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14,
2155 * adding 1e-13 to the constant term more than suffices.
2156 * Hence we adjust the constant term to 0.1760912590558.
2157 * (We could get a more accurate k by invoking log10,
2158 * but this is probably not worthwhile.)
2161 i -= Bias;
2162 denorm = 0;
2164 else {
2165 /* d is denormalized */
2167 i = bbits + be + (Bias + (P-1) - 1);
2168 x = i > 32 ? word0(&u) << (64 - i) | word1(&u) >> (i - 32)
2169 : word1(&u) << (32 - i);
2170 dval(&d2) = x;
2171 word0(&d2) -= 31*Exp_msk1; /* adjust exponent */
2172 i -= (Bias + (P-1) - 1) + 1;
2173 denorm = 1;
2175 ds = (dval(&d2)-1.5)*0.289529654602168 + 0.1760912590558 +
2176 i*0.301029995663981;
2177 k = (int)ds;
2178 if (ds < 0. && ds != k)
2179 k--; /* want k = floor(ds) */
2180 k_check = 1;
2181 if (k >= 0 && k <= Ten_pmax) {
2182 if (dval(&u) < tens[k])
2183 k--;
2184 k_check = 0;
2186 j = bbits - i - 1;
2187 if (j >= 0) {
2188 b2 = 0;
2189 s2 = j;
2191 else {
2192 b2 = -j;
2193 s2 = 0;
2195 if (k >= 0) {
2196 b5 = 0;
2197 s5 = k;
2198 s2 += k;
2200 else {
2201 b2 -= k;
2202 b5 = -k;
2203 s5 = 0;
2205 if (mode < 0 || mode > 9)
2206 mode = 0;
2208 try_quick = 1;
2210 if (mode > 5) {
2211 mode -= 4;
2212 try_quick = 0;
2214 leftright = 1;
2215 ilim = ilim1 = -1; /* Values for cases 0 and 1; done here to */
2216 /* silence erroneous "gcc -Wall" warning. */
2217 switch(mode) {
2218 case 0:
2219 case 1:
2220 i = 18;
2221 ndigits = 0;
2222 break;
2223 case 2:
2224 leftright = 0;
2225 /* no break */
2226 case 4:
2227 if (ndigits <= 0)
2228 ndigits = 1;
2229 ilim = ilim1 = i = ndigits;
2230 break;
2231 case 3:
2232 leftright = 0;
2233 /* no break */
2234 case 5:
2235 i = ndigits + k + 1;
2236 ilim = i;
2237 ilim1 = i - 1;
2238 if (i <= 0)
2239 i = 1;
2241 s0 = rv_alloc(i);
2242 if (s0 == NULL)
2243 goto failed_malloc;
2244 s = s0;
2247 if (ilim >= 0 && ilim <= Quick_max && try_quick) {
2249 /* Try to get by with floating-point arithmetic. */
2251 i = 0;
2252 dval(&d2) = dval(&u);
2253 k0 = k;
2254 ilim0 = ilim;
2255 ieps = 2; /* conservative */
2256 if (k > 0) {
2257 ds = tens[k&0xf];
2258 j = k >> 4;
2259 if (j & Bletch) {
2260 /* prevent overflows */
2261 j &= Bletch - 1;
2262 dval(&u) /= bigtens[n_bigtens-1];
2263 ieps++;
2265 for(; j; j >>= 1, i++)
2266 if (j & 1) {
2267 ieps++;
2268 ds *= bigtens[i];
2270 dval(&u) /= ds;
2272 else if ((j1 = -k)) {
2273 dval(&u) *= tens[j1 & 0xf];
2274 for(j = j1 >> 4; j; j >>= 1, i++)
2275 if (j & 1) {
2276 ieps++;
2277 dval(&u) *= bigtens[i];
2280 if (k_check && dval(&u) < 1. && ilim > 0) {
2281 if (ilim1 <= 0)
2282 goto fast_failed;
2283 ilim = ilim1;
2284 k--;
2285 dval(&u) *= 10.;
2286 ieps++;
2288 dval(&eps) = ieps*dval(&u) + 7.;
2289 word0(&eps) -= (P-1)*Exp_msk1;
2290 if (ilim == 0) {
2291 S = mhi = 0;
2292 dval(&u) -= 5.;
2293 if (dval(&u) > dval(&eps))
2294 goto one_digit;
2295 if (dval(&u) < -dval(&eps))
2296 goto no_digits;
2297 goto fast_failed;
2299 if (leftright) {
2300 /* Use Steele & White method of only
2301 * generating digits needed.
2303 dval(&eps) = 0.5/tens[ilim-1] - dval(&eps);
2304 for(i = 0;;) {
2305 L = (Long)dval(&u);
2306 dval(&u) -= L;
2307 *s++ = '0' + (int)L;
2308 if (dval(&u) < dval(&eps))
2309 goto ret1;
2310 if (1. - dval(&u) < dval(&eps))
2311 goto bump_up;
2312 if (++i >= ilim)
2313 break;
2314 dval(&eps) *= 10.;
2315 dval(&u) *= 10.;
2318 else {
2319 /* Generate ilim digits, then fix them up. */
2320 dval(&eps) *= tens[ilim-1];
2321 for(i = 1;; i++, dval(&u) *= 10.) {
2322 L = (Long)(dval(&u));
2323 if (!(dval(&u) -= L))
2324 ilim = i;
2325 *s++ = '0' + (int)L;
2326 if (i == ilim) {
2327 if (dval(&u) > 0.5 + dval(&eps))
2328 goto bump_up;
2329 else if (dval(&u) < 0.5 - dval(&eps)) {
2330 while(*--s == '0');
2331 s++;
2332 goto ret1;
2334 break;
2338 fast_failed:
2339 s = s0;
2340 dval(&u) = dval(&d2);
2341 k = k0;
2342 ilim = ilim0;
2345 /* Do we have a "small" integer? */
2347 if (be >= 0 && k <= Int_max) {
2348 /* Yes. */
2349 ds = tens[k];
2350 if (ndigits < 0 && ilim <= 0) {
2351 S = mhi = 0;
2352 if (ilim < 0 || dval(&u) <= 5*ds)
2353 goto no_digits;
2354 goto one_digit;
2356 for(i = 1;; i++, dval(&u) *= 10.) {
2357 L = (Long)(dval(&u) / ds);
2358 dval(&u) -= L*ds;
2359 *s++ = '0' + (int)L;
2360 if (!dval(&u)) {
2361 break;
2363 if (i == ilim) {
2364 dval(&u) += dval(&u);
2365 if (dval(&u) > ds || (dval(&u) == ds && L & 1)) {
2366 bump_up:
2367 while(*--s == '9')
2368 if (s == s0) {
2369 k++;
2370 *s = '0';
2371 break;
2373 ++*s++;
2375 break;
2378 goto ret1;
2381 m2 = b2;
2382 m5 = b5;
2383 if (leftright) {
2385 denorm ? be + (Bias + (P-1) - 1 + 1) :
2386 1 + P - bbits;
2387 b2 += i;
2388 s2 += i;
2389 mhi = i2b(1);
2390 if (mhi == NULL)
2391 goto failed_malloc;
2393 if (m2 > 0 && s2 > 0) {
2394 i = m2 < s2 ? m2 : s2;
2395 b2 -= i;
2396 m2 -= i;
2397 s2 -= i;
2399 if (b5 > 0) {
2400 if (leftright) {
2401 if (m5 > 0) {
2402 mhi = pow5mult(mhi, m5);
2403 if (mhi == NULL)
2404 goto failed_malloc;
2405 b1 = mult(mhi, b);
2406 Bfree(b);
2407 b = b1;
2408 if (b == NULL)
2409 goto failed_malloc;
2411 if ((j = b5 - m5)) {
2412 b = pow5mult(b, j);
2413 if (b == NULL)
2414 goto failed_malloc;
2417 else {
2418 b = pow5mult(b, b5);
2419 if (b == NULL)
2420 goto failed_malloc;
2423 S = i2b(1);
2424 if (S == NULL)
2425 goto failed_malloc;
2426 if (s5 > 0) {
2427 S = pow5mult(S, s5);
2428 if (S == NULL)
2429 goto failed_malloc;
2432 /* Check for special case that d is a normalized power of 2. */
2434 spec_case = 0;
2435 if ((mode < 2 || leftright)
2437 if (!word1(&u) && !(word0(&u) & Bndry_mask)
2438 && word0(&u) & (Exp_mask & ~Exp_msk1)
2440 /* The special case */
2441 b2 += Log2P;
2442 s2 += Log2P;
2443 spec_case = 1;
2447 /* Arrange for convenient computation of quotients:
2448 * shift left if necessary so divisor has 4 leading 0 bits.
2450 * Perhaps we should just compute leading 28 bits of S once
2451 * and for all and pass them and a shift to quorem, so it
2452 * can do shifts and ors to compute the numerator for q.
2454 if ((i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0x1f))
2455 i = 32 - i;
2456 #define iInc 28
2457 i = dshift(S, s2);
2458 b2 += i;
2459 m2 += i;
2460 s2 += i;
2461 if (b2 > 0) {
2462 b = lshift(b, b2);
2463 if (b == NULL)
2464 goto failed_malloc;
2466 if (s2 > 0) {
2467 S = lshift(S, s2);
2468 if (S == NULL)
2469 goto failed_malloc;
2471 if (k_check) {
2472 if (cmp(b,S) < 0) {
2473 k--;
2474 b = multadd(b, 10, 0); /* we botched the k estimate */
2475 if (b == NULL)
2476 goto failed_malloc;
2477 if (leftright) {
2478 mhi = multadd(mhi, 10, 0);
2479 if (mhi == NULL)
2480 goto failed_malloc;
2482 ilim = ilim1;
2485 if (ilim <= 0 && (mode == 3 || mode == 5)) {
2486 if (ilim < 0) {
2487 /* no digits, fcvt style */
2488 no_digits:
2489 k = -1 - ndigits;
2490 goto ret;
2492 else {
2493 S = multadd(S, 5, 0);
2494 if (S == NULL)
2495 goto failed_malloc;
2496 if (cmp(b, S) <= 0)
2497 goto no_digits;
2499 one_digit:
2500 *s++ = '1';
2501 k++;
2502 goto ret;
2504 if (leftright) {
2505 if (m2 > 0) {
2506 mhi = lshift(mhi, m2);
2507 if (mhi == NULL)
2508 goto failed_malloc;
2511 /* Compute mlo -- check for special case
2512 * that d is a normalized power of 2.
2515 mlo = mhi;
2516 if (spec_case) {
2517 mhi = Balloc(mhi->k);
2518 if (mhi == NULL)
2519 goto failed_malloc;
2520 Bcopy(mhi, mlo);
2521 mhi = lshift(mhi, Log2P);
2522 if (mhi == NULL)
2523 goto failed_malloc;
2526 for(i = 1;;i++) {
2527 dig = quorem(b,S) + '0';
2528 /* Do we yet have the shortest decimal string
2529 * that will round to d?
2531 j = cmp(b, mlo);
2532 delta = diff(S, mhi);
2533 if (delta == NULL)
2534 goto failed_malloc;
2535 j1 = delta->sign ? 1 : cmp(b, delta);
2536 Bfree(delta);
2537 if (j1 == 0 && mode != 1 && !(word1(&u) & 1)
2539 if (dig == '9')
2540 goto round_9_up;
2541 if (j > 0)
2542 dig++;
2543 *s++ = dig;
2544 goto ret;
2546 if (j < 0 || (j == 0 && mode != 1
2547 && !(word1(&u) & 1)
2548 )) {
2549 if (!b->x[0] && b->wds <= 1) {
2550 goto accept_dig;
2552 if (j1 > 0) {
2553 b = lshift(b, 1);
2554 if (b == NULL)
2555 goto failed_malloc;
2556 j1 = cmp(b, S);
2557 if ((j1 > 0 || (j1 == 0 && dig & 1))
2558 && dig++ == '9')
2559 goto round_9_up;
2561 accept_dig:
2562 *s++ = dig;
2563 goto ret;
2565 if (j1 > 0) {
2566 if (dig == '9') { /* possible if i == 1 */
2567 round_9_up:
2568 *s++ = '9';
2569 goto roundoff;
2571 *s++ = dig + 1;
2572 goto ret;
2574 *s++ = dig;
2575 if (i == ilim)
2576 break;
2577 b = multadd(b, 10, 0);
2578 if (b == NULL)
2579 goto failed_malloc;
2580 if (mlo == mhi) {
2581 mlo = mhi = multadd(mhi, 10, 0);
2582 if (mlo == NULL)
2583 goto failed_malloc;
2585 else {
2586 mlo = multadd(mlo, 10, 0);
2587 if (mlo == NULL)
2588 goto failed_malloc;
2589 mhi = multadd(mhi, 10, 0);
2590 if (mhi == NULL)
2591 goto failed_malloc;
2595 else
2596 for(i = 1;; i++) {
2597 *s++ = dig = quorem(b,S) + '0';
2598 if (!b->x[0] && b->wds <= 1) {
2599 goto ret;
2601 if (i >= ilim)
2602 break;
2603 b = multadd(b, 10, 0);
2604 if (b == NULL)
2605 goto failed_malloc;
2608 /* Round off last digit */
2610 b = lshift(b, 1);
2611 if (b == NULL)
2612 goto failed_malloc;
2613 j = cmp(b, S);
2614 if (j > 0 || (j == 0 && dig & 1)) {
2615 roundoff:
2616 while(*--s == '9')
2617 if (s == s0) {
2618 k++;
2619 *s++ = '1';
2620 goto ret;
2622 ++*s++;
2624 else {
2625 while(*--s == '0');
2626 s++;
2628 ret:
2629 Bfree(S);
2630 if (mhi) {
2631 if (mlo && mlo != mhi)
2632 Bfree(mlo);
2633 Bfree(mhi);
2635 ret1:
2636 Bfree(b);
2637 *s = 0;
2638 *decpt = k + 1;
2639 if (rve)
2640 *rve = s;
2641 return s0;
2642 failed_malloc:
2643 if (S)
2644 Bfree(S);
2645 if (mlo && mlo != mhi)
2646 Bfree(mlo);
2647 if (mhi)
2648 Bfree(mhi);
2649 if (b)
2650 Bfree(b);
2651 if (s0)
2652 _Py_dg_freedtoa(s0);
2653 return NULL;
2655 #ifdef __cplusplus
2657 #endif
2659 #endif /* PY_NO_SHORT_FLOAT_REPR */