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