Issue #7654: enable additional bytes/bytearray tests. Patch by Florent Xicluna.
[python.git] / Python / dtoa.c
blob12e6f806380932de83fe89f7623e7cbe2aba8b2e
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 /* maximum permitted exponent value for strtod; exponents larger than
204 MAX_ABS_EXP in absolute value get truncated to +-MAX_ABS_EXP. MAX_ABS_EXP
205 should fit into an int. */
206 #ifndef MAX_ABS_EXP
207 #define MAX_ABS_EXP 19999U
208 #endif
210 /* The following definition of Storeinc is appropriate for MIPS processors.
211 * An alternative that might be better on some machines is
212 * #define Storeinc(a,b,c) (*a++ = b << 16 | c & 0xffff)
214 #if defined(IEEE_8087)
215 #define Storeinc(a,b,c) (((unsigned short *)a)[1] = (unsigned short)b, \
216 ((unsigned short *)a)[0] = (unsigned short)c, a++)
217 #else
218 #define Storeinc(a,b,c) (((unsigned short *)a)[0] = (unsigned short)b, \
219 ((unsigned short *)a)[1] = (unsigned short)c, a++)
220 #endif
222 /* #define P DBL_MANT_DIG */
223 /* Ten_pmax = floor(P*log(2)/log(5)) */
224 /* Bletch = (highest power of 2 < DBL_MAX_10_EXP) / 16 */
225 /* Quick_max = floor((P-1)*log(FLT_RADIX)/log(10) - 1) */
226 /* Int_max = floor(P*log(FLT_RADIX)/log(10) - 1) */
228 #define Exp_shift 20
229 #define Exp_shift1 20
230 #define Exp_msk1 0x100000
231 #define Exp_msk11 0x100000
232 #define Exp_mask 0x7ff00000
233 #define P 53
234 #define Nbits 53
235 #define Bias 1023
236 #define Emax 1023
237 #define Emin (-1022)
238 #define Exp_1 0x3ff00000
239 #define Exp_11 0x3ff00000
240 #define Ebits 11
241 #define Frac_mask 0xfffff
242 #define Frac_mask1 0xfffff
243 #define Ten_pmax 22
244 #define Bletch 0x10
245 #define Bndry_mask 0xfffff
246 #define Bndry_mask1 0xfffff
247 #define LSB 1
248 #define Sign_bit 0x80000000
249 #define Log2P 1
250 #define Tiny0 0
251 #define Tiny1 1
252 #define Quick_max 14
253 #define Int_max 14
255 #ifndef Flt_Rounds
256 #ifdef FLT_ROUNDS
257 #define Flt_Rounds FLT_ROUNDS
258 #else
259 #define Flt_Rounds 1
260 #endif
261 #endif /*Flt_Rounds*/
263 #define Rounding Flt_Rounds
265 #define Big0 (Frac_mask1 | Exp_msk1*(DBL_MAX_EXP+Bias-1))
266 #define Big1 0xffffffff
268 /* struct BCinfo is used to pass information from _Py_dg_strtod to bigcomp */
270 typedef struct BCinfo BCinfo;
271 struct
272 BCinfo {
273 int dp0, dp1, dplen, dsign, e0, nd, nd0, scale;
276 #define FFFFFFFF 0xffffffffUL
278 #define Kmax 7
280 /* struct Bigint is used to represent arbitrary-precision integers. These
281 integers are stored in sign-magnitude format, with the magnitude stored as
282 an array of base 2**32 digits. Bigints are always normalized: if x is a
283 Bigint then x->wds >= 1, and either x->wds == 1 or x[wds-1] is nonzero.
285 The Bigint fields are as follows:
287 - next is a header used by Balloc and Bfree to keep track of lists
288 of freed Bigints; it's also used for the linked list of
289 powers of 5 of the form 5**2**i used by pow5mult.
290 - k indicates which pool this Bigint was allocated from
291 - maxwds is the maximum number of words space was allocated for
292 (usually maxwds == 2**k)
293 - sign is 1 for negative Bigints, 0 for positive. The sign is unused
294 (ignored on inputs, set to 0 on outputs) in almost all operations
295 involving Bigints: a notable exception is the diff function, which
296 ignores signs on inputs but sets the sign of the output correctly.
297 - wds is the actual number of significant words
298 - x contains the vector of words (digits) for this Bigint, from least
299 significant (x[0]) to most significant (x[wds-1]).
302 struct
303 Bigint {
304 struct Bigint *next;
305 int k, maxwds, sign, wds;
306 ULong x[1];
309 typedef struct Bigint Bigint;
311 /* Memory management: memory is allocated from, and returned to, Kmax+1 pools
312 of memory, where pool k (0 <= k <= Kmax) is for Bigints b with b->maxwds ==
313 1 << k. These pools are maintained as linked lists, with freelist[k]
314 pointing to the head of the list for pool k.
316 On allocation, if there's no free slot in the appropriate pool, MALLOC is
317 called to get more memory. This memory is not returned to the system until
318 Python quits. There's also a private memory pool that's allocated from
319 in preference to using MALLOC.
321 For Bigints with more than (1 << Kmax) digits (which implies at least 1233
322 decimal digits), memory is directly allocated using MALLOC, and freed using
323 FREE.
325 XXX: it would be easy to bypass this memory-management system and
326 translate each call to Balloc into a call to PyMem_Malloc, and each
327 Bfree to PyMem_Free. Investigate whether this has any significant
328 performance on impact. */
330 static Bigint *freelist[Kmax+1];
332 /* Allocate space for a Bigint with up to 1<<k digits */
334 static Bigint *
335 Balloc(int k)
337 int x;
338 Bigint *rv;
339 unsigned int len;
341 if (k <= Kmax && (rv = freelist[k]))
342 freelist[k] = rv->next;
343 else {
344 x = 1 << k;
345 len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1)
346 /sizeof(double);
347 if (k <= Kmax && pmem_next - private_mem + len <= PRIVATE_mem) {
348 rv = (Bigint*)pmem_next;
349 pmem_next += len;
351 else {
352 rv = (Bigint*)MALLOC(len*sizeof(double));
353 if (rv == NULL)
354 return NULL;
356 rv->k = k;
357 rv->maxwds = x;
359 rv->sign = rv->wds = 0;
360 return rv;
363 /* Free a Bigint allocated with Balloc */
365 static void
366 Bfree(Bigint *v)
368 if (v) {
369 if (v->k > Kmax)
370 FREE((void*)v);
371 else {
372 v->next = freelist[v->k];
373 freelist[v->k] = v;
378 #define Bcopy(x,y) memcpy((char *)&x->sign, (char *)&y->sign, \
379 y->wds*sizeof(Long) + 2*sizeof(int))
381 /* Multiply a Bigint b by m and add a. Either modifies b in place and returns
382 a pointer to the modified b, or Bfrees b and returns a pointer to a copy.
383 On failure, return NULL. In this case, b will have been already freed. */
385 static Bigint *
386 multadd(Bigint *b, int m, int a) /* multiply by m and add a */
388 int i, wds;
389 #ifdef ULLong
390 ULong *x;
391 ULLong carry, y;
392 #else
393 ULong carry, *x, y;
394 ULong xi, z;
395 #endif
396 Bigint *b1;
398 wds = b->wds;
399 x = b->x;
400 i = 0;
401 carry = a;
402 do {
403 #ifdef ULLong
404 y = *x * (ULLong)m + carry;
405 carry = y >> 32;
406 *x++ = (ULong)(y & FFFFFFFF);
407 #else
408 xi = *x;
409 y = (xi & 0xffff) * m + carry;
410 z = (xi >> 16) * m + (y >> 16);
411 carry = z >> 16;
412 *x++ = (z << 16) + (y & 0xffff);
413 #endif
415 while(++i < wds);
416 if (carry) {
417 if (wds >= b->maxwds) {
418 b1 = Balloc(b->k+1);
419 if (b1 == NULL){
420 Bfree(b);
421 return NULL;
423 Bcopy(b1, b);
424 Bfree(b);
425 b = b1;
427 b->x[wds++] = (ULong)carry;
428 b->wds = wds;
430 return b;
433 /* convert a string s containing nd decimal digits (possibly containing a
434 decimal separator at position nd0, which is ignored) to a Bigint. This
435 function carries on where the parsing code in _Py_dg_strtod leaves off: on
436 entry, y9 contains the result of converting the first 9 digits. Returns
437 NULL on failure. */
439 static Bigint *
440 s2b(const char *s, int nd0, int nd, ULong y9, int dplen)
442 Bigint *b;
443 int i, k;
444 Long x, y;
446 x = (nd + 8) / 9;
447 for(k = 0, y = 1; x > y; y <<= 1, k++) ;
448 b = Balloc(k);
449 if (b == NULL)
450 return NULL;
451 b->x[0] = y9;
452 b->wds = 1;
454 i = 9;
455 if (9 < nd0) {
456 s += 9;
457 do {
458 b = multadd(b, 10, *s++ - '0');
459 if (b == NULL)
460 return NULL;
461 } while(++i < nd0);
462 s += dplen;
464 else
465 s += dplen + 9;
466 for(; i < nd; i++) {
467 b = multadd(b, 10, *s++ - '0');
468 if (b == NULL)
469 return NULL;
471 return b;
474 /* count leading 0 bits in the 32-bit integer x. */
476 static int
477 hi0bits(ULong x)
479 int k = 0;
481 if (!(x & 0xffff0000)) {
482 k = 16;
483 x <<= 16;
485 if (!(x & 0xff000000)) {
486 k += 8;
487 x <<= 8;
489 if (!(x & 0xf0000000)) {
490 k += 4;
491 x <<= 4;
493 if (!(x & 0xc0000000)) {
494 k += 2;
495 x <<= 2;
497 if (!(x & 0x80000000)) {
498 k++;
499 if (!(x & 0x40000000))
500 return 32;
502 return k;
505 /* count trailing 0 bits in the 32-bit integer y, and shift y right by that
506 number of bits. */
508 static int
509 lo0bits(ULong *y)
511 int k;
512 ULong x = *y;
514 if (x & 7) {
515 if (x & 1)
516 return 0;
517 if (x & 2) {
518 *y = x >> 1;
519 return 1;
521 *y = x >> 2;
522 return 2;
524 k = 0;
525 if (!(x & 0xffff)) {
526 k = 16;
527 x >>= 16;
529 if (!(x & 0xff)) {
530 k += 8;
531 x >>= 8;
533 if (!(x & 0xf)) {
534 k += 4;
535 x >>= 4;
537 if (!(x & 0x3)) {
538 k += 2;
539 x >>= 2;
541 if (!(x & 1)) {
542 k++;
543 x >>= 1;
544 if (!x)
545 return 32;
547 *y = x;
548 return k;
551 /* convert a small nonnegative integer to a Bigint */
553 static Bigint *
554 i2b(int i)
556 Bigint *b;
558 b = Balloc(1);
559 if (b == NULL)
560 return NULL;
561 b->x[0] = i;
562 b->wds = 1;
563 return b;
566 /* multiply two Bigints. Returns a new Bigint, or NULL on failure. Ignores
567 the signs of a and b. */
569 static Bigint *
570 mult(Bigint *a, Bigint *b)
572 Bigint *c;
573 int k, wa, wb, wc;
574 ULong *x, *xa, *xae, *xb, *xbe, *xc, *xc0;
575 ULong y;
576 #ifdef ULLong
577 ULLong carry, z;
578 #else
579 ULong carry, z;
580 ULong z2;
581 #endif
583 if (a->wds < b->wds) {
584 c = a;
585 a = b;
586 b = c;
588 k = a->k;
589 wa = a->wds;
590 wb = b->wds;
591 wc = wa + wb;
592 if (wc > a->maxwds)
593 k++;
594 c = Balloc(k);
595 if (c == NULL)
596 return NULL;
597 for(x = c->x, xa = x + wc; x < xa; x++)
598 *x = 0;
599 xa = a->x;
600 xae = xa + wa;
601 xb = b->x;
602 xbe = xb + wb;
603 xc0 = c->x;
604 #ifdef ULLong
605 for(; xb < xbe; xc0++) {
606 if ((y = *xb++)) {
607 x = xa;
608 xc = xc0;
609 carry = 0;
610 do {
611 z = *x++ * (ULLong)y + *xc + carry;
612 carry = z >> 32;
613 *xc++ = (ULong)(z & FFFFFFFF);
615 while(x < xae);
616 *xc = (ULong)carry;
619 #else
620 for(; xb < xbe; xb++, xc0++) {
621 if (y = *xb & 0xffff) {
622 x = xa;
623 xc = xc0;
624 carry = 0;
625 do {
626 z = (*x & 0xffff) * y + (*xc & 0xffff) + carry;
627 carry = z >> 16;
628 z2 = (*x++ >> 16) * y + (*xc >> 16) + carry;
629 carry = z2 >> 16;
630 Storeinc(xc, z2, z);
632 while(x < xae);
633 *xc = carry;
635 if (y = *xb >> 16) {
636 x = xa;
637 xc = xc0;
638 carry = 0;
639 z2 = *xc;
640 do {
641 z = (*x & 0xffff) * y + (*xc >> 16) + carry;
642 carry = z >> 16;
643 Storeinc(xc, z, z2);
644 z2 = (*x++ >> 16) * y + (*xc & 0xffff) + carry;
645 carry = z2 >> 16;
647 while(x < xae);
648 *xc = z2;
651 #endif
652 for(xc0 = c->x, xc = xc0 + wc; wc > 0 && !*--xc; --wc) ;
653 c->wds = wc;
654 return c;
657 /* p5s is a linked list of powers of 5 of the form 5**(2**i), i >= 2 */
659 static Bigint *p5s;
661 /* multiply the Bigint b by 5**k. Returns a pointer to the result, or NULL on
662 failure; if the returned pointer is distinct from b then the original
663 Bigint b will have been Bfree'd. Ignores the sign of b. */
665 static Bigint *
666 pow5mult(Bigint *b, int k)
668 Bigint *b1, *p5, *p51;
669 int i;
670 static int p05[3] = { 5, 25, 125 };
672 if ((i = k & 3)) {
673 b = multadd(b, p05[i-1], 0);
674 if (b == NULL)
675 return NULL;
678 if (!(k >>= 2))
679 return b;
680 p5 = p5s;
681 if (!p5) {
682 /* first time */
683 p5 = i2b(625);
684 if (p5 == NULL) {
685 Bfree(b);
686 return NULL;
688 p5s = p5;
689 p5->next = 0;
691 for(;;) {
692 if (k & 1) {
693 b1 = mult(b, p5);
694 Bfree(b);
695 b = b1;
696 if (b == NULL)
697 return NULL;
699 if (!(k >>= 1))
700 break;
701 p51 = p5->next;
702 if (!p51) {
703 p51 = mult(p5,p5);
704 if (p51 == NULL) {
705 Bfree(b);
706 return NULL;
708 p51->next = 0;
709 p5->next = p51;
711 p5 = p51;
713 return b;
716 /* shift a Bigint b left by k bits. Return a pointer to the shifted result,
717 or NULL on failure. If the returned pointer is distinct from b then the
718 original b will have been Bfree'd. Ignores the sign of b. */
720 static Bigint *
721 lshift(Bigint *b, int k)
723 int i, k1, n, n1;
724 Bigint *b1;
725 ULong *x, *x1, *xe, z;
727 n = k >> 5;
728 k1 = b->k;
729 n1 = n + b->wds + 1;
730 for(i = b->maxwds; n1 > i; i <<= 1)
731 k1++;
732 b1 = Balloc(k1);
733 if (b1 == NULL) {
734 Bfree(b);
735 return NULL;
737 x1 = b1->x;
738 for(i = 0; i < n; i++)
739 *x1++ = 0;
740 x = b->x;
741 xe = x + b->wds;
742 if (k &= 0x1f) {
743 k1 = 32 - k;
744 z = 0;
745 do {
746 *x1++ = *x << k | z;
747 z = *x++ >> k1;
749 while(x < xe);
750 if ((*x1 = z))
751 ++n1;
753 else do
754 *x1++ = *x++;
755 while(x < xe);
756 b1->wds = n1 - 1;
757 Bfree(b);
758 return b1;
761 /* Do a three-way compare of a and b, returning -1 if a < b, 0 if a == b and
762 1 if a > b. Ignores signs of a and b. */
764 static int
765 cmp(Bigint *a, Bigint *b)
767 ULong *xa, *xa0, *xb, *xb0;
768 int i, j;
770 i = a->wds;
771 j = b->wds;
772 #ifdef DEBUG
773 if (i > 1 && !a->x[i-1])
774 Bug("cmp called with a->x[a->wds-1] == 0");
775 if (j > 1 && !b->x[j-1])
776 Bug("cmp called with b->x[b->wds-1] == 0");
777 #endif
778 if (i -= j)
779 return i;
780 xa0 = a->x;
781 xa = xa0 + j;
782 xb0 = b->x;
783 xb = xb0 + j;
784 for(;;) {
785 if (*--xa != *--xb)
786 return *xa < *xb ? -1 : 1;
787 if (xa <= xa0)
788 break;
790 return 0;
793 /* Take the difference of Bigints a and b, returning a new Bigint. Returns
794 NULL on failure. The signs of a and b are ignored, but the sign of the
795 result is set appropriately. */
797 static Bigint *
798 diff(Bigint *a, Bigint *b)
800 Bigint *c;
801 int i, wa, wb;
802 ULong *xa, *xae, *xb, *xbe, *xc;
803 #ifdef ULLong
804 ULLong borrow, y;
805 #else
806 ULong borrow, y;
807 ULong z;
808 #endif
810 i = cmp(a,b);
811 if (!i) {
812 c = Balloc(0);
813 if (c == NULL)
814 return NULL;
815 c->wds = 1;
816 c->x[0] = 0;
817 return c;
819 if (i < 0) {
820 c = a;
821 a = b;
822 b = c;
823 i = 1;
825 else
826 i = 0;
827 c = Balloc(a->k);
828 if (c == NULL)
829 return NULL;
830 c->sign = i;
831 wa = a->wds;
832 xa = a->x;
833 xae = xa + wa;
834 wb = b->wds;
835 xb = b->x;
836 xbe = xb + wb;
837 xc = c->x;
838 borrow = 0;
839 #ifdef ULLong
840 do {
841 y = (ULLong)*xa++ - *xb++ - borrow;
842 borrow = y >> 32 & (ULong)1;
843 *xc++ = (ULong)(y & FFFFFFFF);
845 while(xb < xbe);
846 while(xa < xae) {
847 y = *xa++ - borrow;
848 borrow = y >> 32 & (ULong)1;
849 *xc++ = (ULong)(y & FFFFFFFF);
851 #else
852 do {
853 y = (*xa & 0xffff) - (*xb & 0xffff) - borrow;
854 borrow = (y & 0x10000) >> 16;
855 z = (*xa++ >> 16) - (*xb++ >> 16) - borrow;
856 borrow = (z & 0x10000) >> 16;
857 Storeinc(xc, z, y);
859 while(xb < xbe);
860 while(xa < xae) {
861 y = (*xa & 0xffff) - borrow;
862 borrow = (y & 0x10000) >> 16;
863 z = (*xa++ >> 16) - borrow;
864 borrow = (z & 0x10000) >> 16;
865 Storeinc(xc, z, y);
867 #endif
868 while(!*--xc)
869 wa--;
870 c->wds = wa;
871 return c;
874 /* Given a positive normal double x, return the difference between x and the next
875 double up. Doesn't give correct results for subnormals. */
877 static double
878 ulp(U *x)
880 Long L;
881 U u;
883 L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1;
884 word0(&u) = L;
885 word1(&u) = 0;
886 return dval(&u);
889 /* Convert a Bigint to a double plus an exponent */
891 static double
892 b2d(Bigint *a, int *e)
894 ULong *xa, *xa0, w, y, z;
895 int k;
896 U d;
898 xa0 = a->x;
899 xa = xa0 + a->wds;
900 y = *--xa;
901 #ifdef DEBUG
902 if (!y) Bug("zero y in b2d");
903 #endif
904 k = hi0bits(y);
905 *e = 32 - k;
906 if (k < Ebits) {
907 word0(&d) = Exp_1 | y >> (Ebits - k);
908 w = xa > xa0 ? *--xa : 0;
909 word1(&d) = y << ((32-Ebits) + k) | w >> (Ebits - k);
910 goto ret_d;
912 z = xa > xa0 ? *--xa : 0;
913 if (k -= Ebits) {
914 word0(&d) = Exp_1 | y << k | z >> (32 - k);
915 y = xa > xa0 ? *--xa : 0;
916 word1(&d) = z << k | y >> (32 - k);
918 else {
919 word0(&d) = Exp_1 | y;
920 word1(&d) = z;
922 ret_d:
923 return dval(&d);
926 /* Convert a double to a Bigint plus an exponent. Return NULL on failure.
928 Given a finite nonzero double d, return an odd Bigint b and exponent *e
929 such that fabs(d) = b * 2**e. On return, *bbits gives the number of
930 significant bits of b; that is, 2**(*bbits-1) <= b < 2**(*bbits).
932 If d is zero, then b == 0, *e == -1010, *bbits = 0.
936 static Bigint *
937 d2b(U *d, int *e, int *bits)
939 Bigint *b;
940 int de, k;
941 ULong *x, y, z;
942 int i;
944 b = Balloc(1);
945 if (b == NULL)
946 return NULL;
947 x = b->x;
949 z = word0(d) & Frac_mask;
950 word0(d) &= 0x7fffffff; /* clear sign bit, which we ignore */
951 if ((de = (int)(word0(d) >> Exp_shift)))
952 z |= Exp_msk1;
953 if ((y = word1(d))) {
954 if ((k = lo0bits(&y))) {
955 x[0] = y | z << (32 - k);
956 z >>= k;
958 else
959 x[0] = y;
961 b->wds = (x[1] = z) ? 2 : 1;
963 else {
964 k = lo0bits(&z);
965 x[0] = z;
967 b->wds = 1;
968 k += 32;
970 if (de) {
971 *e = de - Bias - (P-1) + k;
972 *bits = P - k;
974 else {
975 *e = de - Bias - (P-1) + 1 + k;
976 *bits = 32*i - hi0bits(x[i-1]);
978 return b;
981 /* Compute the ratio of two Bigints, as a double. The result may have an
982 error of up to 2.5 ulps. */
984 static double
985 ratio(Bigint *a, Bigint *b)
987 U da, db;
988 int k, ka, kb;
990 dval(&da) = b2d(a, &ka);
991 dval(&db) = b2d(b, &kb);
992 k = ka - kb + 32*(a->wds - b->wds);
993 if (k > 0)
994 word0(&da) += k*Exp_msk1;
995 else {
996 k = -k;
997 word0(&db) += k*Exp_msk1;
999 return dval(&da) / dval(&db);
1002 static const double
1003 tens[] = {
1004 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
1005 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
1006 1e20, 1e21, 1e22
1009 static const double
1010 bigtens[] = { 1e16, 1e32, 1e64, 1e128, 1e256 };
1011 static const double tinytens[] = { 1e-16, 1e-32, 1e-64, 1e-128,
1012 9007199254740992.*9007199254740992.e-256
1013 /* = 2^106 * 1e-256 */
1015 /* The factor of 2^53 in tinytens[4] helps us avoid setting the underflow */
1016 /* flag unnecessarily. It leads to a song and dance at the end of strtod. */
1017 #define Scale_Bit 0x10
1018 #define n_bigtens 5
1020 #define ULbits 32
1021 #define kshift 5
1022 #define kmask 31
1025 static int
1026 dshift(Bigint *b, int p2)
1028 int rv = hi0bits(b->x[b->wds-1]) - 4;
1029 if (p2 > 0)
1030 rv -= p2;
1031 return rv & kmask;
1034 /* special case of Bigint division. The quotient is always in the range 0 <=
1035 quotient < 10, and on entry the divisor S is normalized so that its top 4
1036 bits (28--31) are zero and bit 27 is set. */
1038 static int
1039 quorem(Bigint *b, Bigint *S)
1041 int n;
1042 ULong *bx, *bxe, q, *sx, *sxe;
1043 #ifdef ULLong
1044 ULLong borrow, carry, y, ys;
1045 #else
1046 ULong borrow, carry, y, ys;
1047 ULong si, z, zs;
1048 #endif
1050 n = S->wds;
1051 #ifdef DEBUG
1052 /*debug*/ if (b->wds > n)
1053 /*debug*/ Bug("oversize b in quorem");
1054 #endif
1055 if (b->wds < n)
1056 return 0;
1057 sx = S->x;
1058 sxe = sx + --n;
1059 bx = b->x;
1060 bxe = bx + n;
1061 q = *bxe / (*sxe + 1); /* ensure q <= true quotient */
1062 #ifdef DEBUG
1063 /*debug*/ if (q > 9)
1064 /*debug*/ Bug("oversized quotient in quorem");
1065 #endif
1066 if (q) {
1067 borrow = 0;
1068 carry = 0;
1069 do {
1070 #ifdef ULLong
1071 ys = *sx++ * (ULLong)q + carry;
1072 carry = ys >> 32;
1073 y = *bx - (ys & FFFFFFFF) - borrow;
1074 borrow = y >> 32 & (ULong)1;
1075 *bx++ = (ULong)(y & FFFFFFFF);
1076 #else
1077 si = *sx++;
1078 ys = (si & 0xffff) * q + carry;
1079 zs = (si >> 16) * q + (ys >> 16);
1080 carry = zs >> 16;
1081 y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
1082 borrow = (y & 0x10000) >> 16;
1083 z = (*bx >> 16) - (zs & 0xffff) - borrow;
1084 borrow = (z & 0x10000) >> 16;
1085 Storeinc(bx, z, y);
1086 #endif
1088 while(sx <= sxe);
1089 if (!*bxe) {
1090 bx = b->x;
1091 while(--bxe > bx && !*bxe)
1092 --n;
1093 b->wds = n;
1096 if (cmp(b, S) >= 0) {
1097 q++;
1098 borrow = 0;
1099 carry = 0;
1100 bx = b->x;
1101 sx = S->x;
1102 do {
1103 #ifdef ULLong
1104 ys = *sx++ + carry;
1105 carry = ys >> 32;
1106 y = *bx - (ys & FFFFFFFF) - borrow;
1107 borrow = y >> 32 & (ULong)1;
1108 *bx++ = (ULong)(y & FFFFFFFF);
1109 #else
1110 si = *sx++;
1111 ys = (si & 0xffff) + carry;
1112 zs = (si >> 16) + (ys >> 16);
1113 carry = zs >> 16;
1114 y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
1115 borrow = (y & 0x10000) >> 16;
1116 z = (*bx >> 16) - (zs & 0xffff) - borrow;
1117 borrow = (z & 0x10000) >> 16;
1118 Storeinc(bx, z, y);
1119 #endif
1121 while(sx <= sxe);
1122 bx = b->x;
1123 bxe = bx + n;
1124 if (!*bxe) {
1125 while(--bxe > bx && !*bxe)
1126 --n;
1127 b->wds = n;
1130 return q;
1134 /* return 0 on success, -1 on failure */
1136 static int
1137 bigcomp(U *rv, const char *s0, BCinfo *bc)
1139 Bigint *b, *d;
1140 int b2, bbits, d2, dd, dig, dsign, i, j, nd, nd0, p2, p5, speccase;
1142 dsign = bc->dsign;
1143 nd = bc->nd;
1144 nd0 = bc->nd0;
1145 p5 = nd + bc->e0 - 1;
1146 speccase = 0;
1147 if (rv->d == 0.) { /* special case: value near underflow-to-zero */
1148 /* threshold was rounded to zero */
1149 b = i2b(1);
1150 if (b == NULL)
1151 return -1;
1152 p2 = Emin - P + 1;
1153 bbits = 1;
1154 word0(rv) = (P+2) << Exp_shift;
1155 i = 0;
1157 speccase = 1;
1158 --p2;
1159 dsign = 0;
1160 goto have_i;
1163 else
1165 b = d2b(rv, &p2, &bbits);
1166 if (b == NULL)
1167 return -1;
1169 p2 -= bc->scale;
1170 /* floor(log2(rv)) == bbits - 1 + p2 */
1171 /* Check for denormal case. */
1172 i = P - bbits;
1173 if (i > (j = P - Emin - 1 + p2)) {
1174 i = j;
1177 b = lshift(b, ++i);
1178 if (b == NULL)
1179 return -1;
1180 b->x[0] |= 1;
1182 have_i:
1183 p2 -= p5 + i;
1184 d = i2b(1);
1185 if (d == NULL) {
1186 Bfree(b);
1187 return -1;
1189 /* Arrange for convenient computation of quotients:
1190 * shift left if necessary so divisor has 4 leading 0 bits.
1192 if (p5 > 0) {
1193 d = pow5mult(d, p5);
1194 if (d == NULL) {
1195 Bfree(b);
1196 return -1;
1199 else if (p5 < 0) {
1200 b = pow5mult(b, -p5);
1201 if (b == NULL) {
1202 Bfree(d);
1203 return -1;
1206 if (p2 > 0) {
1207 b2 = p2;
1208 d2 = 0;
1210 else {
1211 b2 = 0;
1212 d2 = -p2;
1214 i = dshift(d, d2);
1215 if ((b2 += i) > 0) {
1216 b = lshift(b, b2);
1217 if (b == NULL) {
1218 Bfree(d);
1219 return -1;
1222 if ((d2 += i) > 0) {
1223 d = lshift(d, d2);
1224 if (d == NULL) {
1225 Bfree(b);
1226 return -1;
1230 /* Now b/d = exactly half-way between the two floating-point values */
1231 /* on either side of the input string. Compute first digit of b/d. */
1233 if (!(dig = quorem(b,d))) {
1234 b = multadd(b, 10, 0); /* very unlikely */
1235 if (b == NULL) {
1236 Bfree(d);
1237 return -1;
1239 dig = quorem(b,d);
1242 /* Compare b/d with s0 */
1244 assert(nd > 0);
1245 dd = 9999; /* silence gcc compiler warning */
1246 for(i = 0; i < nd0; ) {
1247 if ((dd = s0[i++] - '0' - dig))
1248 goto ret;
1249 if (!b->x[0] && b->wds == 1) {
1250 if (i < nd)
1251 dd = 1;
1252 goto ret;
1254 b = multadd(b, 10, 0);
1255 if (b == NULL) {
1256 Bfree(d);
1257 return -1;
1259 dig = quorem(b,d);
1261 for(j = bc->dp1; i++ < nd;) {
1262 if ((dd = s0[j++] - '0' - dig))
1263 goto ret;
1264 if (!b->x[0] && b->wds == 1) {
1265 if (i < nd)
1266 dd = 1;
1267 goto ret;
1269 b = multadd(b, 10, 0);
1270 if (b == NULL) {
1271 Bfree(d);
1272 return -1;
1274 dig = quorem(b,d);
1276 if (b->x[0] || b->wds > 1)
1277 dd = -1;
1278 ret:
1279 Bfree(b);
1280 Bfree(d);
1281 if (speccase) {
1282 if (dd <= 0)
1283 rv->d = 0.;
1285 else if (dd < 0) {
1286 if (!dsign) /* does not happen for round-near */
1287 retlow1:
1288 dval(rv) -= ulp(rv);
1290 else if (dd > 0) {
1291 if (dsign) {
1292 rethi1:
1293 dval(rv) += ulp(rv);
1296 else {
1297 /* Exact half-way case: apply round-even rule. */
1298 if (word1(rv) & 1) {
1299 if (dsign)
1300 goto rethi1;
1301 goto retlow1;
1305 return 0;
1308 double
1309 _Py_dg_strtod(const char *s00, char **se)
1311 int bb2, bb5, bbe, bd2, bd5, bbbits, bs2, c, e, e1, error;
1312 int esign, i, j, k, nd, nd0, nf, nz, nz0, sign;
1313 const char *s, *s0, *s1;
1314 double aadj, aadj1;
1315 U aadj2, adj, rv, rv0;
1316 ULong y, z, L;
1317 BCinfo bc;
1318 Bigint *bb, *bb1, *bd, *bd0, *bs, *delta;
1320 sign = nz0 = nz = bc.dplen = 0;
1321 dval(&rv) = 0.;
1322 for(s = s00;;s++) switch(*s) {
1323 case '-':
1324 sign = 1;
1325 /* no break */
1326 case '+':
1327 if (*++s)
1328 goto break2;
1329 /* no break */
1330 case 0:
1331 goto ret0;
1332 /* modify original dtoa.c so that it doesn't accept leading whitespace
1333 case '\t':
1334 case '\n':
1335 case '\v':
1336 case '\f':
1337 case '\r':
1338 case ' ':
1339 continue;
1341 default:
1342 goto break2;
1344 break2:
1345 if (*s == '0') {
1346 nz0 = 1;
1347 while(*++s == '0') ;
1348 if (!*s)
1349 goto ret;
1351 s0 = s;
1352 y = z = 0;
1353 for(nd = nf = 0; (c = *s) >= '0' && c <= '9'; nd++, s++)
1354 if (nd < 9)
1355 y = 10*y + c - '0';
1356 else if (nd < 16)
1357 z = 10*z + c - '0';
1358 nd0 = nd;
1359 bc.dp0 = bc.dp1 = s - s0;
1360 if (c == '.') {
1361 c = *++s;
1362 bc.dp1 = s - s0;
1363 bc.dplen = bc.dp1 - bc.dp0;
1364 if (!nd) {
1365 for(; c == '0'; c = *++s)
1366 nz++;
1367 if (c > '0' && c <= '9') {
1368 s0 = s;
1369 nf += nz;
1370 nz = 0;
1371 goto have_dig;
1373 goto dig_done;
1375 for(; c >= '0' && c <= '9'; c = *++s) {
1376 have_dig:
1377 nz++;
1378 if (c -= '0') {
1379 nf += nz;
1380 for(i = 1; i < nz; i++)
1381 if (nd++ < 9)
1382 y *= 10;
1383 else if (nd <= DBL_DIG + 1)
1384 z *= 10;
1385 if (nd++ < 9)
1386 y = 10*y + c;
1387 else if (nd <= DBL_DIG + 1)
1388 z = 10*z + c;
1389 nz = 0;
1393 dig_done:
1394 e = 0;
1395 if (c == 'e' || c == 'E') {
1396 if (!nd && !nz && !nz0) {
1397 goto ret0;
1399 s00 = s;
1400 esign = 0;
1401 switch(c = *++s) {
1402 case '-':
1403 esign = 1;
1404 case '+':
1405 c = *++s;
1407 if (c >= '0' && c <= '9') {
1408 while(c == '0')
1409 c = *++s;
1410 if (c > '0' && c <= '9') {
1411 L = c - '0';
1412 s1 = s;
1413 while((c = *++s) >= '0' && c <= '9')
1414 L = 10*L + c - '0';
1415 if (s - s1 > 8 || L > MAX_ABS_EXP)
1416 /* Avoid confusion from exponents
1417 * so large that e might overflow.
1419 e = (int)MAX_ABS_EXP; /* safe for 16 bit ints */
1420 else
1421 e = (int)L;
1422 if (esign)
1423 e = -e;
1425 else
1426 e = 0;
1428 else
1429 s = s00;
1431 if (!nd) {
1432 if (!nz && !nz0) {
1433 ret0:
1434 s = s00;
1435 sign = 0;
1437 goto ret;
1439 bc.e0 = e1 = e -= nf;
1441 /* Now we have nd0 digits, starting at s0, followed by a
1442 * decimal point, followed by nd-nd0 digits. The number we're
1443 * after is the integer represented by those digits times
1444 * 10**e */
1446 if (!nd0)
1447 nd0 = nd;
1448 k = nd < DBL_DIG + 1 ? nd : DBL_DIG + 1;
1449 dval(&rv) = y;
1450 if (k > 9) {
1451 dval(&rv) = tens[k - 9] * dval(&rv) + z;
1453 bd0 = 0;
1454 if (nd <= DBL_DIG
1455 && Flt_Rounds == 1
1457 if (!e)
1458 goto ret;
1459 if (e > 0) {
1460 if (e <= Ten_pmax) {
1461 dval(&rv) *= tens[e];
1462 goto ret;
1464 i = DBL_DIG - nd;
1465 if (e <= Ten_pmax + i) {
1466 /* A fancier test would sometimes let us do
1467 * this for larger i values.
1469 e -= i;
1470 dval(&rv) *= tens[i];
1471 dval(&rv) *= tens[e];
1472 goto ret;
1475 else if (e >= -Ten_pmax) {
1476 dval(&rv) /= tens[-e];
1477 goto ret;
1480 e1 += nd - k;
1482 bc.scale = 0;
1484 /* Get starting approximation = rv * 10**e1 */
1486 if (e1 > 0) {
1487 if ((i = e1 & 15))
1488 dval(&rv) *= tens[i];
1489 if (e1 &= ~15) {
1490 if (e1 > DBL_MAX_10_EXP) {
1491 ovfl:
1492 errno = ERANGE;
1493 /* Can't trust HUGE_VAL */
1494 word0(&rv) = Exp_mask;
1495 word1(&rv) = 0;
1496 goto ret;
1498 e1 >>= 4;
1499 for(j = 0; e1 > 1; j++, e1 >>= 1)
1500 if (e1 & 1)
1501 dval(&rv) *= bigtens[j];
1502 /* The last multiplication could overflow. */
1503 word0(&rv) -= P*Exp_msk1;
1504 dval(&rv) *= bigtens[j];
1505 if ((z = word0(&rv) & Exp_mask)
1506 > Exp_msk1*(DBL_MAX_EXP+Bias-P))
1507 goto ovfl;
1508 if (z > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) {
1509 /* set to largest number */
1510 /* (Can't trust DBL_MAX) */
1511 word0(&rv) = Big0;
1512 word1(&rv) = Big1;
1514 else
1515 word0(&rv) += P*Exp_msk1;
1518 else if (e1 < 0) {
1519 e1 = -e1;
1520 if ((i = e1 & 15))
1521 dval(&rv) /= tens[i];
1522 if (e1 >>= 4) {
1523 if (e1 >= 1 << n_bigtens)
1524 goto undfl;
1525 if (e1 & Scale_Bit)
1526 bc.scale = 2*P;
1527 for(j = 0; e1 > 0; j++, e1 >>= 1)
1528 if (e1 & 1)
1529 dval(&rv) *= tinytens[j];
1530 if (bc.scale && (j = 2*P + 1 - ((word0(&rv) & Exp_mask)
1531 >> Exp_shift)) > 0) {
1532 /* scaled rv is denormal; clear j low bits */
1533 if (j >= 32) {
1534 word1(&rv) = 0;
1535 if (j >= 53)
1536 word0(&rv) = (P+2)*Exp_msk1;
1537 else
1538 word0(&rv) &= 0xffffffff << (j-32);
1540 else
1541 word1(&rv) &= 0xffffffff << j;
1543 if (!dval(&rv)) {
1544 undfl:
1545 dval(&rv) = 0.;
1546 errno = ERANGE;
1547 goto ret;
1552 /* Now the hard part -- adjusting rv to the correct value.*/
1554 /* Put digits into bd: true value = bd * 10^e */
1556 bc.nd = nd;
1557 bc.nd0 = nd0; /* Only needed if nd > STRTOD_DIGLIM, but done here */
1558 /* to silence an erroneous warning about bc.nd0 */
1559 /* possibly not being initialized. */
1560 if (nd > STRTOD_DIGLIM) {
1561 /* ASSERT(STRTOD_DIGLIM >= 18); 18 == one more than the */
1562 /* minimum number of decimal digits to distinguish double values */
1563 /* in IEEE arithmetic. */
1564 i = j = 18;
1565 if (i > nd0)
1566 j += bc.dplen;
1567 for(;;) {
1568 if (--j <= bc.dp1 && j >= bc.dp0)
1569 j = bc.dp0 - 1;
1570 if (s0[j] != '0')
1571 break;
1572 --i;
1574 e += nd - i;
1575 nd = i;
1576 if (nd0 > nd)
1577 nd0 = nd;
1578 if (nd < 9) { /* must recompute y */
1579 y = 0;
1580 for(i = 0; i < nd0; ++i)
1581 y = 10*y + s0[i] - '0';
1582 for(j = bc.dp1; i < nd; ++i)
1583 y = 10*y + s0[j++] - '0';
1586 bd0 = s2b(s0, nd0, nd, y, bc.dplen);
1587 if (bd0 == NULL)
1588 goto failed_malloc;
1590 for(;;) {
1591 bd = Balloc(bd0->k);
1592 if (bd == NULL) {
1593 Bfree(bd0);
1594 goto failed_malloc;
1596 Bcopy(bd, bd0);
1597 bb = d2b(&rv, &bbe, &bbbits); /* rv = bb * 2^bbe */
1598 if (bb == NULL) {
1599 Bfree(bd);
1600 Bfree(bd0);
1601 goto failed_malloc;
1603 bs = i2b(1);
1604 if (bs == NULL) {
1605 Bfree(bb);
1606 Bfree(bd);
1607 Bfree(bd0);
1608 goto failed_malloc;
1611 if (e >= 0) {
1612 bb2 = bb5 = 0;
1613 bd2 = bd5 = e;
1615 else {
1616 bb2 = bb5 = -e;
1617 bd2 = bd5 = 0;
1619 if (bbe >= 0)
1620 bb2 += bbe;
1621 else
1622 bd2 -= bbe;
1623 bs2 = bb2;
1624 j = bbe - bc.scale;
1625 i = j + bbbits - 1; /* logb(rv) */
1626 if (i < Emin) /* denormal */
1627 j += P - Emin;
1628 else
1629 j = P + 1 - bbbits;
1630 bb2 += j;
1631 bd2 += j;
1632 bd2 += bc.scale;
1633 i = bb2 < bd2 ? bb2 : bd2;
1634 if (i > bs2)
1635 i = bs2;
1636 if (i > 0) {
1637 bb2 -= i;
1638 bd2 -= i;
1639 bs2 -= i;
1641 if (bb5 > 0) {
1642 bs = pow5mult(bs, bb5);
1643 if (bs == NULL) {
1644 Bfree(bb);
1645 Bfree(bd);
1646 Bfree(bd0);
1647 goto failed_malloc;
1649 bb1 = mult(bs, bb);
1650 Bfree(bb);
1651 bb = bb1;
1652 if (bb == NULL) {
1653 Bfree(bs);
1654 Bfree(bd);
1655 Bfree(bd0);
1656 goto failed_malloc;
1659 if (bb2 > 0) {
1660 bb = lshift(bb, bb2);
1661 if (bb == NULL) {
1662 Bfree(bs);
1663 Bfree(bd);
1664 Bfree(bd0);
1665 goto failed_malloc;
1668 if (bd5 > 0) {
1669 bd = pow5mult(bd, bd5);
1670 if (bd == NULL) {
1671 Bfree(bb);
1672 Bfree(bs);
1673 Bfree(bd0);
1674 goto failed_malloc;
1677 if (bd2 > 0) {
1678 bd = lshift(bd, bd2);
1679 if (bd == NULL) {
1680 Bfree(bb);
1681 Bfree(bs);
1682 Bfree(bd0);
1683 goto failed_malloc;
1686 if (bs2 > 0) {
1687 bs = lshift(bs, bs2);
1688 if (bs == NULL) {
1689 Bfree(bb);
1690 Bfree(bd);
1691 Bfree(bd0);
1692 goto failed_malloc;
1695 delta = diff(bb, bd);
1696 if (delta == NULL) {
1697 Bfree(bb);
1698 Bfree(bs);
1699 Bfree(bd);
1700 Bfree(bd0);
1701 goto failed_malloc;
1703 bc.dsign = delta->sign;
1704 delta->sign = 0;
1705 i = cmp(delta, bs);
1706 if (bc.nd > nd && i <= 0) {
1707 if (bc.dsign)
1708 break; /* Must use bigcomp(). */
1710 bc.nd = nd;
1711 i = -1; /* Discarded digits make delta smaller. */
1715 if (i < 0) {
1716 /* Error is less than half an ulp -- check for
1717 * special case of mantissa a power of two.
1719 if (bc.dsign || word1(&rv) || word0(&rv) & Bndry_mask
1720 || (word0(&rv) & Exp_mask) <= (2*P+1)*Exp_msk1
1722 break;
1724 if (!delta->x[0] && delta->wds <= 1) {
1725 /* exact result */
1726 break;
1728 delta = lshift(delta,Log2P);
1729 if (delta == NULL) {
1730 Bfree(bb);
1731 Bfree(bs);
1732 Bfree(bd);
1733 Bfree(bd0);
1734 goto failed_malloc;
1736 if (cmp(delta, bs) > 0)
1737 goto drop_down;
1738 break;
1740 if (i == 0) {
1741 /* exactly half-way between */
1742 if (bc.dsign) {
1743 if ((word0(&rv) & Bndry_mask1) == Bndry_mask1
1744 && word1(&rv) == (
1745 (bc.scale &&
1746 (y = word0(&rv) & Exp_mask) <= 2*P*Exp_msk1) ?
1747 (0xffffffff & (0xffffffff << (2*P+1-(y>>Exp_shift)))) :
1748 0xffffffff)) {
1749 /*boundary case -- increment exponent*/
1750 word0(&rv) = (word0(&rv) & Exp_mask)
1751 + Exp_msk1
1753 word1(&rv) = 0;
1754 bc.dsign = 0;
1755 break;
1758 else if (!(word0(&rv) & Bndry_mask) && !word1(&rv)) {
1759 drop_down:
1760 /* boundary case -- decrement exponent */
1761 if (bc.scale) {
1762 L = word0(&rv) & Exp_mask;
1763 if (L <= (2*P+1)*Exp_msk1) {
1764 if (L > (P+2)*Exp_msk1)
1765 /* round even ==> */
1766 /* accept rv */
1767 break;
1768 /* rv = smallest denormal */
1769 if (bc.nd >nd)
1770 break;
1771 goto undfl;
1774 L = (word0(&rv) & Exp_mask) - Exp_msk1;
1775 word0(&rv) = L | Bndry_mask1;
1776 word1(&rv) = 0xffffffff;
1777 break;
1779 if (!(word1(&rv) & LSB))
1780 break;
1781 if (bc.dsign)
1782 dval(&rv) += ulp(&rv);
1783 else {
1784 dval(&rv) -= ulp(&rv);
1785 if (!dval(&rv)) {
1786 if (bc.nd >nd)
1787 break;
1788 goto undfl;
1791 bc.dsign = 1 - bc.dsign;
1792 break;
1794 if ((aadj = ratio(delta, bs)) <= 2.) {
1795 if (bc.dsign)
1796 aadj = aadj1 = 1.;
1797 else if (word1(&rv) || word0(&rv) & Bndry_mask) {
1798 if (word1(&rv) == Tiny1 && !word0(&rv)) {
1799 if (bc.nd >nd)
1800 break;
1801 goto undfl;
1803 aadj = 1.;
1804 aadj1 = -1.;
1806 else {
1807 /* special case -- power of FLT_RADIX to be */
1808 /* rounded down... */
1810 if (aadj < 2./FLT_RADIX)
1811 aadj = 1./FLT_RADIX;
1812 else
1813 aadj *= 0.5;
1814 aadj1 = -aadj;
1817 else {
1818 aadj *= 0.5;
1819 aadj1 = bc.dsign ? aadj : -aadj;
1820 if (Flt_Rounds == 0)
1821 aadj1 += 0.5;
1823 y = word0(&rv) & Exp_mask;
1825 /* Check for overflow */
1827 if (y == Exp_msk1*(DBL_MAX_EXP+Bias-1)) {
1828 dval(&rv0) = dval(&rv);
1829 word0(&rv) -= P*Exp_msk1;
1830 adj.d = aadj1 * ulp(&rv);
1831 dval(&rv) += adj.d;
1832 if ((word0(&rv) & Exp_mask) >=
1833 Exp_msk1*(DBL_MAX_EXP+Bias-P)) {
1834 if (word0(&rv0) == Big0 && word1(&rv0) == Big1)
1835 goto ovfl;
1836 word0(&rv) = Big0;
1837 word1(&rv) = Big1;
1838 goto cont;
1840 else
1841 word0(&rv) += P*Exp_msk1;
1843 else {
1844 if (bc.scale && y <= 2*P*Exp_msk1) {
1845 if (aadj <= 0x7fffffff) {
1846 if ((z = (ULong)aadj) <= 0)
1847 z = 1;
1848 aadj = z;
1849 aadj1 = bc.dsign ? aadj : -aadj;
1851 dval(&aadj2) = aadj1;
1852 word0(&aadj2) += (2*P+1)*Exp_msk1 - y;
1853 aadj1 = dval(&aadj2);
1855 adj.d = aadj1 * ulp(&rv);
1856 dval(&rv) += adj.d;
1858 z = word0(&rv) & Exp_mask;
1859 if (bc.nd == nd) {
1860 if (!bc.scale)
1861 if (y == z) {
1862 /* Can we stop now? */
1863 L = (Long)aadj;
1864 aadj -= L;
1865 /* The tolerances below are conservative. */
1866 if (bc.dsign || word1(&rv) || word0(&rv) & Bndry_mask) {
1867 if (aadj < .4999999 || aadj > .5000001)
1868 break;
1870 else if (aadj < .4999999/FLT_RADIX)
1871 break;
1874 cont:
1875 Bfree(bb);
1876 Bfree(bd);
1877 Bfree(bs);
1878 Bfree(delta);
1880 Bfree(bb);
1881 Bfree(bd);
1882 Bfree(bs);
1883 Bfree(bd0);
1884 Bfree(delta);
1885 if (bc.nd > nd) {
1886 error = bigcomp(&rv, s0, &bc);
1887 if (error)
1888 goto failed_malloc;
1891 if (bc.scale) {
1892 word0(&rv0) = Exp_1 - 2*P*Exp_msk1;
1893 word1(&rv0) = 0;
1894 dval(&rv) *= dval(&rv0);
1895 /* try to avoid the bug of testing an 8087 register value */
1896 if (!(word0(&rv) & Exp_mask))
1897 errno = ERANGE;
1899 ret:
1900 if (se)
1901 *se = (char *)s;
1902 return sign ? -dval(&rv) : dval(&rv);
1904 failed_malloc:
1905 if (se)
1906 *se = (char *)s00;
1907 errno = ENOMEM;
1908 return -1.0;
1911 static char *
1912 rv_alloc(int i)
1914 int j, k, *r;
1916 j = sizeof(ULong);
1917 for(k = 0;
1918 sizeof(Bigint) - sizeof(ULong) - sizeof(int) + j <= (unsigned)i;
1919 j <<= 1)
1920 k++;
1921 r = (int*)Balloc(k);
1922 if (r == NULL)
1923 return NULL;
1924 *r = k;
1925 return (char *)(r+1);
1928 static char *
1929 nrv_alloc(char *s, char **rve, int n)
1931 char *rv, *t;
1933 rv = rv_alloc(n);
1934 if (rv == NULL)
1935 return NULL;
1936 t = rv;
1937 while((*t = *s++)) t++;
1938 if (rve)
1939 *rve = t;
1940 return rv;
1943 /* freedtoa(s) must be used to free values s returned by dtoa
1944 * when MULTIPLE_THREADS is #defined. It should be used in all cases,
1945 * but for consistency with earlier versions of dtoa, it is optional
1946 * when MULTIPLE_THREADS is not defined.
1949 void
1950 _Py_dg_freedtoa(char *s)
1952 Bigint *b = (Bigint *)((int *)s - 1);
1953 b->maxwds = 1 << (b->k = *(int*)b);
1954 Bfree(b);
1957 /* dtoa for IEEE arithmetic (dmg): convert double to ASCII string.
1959 * Inspired by "How to Print Floating-Point Numbers Accurately" by
1960 * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 112-126].
1962 * Modifications:
1963 * 1. Rather than iterating, we use a simple numeric overestimate
1964 * to determine k = floor(log10(d)). We scale relevant
1965 * quantities using O(log2(k)) rather than O(k) multiplications.
1966 * 2. For some modes > 2 (corresponding to ecvt and fcvt), we don't
1967 * try to generate digits strictly left to right. Instead, we
1968 * compute with fewer bits and propagate the carry if necessary
1969 * when rounding the final digit up. This is often faster.
1970 * 3. Under the assumption that input will be rounded nearest,
1971 * mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22.
1972 * That is, we allow equality in stopping tests when the
1973 * round-nearest rule will give the same floating-point value
1974 * as would satisfaction of the stopping test with strict
1975 * inequality.
1976 * 4. We remove common factors of powers of 2 from relevant
1977 * quantities.
1978 * 5. When converting floating-point integers less than 1e16,
1979 * we use floating-point arithmetic rather than resorting
1980 * to multiple-precision integers.
1981 * 6. When asked to produce fewer than 15 digits, we first try
1982 * to get by with floating-point arithmetic; we resort to
1983 * multiple-precision integer arithmetic only if we cannot
1984 * guarantee that the floating-point calculation has given
1985 * the correctly rounded result. For k requested digits and
1986 * "uniformly" distributed input, the probability is
1987 * something like 10^(k-15) that we must resort to the Long
1988 * calculation.
1991 /* Additional notes (METD): (1) returns NULL on failure. (2) to avoid memory
1992 leakage, a successful call to _Py_dg_dtoa should always be matched by a
1993 call to _Py_dg_freedtoa. */
1995 char *
1996 _Py_dg_dtoa(double dd, int mode, int ndigits,
1997 int *decpt, int *sign, char **rve)
1999 /* Arguments ndigits, decpt, sign are similar to those
2000 of ecvt and fcvt; trailing zeros are suppressed from
2001 the returned string. If not null, *rve is set to point
2002 to the end of the return value. If d is +-Infinity or NaN,
2003 then *decpt is set to 9999.
2005 mode:
2006 0 ==> shortest string that yields d when read in
2007 and rounded to nearest.
2008 1 ==> like 0, but with Steele & White stopping rule;
2009 e.g. with IEEE P754 arithmetic , mode 0 gives
2010 1e23 whereas mode 1 gives 9.999999999999999e22.
2011 2 ==> max(1,ndigits) significant digits. This gives a
2012 return value similar to that of ecvt, except
2013 that trailing zeros are suppressed.
2014 3 ==> through ndigits past the decimal point. This
2015 gives a return value similar to that from fcvt,
2016 except that trailing zeros are suppressed, and
2017 ndigits can be negative.
2018 4,5 ==> similar to 2 and 3, respectively, but (in
2019 round-nearest mode) with the tests of mode 0 to
2020 possibly return a shorter string that rounds to d.
2021 With IEEE arithmetic and compilation with
2022 -DHonor_FLT_ROUNDS, modes 4 and 5 behave the same
2023 as modes 2 and 3 when FLT_ROUNDS != 1.
2024 6-9 ==> Debugging modes similar to mode - 4: don't try
2025 fast floating-point estimate (if applicable).
2027 Values of mode other than 0-9 are treated as mode 0.
2029 Sufficient space is allocated to the return value
2030 to hold the suppressed trailing zeros.
2033 int bbits, b2, b5, be, dig, i, ieps, ilim, ilim0, ilim1,
2034 j, j1, k, k0, k_check, leftright, m2, m5, s2, s5,
2035 spec_case, try_quick;
2036 Long L;
2037 int denorm;
2038 ULong x;
2039 Bigint *b, *b1, *delta, *mlo, *mhi, *S;
2040 U d2, eps, u;
2041 double ds;
2042 char *s, *s0;
2044 /* set pointers to NULL, to silence gcc compiler warnings and make
2045 cleanup easier on error */
2046 mlo = mhi = b = S = 0;
2047 s0 = 0;
2049 u.d = dd;
2050 if (word0(&u) & Sign_bit) {
2051 /* set sign for everything, including 0's and NaNs */
2052 *sign = 1;
2053 word0(&u) &= ~Sign_bit; /* clear sign bit */
2055 else
2056 *sign = 0;
2058 /* quick return for Infinities, NaNs and zeros */
2059 if ((word0(&u) & Exp_mask) == Exp_mask)
2061 /* Infinity or NaN */
2062 *decpt = 9999;
2063 if (!word1(&u) && !(word0(&u) & 0xfffff))
2064 return nrv_alloc("Infinity", rve, 8);
2065 return nrv_alloc("NaN", rve, 3);
2067 if (!dval(&u)) {
2068 *decpt = 1;
2069 return nrv_alloc("0", rve, 1);
2072 /* compute k = floor(log10(d)). The computation may leave k
2073 one too large, but should never leave k too small. */
2074 b = d2b(&u, &be, &bbits);
2075 if (b == NULL)
2076 goto failed_malloc;
2077 if ((i = (int)(word0(&u) >> Exp_shift1 & (Exp_mask>>Exp_shift1)))) {
2078 dval(&d2) = dval(&u);
2079 word0(&d2) &= Frac_mask1;
2080 word0(&d2) |= Exp_11;
2082 /* log(x) ~=~ log(1.5) + (x-1.5)/1.5
2083 * log10(x) = log(x) / log(10)
2084 * ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10))
2085 * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2)
2087 * This suggests computing an approximation k to log10(d) by
2089 * k = (i - Bias)*0.301029995663981
2090 * + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 );
2092 * We want k to be too large rather than too small.
2093 * The error in the first-order Taylor series approximation
2094 * is in our favor, so we just round up the constant enough
2095 * to compensate for any error in the multiplication of
2096 * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077,
2097 * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14,
2098 * adding 1e-13 to the constant term more than suffices.
2099 * Hence we adjust the constant term to 0.1760912590558.
2100 * (We could get a more accurate k by invoking log10,
2101 * but this is probably not worthwhile.)
2104 i -= Bias;
2105 denorm = 0;
2107 else {
2108 /* d is denormalized */
2110 i = bbits + be + (Bias + (P-1) - 1);
2111 x = i > 32 ? word0(&u) << (64 - i) | word1(&u) >> (i - 32)
2112 : word1(&u) << (32 - i);
2113 dval(&d2) = x;
2114 word0(&d2) -= 31*Exp_msk1; /* adjust exponent */
2115 i -= (Bias + (P-1) - 1) + 1;
2116 denorm = 1;
2118 ds = (dval(&d2)-1.5)*0.289529654602168 + 0.1760912590558 +
2119 i*0.301029995663981;
2120 k = (int)ds;
2121 if (ds < 0. && ds != k)
2122 k--; /* want k = floor(ds) */
2123 k_check = 1;
2124 if (k >= 0 && k <= Ten_pmax) {
2125 if (dval(&u) < tens[k])
2126 k--;
2127 k_check = 0;
2129 j = bbits - i - 1;
2130 if (j >= 0) {
2131 b2 = 0;
2132 s2 = j;
2134 else {
2135 b2 = -j;
2136 s2 = 0;
2138 if (k >= 0) {
2139 b5 = 0;
2140 s5 = k;
2141 s2 += k;
2143 else {
2144 b2 -= k;
2145 b5 = -k;
2146 s5 = 0;
2148 if (mode < 0 || mode > 9)
2149 mode = 0;
2151 try_quick = 1;
2153 if (mode > 5) {
2154 mode -= 4;
2155 try_quick = 0;
2157 leftright = 1;
2158 ilim = ilim1 = -1; /* Values for cases 0 and 1; done here to */
2159 /* silence erroneous "gcc -Wall" warning. */
2160 switch(mode) {
2161 case 0:
2162 case 1:
2163 i = 18;
2164 ndigits = 0;
2165 break;
2166 case 2:
2167 leftright = 0;
2168 /* no break */
2169 case 4:
2170 if (ndigits <= 0)
2171 ndigits = 1;
2172 ilim = ilim1 = i = ndigits;
2173 break;
2174 case 3:
2175 leftright = 0;
2176 /* no break */
2177 case 5:
2178 i = ndigits + k + 1;
2179 ilim = i;
2180 ilim1 = i - 1;
2181 if (i <= 0)
2182 i = 1;
2184 s0 = rv_alloc(i);
2185 if (s0 == NULL)
2186 goto failed_malloc;
2187 s = s0;
2190 if (ilim >= 0 && ilim <= Quick_max && try_quick) {
2192 /* Try to get by with floating-point arithmetic. */
2194 i = 0;
2195 dval(&d2) = dval(&u);
2196 k0 = k;
2197 ilim0 = ilim;
2198 ieps = 2; /* conservative */
2199 if (k > 0) {
2200 ds = tens[k&0xf];
2201 j = k >> 4;
2202 if (j & Bletch) {
2203 /* prevent overflows */
2204 j &= Bletch - 1;
2205 dval(&u) /= bigtens[n_bigtens-1];
2206 ieps++;
2208 for(; j; j >>= 1, i++)
2209 if (j & 1) {
2210 ieps++;
2211 ds *= bigtens[i];
2213 dval(&u) /= ds;
2215 else if ((j1 = -k)) {
2216 dval(&u) *= tens[j1 & 0xf];
2217 for(j = j1 >> 4; j; j >>= 1, i++)
2218 if (j & 1) {
2219 ieps++;
2220 dval(&u) *= bigtens[i];
2223 if (k_check && dval(&u) < 1. && ilim > 0) {
2224 if (ilim1 <= 0)
2225 goto fast_failed;
2226 ilim = ilim1;
2227 k--;
2228 dval(&u) *= 10.;
2229 ieps++;
2231 dval(&eps) = ieps*dval(&u) + 7.;
2232 word0(&eps) -= (P-1)*Exp_msk1;
2233 if (ilim == 0) {
2234 S = mhi = 0;
2235 dval(&u) -= 5.;
2236 if (dval(&u) > dval(&eps))
2237 goto one_digit;
2238 if (dval(&u) < -dval(&eps))
2239 goto no_digits;
2240 goto fast_failed;
2242 if (leftright) {
2243 /* Use Steele & White method of only
2244 * generating digits needed.
2246 dval(&eps) = 0.5/tens[ilim-1] - dval(&eps);
2247 for(i = 0;;) {
2248 L = (Long)dval(&u);
2249 dval(&u) -= L;
2250 *s++ = '0' + (int)L;
2251 if (dval(&u) < dval(&eps))
2252 goto ret1;
2253 if (1. - dval(&u) < dval(&eps))
2254 goto bump_up;
2255 if (++i >= ilim)
2256 break;
2257 dval(&eps) *= 10.;
2258 dval(&u) *= 10.;
2261 else {
2262 /* Generate ilim digits, then fix them up. */
2263 dval(&eps) *= tens[ilim-1];
2264 for(i = 1;; i++, dval(&u) *= 10.) {
2265 L = (Long)(dval(&u));
2266 if (!(dval(&u) -= L))
2267 ilim = i;
2268 *s++ = '0' + (int)L;
2269 if (i == ilim) {
2270 if (dval(&u) > 0.5 + dval(&eps))
2271 goto bump_up;
2272 else if (dval(&u) < 0.5 - dval(&eps)) {
2273 while(*--s == '0');
2274 s++;
2275 goto ret1;
2277 break;
2281 fast_failed:
2282 s = s0;
2283 dval(&u) = dval(&d2);
2284 k = k0;
2285 ilim = ilim0;
2288 /* Do we have a "small" integer? */
2290 if (be >= 0 && k <= Int_max) {
2291 /* Yes. */
2292 ds = tens[k];
2293 if (ndigits < 0 && ilim <= 0) {
2294 S = mhi = 0;
2295 if (ilim < 0 || dval(&u) <= 5*ds)
2296 goto no_digits;
2297 goto one_digit;
2299 for(i = 1;; i++, dval(&u) *= 10.) {
2300 L = (Long)(dval(&u) / ds);
2301 dval(&u) -= L*ds;
2302 *s++ = '0' + (int)L;
2303 if (!dval(&u)) {
2304 break;
2306 if (i == ilim) {
2307 dval(&u) += dval(&u);
2308 if (dval(&u) > ds || (dval(&u) == ds && L & 1)) {
2309 bump_up:
2310 while(*--s == '9')
2311 if (s == s0) {
2312 k++;
2313 *s = '0';
2314 break;
2316 ++*s++;
2318 break;
2321 goto ret1;
2324 m2 = b2;
2325 m5 = b5;
2326 if (leftright) {
2328 denorm ? be + (Bias + (P-1) - 1 + 1) :
2329 1 + P - bbits;
2330 b2 += i;
2331 s2 += i;
2332 mhi = i2b(1);
2333 if (mhi == NULL)
2334 goto failed_malloc;
2336 if (m2 > 0 && s2 > 0) {
2337 i = m2 < s2 ? m2 : s2;
2338 b2 -= i;
2339 m2 -= i;
2340 s2 -= i;
2342 if (b5 > 0) {
2343 if (leftright) {
2344 if (m5 > 0) {
2345 mhi = pow5mult(mhi, m5);
2346 if (mhi == NULL)
2347 goto failed_malloc;
2348 b1 = mult(mhi, b);
2349 Bfree(b);
2350 b = b1;
2351 if (b == NULL)
2352 goto failed_malloc;
2354 if ((j = b5 - m5)) {
2355 b = pow5mult(b, j);
2356 if (b == NULL)
2357 goto failed_malloc;
2360 else {
2361 b = pow5mult(b, b5);
2362 if (b == NULL)
2363 goto failed_malloc;
2366 S = i2b(1);
2367 if (S == NULL)
2368 goto failed_malloc;
2369 if (s5 > 0) {
2370 S = pow5mult(S, s5);
2371 if (S == NULL)
2372 goto failed_malloc;
2375 /* Check for special case that d is a normalized power of 2. */
2377 spec_case = 0;
2378 if ((mode < 2 || leftright)
2380 if (!word1(&u) && !(word0(&u) & Bndry_mask)
2381 && word0(&u) & (Exp_mask & ~Exp_msk1)
2383 /* The special case */
2384 b2 += Log2P;
2385 s2 += Log2P;
2386 spec_case = 1;
2390 /* Arrange for convenient computation of quotients:
2391 * shift left if necessary so divisor has 4 leading 0 bits.
2393 * Perhaps we should just compute leading 28 bits of S once
2394 * and for all and pass them and a shift to quorem, so it
2395 * can do shifts and ors to compute the numerator for q.
2397 if ((i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0x1f))
2398 i = 32 - i;
2399 #define iInc 28
2400 i = dshift(S, s2);
2401 b2 += i;
2402 m2 += i;
2403 s2 += i;
2404 if (b2 > 0) {
2405 b = lshift(b, b2);
2406 if (b == NULL)
2407 goto failed_malloc;
2409 if (s2 > 0) {
2410 S = lshift(S, s2);
2411 if (S == NULL)
2412 goto failed_malloc;
2414 if (k_check) {
2415 if (cmp(b,S) < 0) {
2416 k--;
2417 b = multadd(b, 10, 0); /* we botched the k estimate */
2418 if (b == NULL)
2419 goto failed_malloc;
2420 if (leftright) {
2421 mhi = multadd(mhi, 10, 0);
2422 if (mhi == NULL)
2423 goto failed_malloc;
2425 ilim = ilim1;
2428 if (ilim <= 0 && (mode == 3 || mode == 5)) {
2429 if (ilim < 0) {
2430 /* no digits, fcvt style */
2431 no_digits:
2432 k = -1 - ndigits;
2433 goto ret;
2435 else {
2436 S = multadd(S, 5, 0);
2437 if (S == NULL)
2438 goto failed_malloc;
2439 if (cmp(b, S) <= 0)
2440 goto no_digits;
2442 one_digit:
2443 *s++ = '1';
2444 k++;
2445 goto ret;
2447 if (leftright) {
2448 if (m2 > 0) {
2449 mhi = lshift(mhi, m2);
2450 if (mhi == NULL)
2451 goto failed_malloc;
2454 /* Compute mlo -- check for special case
2455 * that d is a normalized power of 2.
2458 mlo = mhi;
2459 if (spec_case) {
2460 mhi = Balloc(mhi->k);
2461 if (mhi == NULL)
2462 goto failed_malloc;
2463 Bcopy(mhi, mlo);
2464 mhi = lshift(mhi, Log2P);
2465 if (mhi == NULL)
2466 goto failed_malloc;
2469 for(i = 1;;i++) {
2470 dig = quorem(b,S) + '0';
2471 /* Do we yet have the shortest decimal string
2472 * that will round to d?
2474 j = cmp(b, mlo);
2475 delta = diff(S, mhi);
2476 if (delta == NULL)
2477 goto failed_malloc;
2478 j1 = delta->sign ? 1 : cmp(b, delta);
2479 Bfree(delta);
2480 if (j1 == 0 && mode != 1 && !(word1(&u) & 1)
2482 if (dig == '9')
2483 goto round_9_up;
2484 if (j > 0)
2485 dig++;
2486 *s++ = dig;
2487 goto ret;
2489 if (j < 0 || (j == 0 && mode != 1
2490 && !(word1(&u) & 1)
2491 )) {
2492 if (!b->x[0] && b->wds <= 1) {
2493 goto accept_dig;
2495 if (j1 > 0) {
2496 b = lshift(b, 1);
2497 if (b == NULL)
2498 goto failed_malloc;
2499 j1 = cmp(b, S);
2500 if ((j1 > 0 || (j1 == 0 && dig & 1))
2501 && dig++ == '9')
2502 goto round_9_up;
2504 accept_dig:
2505 *s++ = dig;
2506 goto ret;
2508 if (j1 > 0) {
2509 if (dig == '9') { /* possible if i == 1 */
2510 round_9_up:
2511 *s++ = '9';
2512 goto roundoff;
2514 *s++ = dig + 1;
2515 goto ret;
2517 *s++ = dig;
2518 if (i == ilim)
2519 break;
2520 b = multadd(b, 10, 0);
2521 if (b == NULL)
2522 goto failed_malloc;
2523 if (mlo == mhi) {
2524 mlo = mhi = multadd(mhi, 10, 0);
2525 if (mlo == NULL)
2526 goto failed_malloc;
2528 else {
2529 mlo = multadd(mlo, 10, 0);
2530 if (mlo == NULL)
2531 goto failed_malloc;
2532 mhi = multadd(mhi, 10, 0);
2533 if (mhi == NULL)
2534 goto failed_malloc;
2538 else
2539 for(i = 1;; i++) {
2540 *s++ = dig = quorem(b,S) + '0';
2541 if (!b->x[0] && b->wds <= 1) {
2542 goto ret;
2544 if (i >= ilim)
2545 break;
2546 b = multadd(b, 10, 0);
2547 if (b == NULL)
2548 goto failed_malloc;
2551 /* Round off last digit */
2553 b = lshift(b, 1);
2554 if (b == NULL)
2555 goto failed_malloc;
2556 j = cmp(b, S);
2557 if (j > 0 || (j == 0 && dig & 1)) {
2558 roundoff:
2559 while(*--s == '9')
2560 if (s == s0) {
2561 k++;
2562 *s++ = '1';
2563 goto ret;
2565 ++*s++;
2567 else {
2568 while(*--s == '0');
2569 s++;
2571 ret:
2572 Bfree(S);
2573 if (mhi) {
2574 if (mlo && mlo != mhi)
2575 Bfree(mlo);
2576 Bfree(mhi);
2578 ret1:
2579 Bfree(b);
2580 *s = 0;
2581 *decpt = k + 1;
2582 if (rve)
2583 *rve = s;
2584 return s0;
2585 failed_malloc:
2586 if (S)
2587 Bfree(S);
2588 if (mlo && mlo != mhi)
2589 Bfree(mlo);
2590 if (mhi)
2591 Bfree(mhi);
2592 if (b)
2593 Bfree(b);
2594 if (s0)
2595 _Py_dg_freedtoa(s0);
2596 return NULL;
2598 #ifdef __cplusplus
2600 #endif
2602 #endif /* PY_NO_SHORT_FLOAT_REPR */