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