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