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