/****************************************************************1*2* The author of this software is David M. Gay.3*4* Copyright (c) 1991, 2000, 2001 by Lucent Technologies.5*6* Permission to use, copy, modify, and distribute this software for any7* purpose without fee is hereby granted, provided that this entire notice8* is included in all copies of any software which is or includes a copy9* or modification of this software and in all copies of the supporting10* documentation for such software.11*12* THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED13* WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY14* REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY15* OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.16*17***************************************************************/1819/****************************************************************20* This is dtoa.c by David M. Gay, downloaded from21* http://www.netlib.org/fp/dtoa.c on April 15, 2009 and modified for22* inclusion into the Python core by Mark E. T. Dickinson and Eric V. Smith.23*24* Please remember to check http://www.netlib.org/fp regularly (and especially25* before any Python release) for bugfixes and updates.26*27* The major modifications from Gay's original code are as follows:28*29* 0. The original code has been specialized to Python's needs by removing30* many of the #ifdef'd sections. In particular, code to support VAX and31* IBM floating-point formats, hex NaNs, hex floats, locale-aware32* treatment of the decimal point, and setting of the inexact flag have33* been removed.34*35* 1. We use PyMem_Malloc and PyMem_Free in place of malloc and free.36*37* 2. The public functions strtod, dtoa and freedtoa all now have38* a _Py_dg_ prefix.39*40* 3. Instead of assuming that PyMem_Malloc always succeeds, we thread41* PyMem_Malloc failures through the code. The functions42*43* Balloc, multadd, s2b, i2b, mult, pow5mult, lshift, diff, d2b44*45* of return type *Bigint all return NULL to indicate a malloc failure.46* Similarly, rv_alloc and nrv_alloc (return type char *) return NULL on47* failure. bigcomp now has return type int (it used to be void) and48* returns -1 on failure and 0 otherwise. _Py_dg_dtoa returns NULL49* on failure. _Py_dg_strtod indicates failure due to malloc failure50* by returning -1.0, setting errno=ENOMEM and *se to s00.51*52* 4. The static variable dtoa_result has been removed. Callers of53* _Py_dg_dtoa are expected to call _Py_dg_freedtoa to free54* the memory allocated by _Py_dg_dtoa.55*56* 5. The code has been reformatted to better fit with Python's57* C style guide (PEP 7).58*59* 6. A bug in the memory allocation has been fixed: to avoid FREEing memory60* that hasn't been MALLOC'ed, private_mem should only be used when k <=61* Kmax.62*63* 7. _Py_dg_strtod has been modified so that it doesn't accept strings with64* leading whitespace.65*66* 8. A corner case where _Py_dg_dtoa didn't strip trailing zeros has been67* fixed. (bugs.python.org/issue40780)68*69***************************************************************/7071/* Please send bug reports for the original dtoa.c code to David M. Gay (dmg72* at acm dot org, with " at " changed at "@" and " dot " changed to ".").73* Please report bugs for this modified version using the Python issue tracker74* (http://bugs.python.org). */7576/* On a machine with IEEE extended-precision registers, it is77* necessary to specify double-precision (53-bit) rounding precision78* before invoking strtod or dtoa. If the machine uses (the equivalent79* of) Intel 80x87 arithmetic, the call80* _control87(PC_53, MCW_PC);81* does this with many compilers. Whether this or another call is82* appropriate depends on the compiler; for this to work, it may be83* necessary to #include "float.h" or another system-dependent header84* file.85*/8687/* strtod for IEEE-, VAX-, and IBM-arithmetic machines.88*89* This strtod returns a nearest machine number to the input decimal90* string (or sets errno to ERANGE). With IEEE arithmetic, ties are91* broken by the IEEE round-even rule. Otherwise ties are broken by92* biased rounding (add half and chop).93*94* Inspired loosely by William D. Clinger's paper "How to Read Floating95* Point Numbers Accurately" [Proc. ACM SIGPLAN '90, pp. 92-101].96*97* Modifications:98*99* 1. We only require IEEE, IBM, or VAX double-precision100* arithmetic (not IEEE double-extended).101* 2. We get by with floating-point arithmetic in a case that102* Clinger missed -- when we're computing d * 10^n103* for a small integer d and the integer n is not too104* much larger than 22 (the maximum integer k for which105* we can represent 10^k exactly), we may be able to106* compute (d*10^k) * 10^(e-k) with just one roundoff.107* 3. Rather than a bit-at-a-time adjustment of the binary108* result in the hard case, we use floating-point109* arithmetic to determine the adjustment to within110* one bit; only in really hard cases do we need to111* compute a second residual.112* 4. Because of 3., we don't need a large table of powers of 10113* for ten-to-e (just some small tables, e.g. of 10^k114* for 0 <= k <= 22).115*/116117/* Linking of Python's #defines to Gay's #defines starts here. */118119#include "Python.h"120#include "pycore_dtoa.h" // _PY_SHORT_FLOAT_REPR121#include "pycore_pystate.h" // _PyInterpreterState_GET()122#include <stdlib.h> // exit()123124/* if _PY_SHORT_FLOAT_REPR == 0, then don't even try to compile125the following code */126#if _PY_SHORT_FLOAT_REPR == 1127128#include "float.h"129130#define MALLOC PyMem_Malloc131#define FREE PyMem_Free132133/* This code should also work for ARM mixed-endian format on little-endian134machines, where doubles have byte order 45670123 (in increasing address135order, 0 being the least significant byte). */136#ifdef DOUBLE_IS_LITTLE_ENDIAN_IEEE754137# define IEEE_8087138#endif139#if defined(DOUBLE_IS_BIG_ENDIAN_IEEE754) || \140defined(DOUBLE_IS_ARM_MIXED_ENDIAN_IEEE754)141# define IEEE_MC68k142#endif143#if defined(IEEE_8087) + defined(IEEE_MC68k) != 1144#error "Exactly one of IEEE_8087 or IEEE_MC68k should be defined."145#endif146147/* The code below assumes that the endianness of integers matches the148endianness of the two 32-bit words of a double. Check this. */149#if defined(WORDS_BIGENDIAN) && (defined(DOUBLE_IS_LITTLE_ENDIAN_IEEE754) || \150defined(DOUBLE_IS_ARM_MIXED_ENDIAN_IEEE754))151#error "doubles and ints have incompatible endianness"152#endif153154#if !defined(WORDS_BIGENDIAN) && defined(DOUBLE_IS_BIG_ENDIAN_IEEE754)155#error "doubles and ints have incompatible endianness"156#endif157158159// ULong is defined in pycore_dtoa.h.160typedef int32_t Long;161typedef uint64_t ULLong;162163#undef DEBUG164#ifdef Py_DEBUG165#define DEBUG166#endif167168/* End Python #define linking */169170#ifdef DEBUG171#define Bug(x) {fprintf(stderr, "%s\n", x); exit(1);}172#endif173174#ifdef __cplusplus175extern "C" {176#endif177178typedef union { double d; ULong L[2]; } U;179180#ifdef IEEE_8087181#define word0(x) (x)->L[1]182#define word1(x) (x)->L[0]183#else184#define word0(x) (x)->L[0]185#define word1(x) (x)->L[1]186#endif187#define dval(x) (x)->d188189#ifndef STRTOD_DIGLIM190#define STRTOD_DIGLIM 40191#endif192193/* maximum permitted exponent value for strtod; exponents larger than194MAX_ABS_EXP in absolute value get truncated to +-MAX_ABS_EXP. MAX_ABS_EXP195should fit into an int. */196#ifndef MAX_ABS_EXP197#define MAX_ABS_EXP 1100000000U198#endif199/* Bound on length of pieces of input strings in _Py_dg_strtod; specifically,200this is used to bound the total number of digits ignoring leading zeros and201the number of digits that follow the decimal point. Ideally, MAX_DIGITS202should satisfy MAX_DIGITS + 400 < MAX_ABS_EXP; that ensures that the203exponent clipping in _Py_dg_strtod can't affect the value of the output. */204#ifndef MAX_DIGITS205#define MAX_DIGITS 1000000000U206#endif207208/* Guard against trying to use the above values on unusual platforms with ints209* of width less than 32 bits. */210#if MAX_ABS_EXP > INT_MAX211#error "MAX_ABS_EXP should fit in an int"212#endif213#if MAX_DIGITS > INT_MAX214#error "MAX_DIGITS should fit in an int"215#endif216217/* The following definition of Storeinc is appropriate for MIPS processors.218* An alternative that might be better on some machines is219* #define Storeinc(a,b,c) (*a++ = b << 16 | c & 0xffff)220*/221#if defined(IEEE_8087)222#define Storeinc(a,b,c) (((unsigned short *)a)[1] = (unsigned short)b, \223((unsigned short *)a)[0] = (unsigned short)c, a++)224#else225#define Storeinc(a,b,c) (((unsigned short *)a)[0] = (unsigned short)b, \226((unsigned short *)a)[1] = (unsigned short)c, a++)227#endif228229/* #define P DBL_MANT_DIG */230/* Ten_pmax = floor(P*log(2)/log(5)) */231/* Bletch = (highest power of 2 < DBL_MAX_10_EXP) / 16 */232/* Quick_max = floor((P-1)*log(FLT_RADIX)/log(10) - 1) */233/* Int_max = floor(P*log(FLT_RADIX)/log(10) - 1) */234235#define Exp_shift 20236#define Exp_shift1 20237#define Exp_msk1 0x100000238#define Exp_msk11 0x100000239#define Exp_mask 0x7ff00000240#define P 53241#define Nbits 53242#define Bias 1023243#define Emax 1023244#define Emin (-1022)245#define Etiny (-1074) /* smallest denormal is 2**Etiny */246#define Exp_1 0x3ff00000247#define Exp_11 0x3ff00000248#define Ebits 11249#define Frac_mask 0xfffff250#define Frac_mask1 0xfffff251#define Ten_pmax 22252#define Bletch 0x10253#define Bndry_mask 0xfffff254#define Bndry_mask1 0xfffff255#define Sign_bit 0x80000000256#define Log2P 1257#define Tiny0 0258#define Tiny1 1259#define Quick_max 14260#define Int_max 14261262#ifndef Flt_Rounds263#ifdef FLT_ROUNDS264#define Flt_Rounds FLT_ROUNDS265#else266#define Flt_Rounds 1267#endif268#endif /*Flt_Rounds*/269270#define Rounding Flt_Rounds271272#define Big0 (Frac_mask1 | Exp_msk1*(DBL_MAX_EXP+Bias-1))273#define Big1 0xffffffff274275/* Bits of the representation of positive infinity. */276277#define POSINF_WORD0 0x7ff00000278#define POSINF_WORD1 0279280/* struct BCinfo is used to pass information from _Py_dg_strtod to bigcomp */281282typedef struct BCinfo BCinfo;283struct284BCinfo {285int e0, nd, nd0, scale;286};287288#define FFFFFFFF 0xffffffffUL289290/* struct Bigint is used to represent arbitrary-precision integers. These291integers are stored in sign-magnitude format, with the magnitude stored as292an array of base 2**32 digits. Bigints are always normalized: if x is a293Bigint then x->wds >= 1, and either x->wds == 1 or x[wds-1] is nonzero.294295The Bigint fields are as follows:296297- next is a header used by Balloc and Bfree to keep track of lists298of freed Bigints; it's also used for the linked list of299powers of 5 of the form 5**2**i used by pow5mult.300- k indicates which pool this Bigint was allocated from301- maxwds is the maximum number of words space was allocated for302(usually maxwds == 2**k)303- sign is 1 for negative Bigints, 0 for positive. The sign is unused304(ignored on inputs, set to 0 on outputs) in almost all operations305involving Bigints: a notable exception is the diff function, which306ignores signs on inputs but sets the sign of the output correctly.307- wds is the actual number of significant words308- x contains the vector of words (digits) for this Bigint, from least309significant (x[0]) to most significant (x[wds-1]).310*/311312// struct Bigint is defined in pycore_dtoa.h.313typedef struct Bigint Bigint;314315#ifndef Py_USING_MEMORY_DEBUGGER316317/* Memory management: memory is allocated from, and returned to, Kmax+1 pools318of memory, where pool k (0 <= k <= Kmax) is for Bigints b with b->maxwds ==3191 << k. These pools are maintained as linked lists, with freelist[k]320pointing to the head of the list for pool k.321322On allocation, if there's no free slot in the appropriate pool, MALLOC is323called to get more memory. This memory is not returned to the system until324Python quits. There's also a private memory pool that's allocated from325in preference to using MALLOC.326327For Bigints with more than (1 << Kmax) digits (which implies at least 1233328decimal digits), memory is directly allocated using MALLOC, and freed using329FREE.330331XXX: it would be easy to bypass this memory-management system and332translate each call to Balloc into a call to PyMem_Malloc, and each333Bfree to PyMem_Free. Investigate whether this has any significant334performance on impact. */335336#define freelist interp->dtoa.freelist337#define private_mem interp->dtoa.preallocated338#define pmem_next interp->dtoa.preallocated_next339340/* Allocate space for a Bigint with up to 1<<k digits */341342static Bigint *343Balloc(int k)344{345int x;346Bigint *rv;347unsigned int len;348PyInterpreterState *interp = _PyInterpreterState_GET();349350if (k <= Bigint_Kmax && (rv = freelist[k]))351freelist[k] = rv->next;352else {353x = 1 << k;354len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1)355/sizeof(double);356if (k <= Bigint_Kmax &&357pmem_next - private_mem + len <= (Py_ssize_t)Bigint_PREALLOC_SIZE358) {359rv = (Bigint*)pmem_next;360pmem_next += len;361}362else {363rv = (Bigint*)MALLOC(len*sizeof(double));364if (rv == NULL)365return NULL;366}367rv->k = k;368rv->maxwds = x;369}370rv->sign = rv->wds = 0;371return rv;372}373374/* Free a Bigint allocated with Balloc */375376static void377Bfree(Bigint *v)378{379if (v) {380if (v->k > Bigint_Kmax)381FREE((void*)v);382else {383PyInterpreterState *interp = _PyInterpreterState_GET();384v->next = freelist[v->k];385freelist[v->k] = v;386}387}388}389390#undef pmem_next391#undef private_mem392#undef freelist393394#else395396/* Alternative versions of Balloc and Bfree that use PyMem_Malloc and397PyMem_Free directly in place of the custom memory allocation scheme above.398These are provided for the benefit of memory debugging tools like399Valgrind. */400401/* Allocate space for a Bigint with up to 1<<k digits */402403static Bigint *404Balloc(int k)405{406int x;407Bigint *rv;408unsigned int len;409410x = 1 << k;411len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1)412/sizeof(double);413414rv = (Bigint*)MALLOC(len*sizeof(double));415if (rv == NULL)416return NULL;417418rv->k = k;419rv->maxwds = x;420rv->sign = rv->wds = 0;421return rv;422}423424/* Free a Bigint allocated with Balloc */425426static void427Bfree(Bigint *v)428{429if (v) {430FREE((void*)v);431}432}433434#endif /* Py_USING_MEMORY_DEBUGGER */435436#define Bcopy(x,y) memcpy((char *)&x->sign, (char *)&y->sign, \437y->wds*sizeof(Long) + 2*sizeof(int))438439/* Multiply a Bigint b by m and add a. Either modifies b in place and returns440a pointer to the modified b, or Bfrees b and returns a pointer to a copy.441On failure, return NULL. In this case, b will have been already freed. */442443static Bigint *444multadd(Bigint *b, int m, int a) /* multiply by m and add a */445{446int i, wds;447ULong *x;448ULLong carry, y;449Bigint *b1;450451wds = b->wds;452x = b->x;453i = 0;454carry = a;455do {456y = *x * (ULLong)m + carry;457carry = y >> 32;458*x++ = (ULong)(y & FFFFFFFF);459}460while(++i < wds);461if (carry) {462if (wds >= b->maxwds) {463b1 = Balloc(b->k+1);464if (b1 == NULL){465Bfree(b);466return NULL;467}468Bcopy(b1, b);469Bfree(b);470b = b1;471}472b->x[wds++] = (ULong)carry;473b->wds = wds;474}475return b;476}477478/* convert a string s containing nd decimal digits (possibly containing a479decimal separator at position nd0, which is ignored) to a Bigint. This480function carries on where the parsing code in _Py_dg_strtod leaves off: on481entry, y9 contains the result of converting the first 9 digits. Returns482NULL on failure. */483484static Bigint *485s2b(const char *s, int nd0, int nd, ULong y9)486{487Bigint *b;488int i, k;489Long x, y;490491x = (nd + 8) / 9;492for(k = 0, y = 1; x > y; y <<= 1, k++) ;493b = Balloc(k);494if (b == NULL)495return NULL;496b->x[0] = y9;497b->wds = 1;498499if (nd <= 9)500return b;501502s += 9;503for (i = 9; i < nd0; i++) {504b = multadd(b, 10, *s++ - '0');505if (b == NULL)506return NULL;507}508s++;509for(; i < nd; i++) {510b = multadd(b, 10, *s++ - '0');511if (b == NULL)512return NULL;513}514return b;515}516517/* count leading 0 bits in the 32-bit integer x. */518519static int520hi0bits(ULong x)521{522int k = 0;523524if (!(x & 0xffff0000)) {525k = 16;526x <<= 16;527}528if (!(x & 0xff000000)) {529k += 8;530x <<= 8;531}532if (!(x & 0xf0000000)) {533k += 4;534x <<= 4;535}536if (!(x & 0xc0000000)) {537k += 2;538x <<= 2;539}540if (!(x & 0x80000000)) {541k++;542if (!(x & 0x40000000))543return 32;544}545return k;546}547548/* count trailing 0 bits in the 32-bit integer y, and shift y right by that549number of bits. */550551static int552lo0bits(ULong *y)553{554int k;555ULong x = *y;556557if (x & 7) {558if (x & 1)559return 0;560if (x & 2) {561*y = x >> 1;562return 1;563}564*y = x >> 2;565return 2;566}567k = 0;568if (!(x & 0xffff)) {569k = 16;570x >>= 16;571}572if (!(x & 0xff)) {573k += 8;574x >>= 8;575}576if (!(x & 0xf)) {577k += 4;578x >>= 4;579}580if (!(x & 0x3)) {581k += 2;582x >>= 2;583}584if (!(x & 1)) {585k++;586x >>= 1;587if (!x)588return 32;589}590*y = x;591return k;592}593594/* convert a small nonnegative integer to a Bigint */595596static Bigint *597i2b(int i)598{599Bigint *b;600601b = Balloc(1);602if (b == NULL)603return NULL;604b->x[0] = i;605b->wds = 1;606return b;607}608609/* multiply two Bigints. Returns a new Bigint, or NULL on failure. Ignores610the signs of a and b. */611612static Bigint *613mult(Bigint *a, Bigint *b)614{615Bigint *c;616int k, wa, wb, wc;617ULong *x, *xa, *xae, *xb, *xbe, *xc, *xc0;618ULong y;619ULLong carry, z;620621if ((!a->x[0] && a->wds == 1) || (!b->x[0] && b->wds == 1)) {622c = Balloc(0);623if (c == NULL)624return NULL;625c->wds = 1;626c->x[0] = 0;627return c;628}629630if (a->wds < b->wds) {631c = a;632a = b;633b = c;634}635k = a->k;636wa = a->wds;637wb = b->wds;638wc = wa + wb;639if (wc > a->maxwds)640k++;641c = Balloc(k);642if (c == NULL)643return NULL;644for(x = c->x, xa = x + wc; x < xa; x++)645*x = 0;646xa = a->x;647xae = xa + wa;648xb = b->x;649xbe = xb + wb;650xc0 = c->x;651for(; xb < xbe; xc0++) {652if ((y = *xb++)) {653x = xa;654xc = xc0;655carry = 0;656do {657z = *x++ * (ULLong)y + *xc + carry;658carry = z >> 32;659*xc++ = (ULong)(z & FFFFFFFF);660}661while(x < xae);662*xc = (ULong)carry;663}664}665for(xc0 = c->x, xc = xc0 + wc; wc > 0 && !*--xc; --wc) ;666c->wds = wc;667return c;668}669670#ifndef Py_USING_MEMORY_DEBUGGER671672/* multiply the Bigint b by 5**k. Returns a pointer to the result, or NULL on673failure; if the returned pointer is distinct from b then the original674Bigint b will have been Bfree'd. Ignores the sign of b. */675676static Bigint *677pow5mult(Bigint *b, int k)678{679Bigint *b1, *p5, *p51;680int i;681static const int p05[3] = { 5, 25, 125 };682683if ((i = k & 3)) {684b = multadd(b, p05[i-1], 0);685if (b == NULL)686return NULL;687}688689if (!(k >>= 2))690return b;691PyInterpreterState *interp = _PyInterpreterState_GET();692p5 = interp->dtoa.p5s;693if (!p5) {694/* first time */695p5 = i2b(625);696if (p5 == NULL) {697Bfree(b);698return NULL;699}700interp->dtoa.p5s = p5;701p5->next = 0;702}703for(;;) {704if (k & 1) {705b1 = mult(b, p5);706Bfree(b);707b = b1;708if (b == NULL)709return NULL;710}711if (!(k >>= 1))712break;713p51 = p5->next;714if (!p51) {715p51 = mult(p5,p5);716if (p51 == NULL) {717Bfree(b);718return NULL;719}720p51->next = 0;721p5->next = p51;722}723p5 = p51;724}725return b;726}727728#else729730/* Version of pow5mult that doesn't cache powers of 5. Provided for731the benefit of memory debugging tools like Valgrind. */732733static Bigint *734pow5mult(Bigint *b, int k)735{736Bigint *b1, *p5, *p51;737int i;738static const int p05[3] = { 5, 25, 125 };739740if ((i = k & 3)) {741b = multadd(b, p05[i-1], 0);742if (b == NULL)743return NULL;744}745746if (!(k >>= 2))747return b;748p5 = i2b(625);749if (p5 == NULL) {750Bfree(b);751return NULL;752}753754for(;;) {755if (k & 1) {756b1 = mult(b, p5);757Bfree(b);758b = b1;759if (b == NULL) {760Bfree(p5);761return NULL;762}763}764if (!(k >>= 1))765break;766p51 = mult(p5, p5);767Bfree(p5);768p5 = p51;769if (p5 == NULL) {770Bfree(b);771return NULL;772}773}774Bfree(p5);775return b;776}777778#endif /* Py_USING_MEMORY_DEBUGGER */779780/* shift a Bigint b left by k bits. Return a pointer to the shifted result,781or NULL on failure. If the returned pointer is distinct from b then the782original b will have been Bfree'd. Ignores the sign of b. */783784static Bigint *785lshift(Bigint *b, int k)786{787int i, k1, n, n1;788Bigint *b1;789ULong *x, *x1, *xe, z;790791if (!k || (!b->x[0] && b->wds == 1))792return b;793794n = k >> 5;795k1 = b->k;796n1 = n + b->wds + 1;797for(i = b->maxwds; n1 > i; i <<= 1)798k1++;799b1 = Balloc(k1);800if (b1 == NULL) {801Bfree(b);802return NULL;803}804x1 = b1->x;805for(i = 0; i < n; i++)806*x1++ = 0;807x = b->x;808xe = x + b->wds;809if (k &= 0x1f) {810k1 = 32 - k;811z = 0;812do {813*x1++ = *x << k | z;814z = *x++ >> k1;815}816while(x < xe);817if ((*x1 = z))818++n1;819}820else do821*x1++ = *x++;822while(x < xe);823b1->wds = n1 - 1;824Bfree(b);825return b1;826}827828/* Do a three-way compare of a and b, returning -1 if a < b, 0 if a == b and8291 if a > b. Ignores signs of a and b. */830831static int832cmp(Bigint *a, Bigint *b)833{834ULong *xa, *xa0, *xb, *xb0;835int i, j;836837i = a->wds;838j = b->wds;839#ifdef DEBUG840if (i > 1 && !a->x[i-1])841Bug("cmp called with a->x[a->wds-1] == 0");842if (j > 1 && !b->x[j-1])843Bug("cmp called with b->x[b->wds-1] == 0");844#endif845if (i -= j)846return i;847xa0 = a->x;848xa = xa0 + j;849xb0 = b->x;850xb = xb0 + j;851for(;;) {852if (*--xa != *--xb)853return *xa < *xb ? -1 : 1;854if (xa <= xa0)855break;856}857return 0;858}859860/* Take the difference of Bigints a and b, returning a new Bigint. Returns861NULL on failure. The signs of a and b are ignored, but the sign of the862result is set appropriately. */863864static Bigint *865diff(Bigint *a, Bigint *b)866{867Bigint *c;868int i, wa, wb;869ULong *xa, *xae, *xb, *xbe, *xc;870ULLong borrow, y;871872i = cmp(a,b);873if (!i) {874c = Balloc(0);875if (c == NULL)876return NULL;877c->wds = 1;878c->x[0] = 0;879return c;880}881if (i < 0) {882c = a;883a = b;884b = c;885i = 1;886}887else888i = 0;889c = Balloc(a->k);890if (c == NULL)891return NULL;892c->sign = i;893wa = a->wds;894xa = a->x;895xae = xa + wa;896wb = b->wds;897xb = b->x;898xbe = xb + wb;899xc = c->x;900borrow = 0;901do {902y = (ULLong)*xa++ - *xb++ - borrow;903borrow = y >> 32 & (ULong)1;904*xc++ = (ULong)(y & FFFFFFFF);905}906while(xb < xbe);907while(xa < xae) {908y = *xa++ - borrow;909borrow = y >> 32 & (ULong)1;910*xc++ = (ULong)(y & FFFFFFFF);911}912while(!*--xc)913wa--;914c->wds = wa;915return c;916}917918/* Given a positive normal double x, return the difference between x and the919next double up. Doesn't give correct results for subnormals. */920921static double922ulp(U *x)923{924Long L;925U u;926927L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1;928word0(&u) = L;929word1(&u) = 0;930return dval(&u);931}932933/* Convert a Bigint to a double plus an exponent */934935static double936b2d(Bigint *a, int *e)937{938ULong *xa, *xa0, w, y, z;939int k;940U d;941942xa0 = a->x;943xa = xa0 + a->wds;944y = *--xa;945#ifdef DEBUG946if (!y) Bug("zero y in b2d");947#endif948k = hi0bits(y);949*e = 32 - k;950if (k < Ebits) {951word0(&d) = Exp_1 | y >> (Ebits - k);952w = xa > xa0 ? *--xa : 0;953word1(&d) = y << ((32-Ebits) + k) | w >> (Ebits - k);954goto ret_d;955}956z = xa > xa0 ? *--xa : 0;957if (k -= Ebits) {958word0(&d) = Exp_1 | y << k | z >> (32 - k);959y = xa > xa0 ? *--xa : 0;960word1(&d) = z << k | y >> (32 - k);961}962else {963word0(&d) = Exp_1 | y;964word1(&d) = z;965}966ret_d:967return dval(&d);968}969970/* Convert a scaled double to a Bigint plus an exponent. Similar to d2b,971except that it accepts the scale parameter used in _Py_dg_strtod (which972should be either 0 or 2*P), and the normalization for the return value is973different (see below). On input, d should be finite and nonnegative, and d974/ 2**scale should be exactly representable as an IEEE 754 double.975976Returns a Bigint b and an integer e such that977978dval(d) / 2**scale = b * 2**e.979980Unlike d2b, b is not necessarily odd: b and e are normalized so981that either 2**(P-1) <= b < 2**P and e >= Etiny, or b < 2**P982and e == Etiny. This applies equally to an input of 0.0: in that983case the return values are b = 0 and e = Etiny.984985The above normalization ensures that for all possible inputs d,9862**e gives ulp(d/2**scale).987988Returns NULL on failure.989*/990991static Bigint *992sd2b(U *d, int scale, int *e)993{994Bigint *b;995996b = Balloc(1);997if (b == NULL)998return NULL;9991000/* First construct b and e assuming that scale == 0. */1001b->wds = 2;1002b->x[0] = word1(d);1003b->x[1] = word0(d) & Frac_mask;1004*e = Etiny - 1 + (int)((word0(d) & Exp_mask) >> Exp_shift);1005if (*e < Etiny)1006*e = Etiny;1007else1008b->x[1] |= Exp_msk1;10091010/* Now adjust for scale, provided that b != 0. */1011if (scale && (b->x[0] || b->x[1])) {1012*e -= scale;1013if (*e < Etiny) {1014scale = Etiny - *e;1015*e = Etiny;1016/* We can't shift more than P-1 bits without shifting out a 1. */1017assert(0 < scale && scale <= P - 1);1018if (scale >= 32) {1019/* The bits shifted out should all be zero. */1020assert(b->x[0] == 0);1021b->x[0] = b->x[1];1022b->x[1] = 0;1023scale -= 32;1024}1025if (scale) {1026/* The bits shifted out should all be zero. */1027assert(b->x[0] << (32 - scale) == 0);1028b->x[0] = (b->x[0] >> scale) | (b->x[1] << (32 - scale));1029b->x[1] >>= scale;1030}1031}1032}1033/* Ensure b is normalized. */1034if (!b->x[1])1035b->wds = 1;10361037return b;1038}10391040/* Convert a double to a Bigint plus an exponent. Return NULL on failure.10411042Given a finite nonzero double d, return an odd Bigint b and exponent *e1043such that fabs(d) = b * 2**e. On return, *bbits gives the number of1044significant bits of b; that is, 2**(*bbits-1) <= b < 2**(*bbits).10451046If d is zero, then b == 0, *e == -1010, *bbits = 0.1047*/10481049static Bigint *1050d2b(U *d, int *e, int *bits)1051{1052Bigint *b;1053int de, k;1054ULong *x, y, z;1055int i;10561057b = Balloc(1);1058if (b == NULL)1059return NULL;1060x = b->x;10611062z = word0(d) & Frac_mask;1063word0(d) &= 0x7fffffff; /* clear sign bit, which we ignore */1064if ((de = (int)(word0(d) >> Exp_shift)))1065z |= Exp_msk1;1066if ((y = word1(d))) {1067if ((k = lo0bits(&y))) {1068x[0] = y | z << (32 - k);1069z >>= k;1070}1071else1072x[0] = y;1073i =1074b->wds = (x[1] = z) ? 2 : 1;1075}1076else {1077k = lo0bits(&z);1078x[0] = z;1079i =1080b->wds = 1;1081k += 32;1082}1083if (de) {1084*e = de - Bias - (P-1) + k;1085*bits = P - k;1086}1087else {1088*e = de - Bias - (P-1) + 1 + k;1089*bits = 32*i - hi0bits(x[i-1]);1090}1091return b;1092}10931094/* Compute the ratio of two Bigints, as a double. The result may have an1095error of up to 2.5 ulps. */10961097static double1098ratio(Bigint *a, Bigint *b)1099{1100U da, db;1101int k, ka, kb;11021103dval(&da) = b2d(a, &ka);1104dval(&db) = b2d(b, &kb);1105k = ka - kb + 32*(a->wds - b->wds);1106if (k > 0)1107word0(&da) += k*Exp_msk1;1108else {1109k = -k;1110word0(&db) += k*Exp_msk1;1111}1112return dval(&da) / dval(&db);1113}11141115static const double1116tens[] = {11171e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,11181e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,11191e20, 1e21, 1e221120};11211122static const double1123bigtens[] = { 1e16, 1e32, 1e64, 1e128, 1e256 };1124static const double tinytens[] = { 1e-16, 1e-32, 1e-64, 1e-128,11259007199254740992.*9007199254740992.e-2561126/* = 2^106 * 1e-256 */1127};1128/* The factor of 2^53 in tinytens[4] helps us avoid setting the underflow */1129/* flag unnecessarily. It leads to a song and dance at the end of strtod. */1130#define Scale_Bit 0x101131#define n_bigtens 511321133#define ULbits 321134#define kshift 51135#define kmask 31113611371138static int1139dshift(Bigint *b, int p2)1140{1141int rv = hi0bits(b->x[b->wds-1]) - 4;1142if (p2 > 0)1143rv -= p2;1144return rv & kmask;1145}11461147/* special case of Bigint division. The quotient is always in the range 0 <=1148quotient < 10, and on entry the divisor S is normalized so that its top 41149bits (28--31) are zero and bit 27 is set. */11501151static int1152quorem(Bigint *b, Bigint *S)1153{1154int n;1155ULong *bx, *bxe, q, *sx, *sxe;1156ULLong borrow, carry, y, ys;11571158n = S->wds;1159#ifdef DEBUG1160/*debug*/ if (b->wds > n)1161/*debug*/ Bug("oversize b in quorem");1162#endif1163if (b->wds < n)1164return 0;1165sx = S->x;1166sxe = sx + --n;1167bx = b->x;1168bxe = bx + n;1169q = *bxe / (*sxe + 1); /* ensure q <= true quotient */1170#ifdef DEBUG1171/*debug*/ if (q > 9)1172/*debug*/ Bug("oversized quotient in quorem");1173#endif1174if (q) {1175borrow = 0;1176carry = 0;1177do {1178ys = *sx++ * (ULLong)q + carry;1179carry = ys >> 32;1180y = *bx - (ys & FFFFFFFF) - borrow;1181borrow = y >> 32 & (ULong)1;1182*bx++ = (ULong)(y & FFFFFFFF);1183}1184while(sx <= sxe);1185if (!*bxe) {1186bx = b->x;1187while(--bxe > bx && !*bxe)1188--n;1189b->wds = n;1190}1191}1192if (cmp(b, S) >= 0) {1193q++;1194borrow = 0;1195carry = 0;1196bx = b->x;1197sx = S->x;1198do {1199ys = *sx++ + carry;1200carry = ys >> 32;1201y = *bx - (ys & FFFFFFFF) - borrow;1202borrow = y >> 32 & (ULong)1;1203*bx++ = (ULong)(y & FFFFFFFF);1204}1205while(sx <= sxe);1206bx = b->x;1207bxe = bx + n;1208if (!*bxe) {1209while(--bxe > bx && !*bxe)1210--n;1211b->wds = n;1212}1213}1214return q;1215}12161217/* sulp(x) is a version of ulp(x) that takes bc.scale into account.12181219Assuming that x is finite and nonnegative (positive zero is fine1220here) and x / 2^bc.scale is exactly representable as a double,1221sulp(x) is equivalent to 2^bc.scale * ulp(x / 2^bc.scale). */12221223static double1224sulp(U *x, BCinfo *bc)1225{1226U u;12271228if (bc->scale && 2*P + 1 > (int)((word0(x) & Exp_mask) >> Exp_shift)) {1229/* rv/2^bc->scale is subnormal */1230word0(&u) = (P+2)*Exp_msk1;1231word1(&u) = 0;1232return u.d;1233}1234else {1235assert(word0(x) || word1(x)); /* x != 0.0 */1236return ulp(x);1237}1238}12391240/* The bigcomp function handles some hard cases for strtod, for inputs1241with more than STRTOD_DIGLIM digits. It's called once an initial1242estimate for the double corresponding to the input string has1243already been obtained by the code in _Py_dg_strtod.12441245The bigcomp function is only called after _Py_dg_strtod has found a1246double value rv such that either rv or rv + 1ulp represents the1247correctly rounded value corresponding to the original string. It1248determines which of these two values is the correct one by1249computing the decimal digits of rv + 0.5ulp and comparing them with1250the corresponding digits of s0.12511252In the following, write dv for the absolute value of the number represented1253by the input string.12541255Inputs:12561257s0 points to the first significant digit of the input string.12581259rv is a (possibly scaled) estimate for the closest double value to the1260value represented by the original input to _Py_dg_strtod. If1261bc->scale is nonzero, then rv/2^(bc->scale) is the approximation to1262the input value.12631264bc is a struct containing information gathered during the parsing and1265estimation steps of _Py_dg_strtod. Description of fields follows:12661267bc->e0 gives the exponent of the input value, such that dv = (integer1268given by the bd->nd digits of s0) * 10**e012691270bc->nd gives the total number of significant digits of s0. It will1271be at least 1.12721273bc->nd0 gives the number of significant digits of s0 before the1274decimal separator. If there's no decimal separator, bc->nd0 ==1275bc->nd.12761277bc->scale is the value used to scale rv to avoid doing arithmetic with1278subnormal values. It's either 0 or 2*P (=106).12791280Outputs:12811282On successful exit, rv/2^(bc->scale) is the closest double to dv.12831284Returns 0 on success, -1 on failure (e.g., due to a failed malloc call). */12851286static int1287bigcomp(U *rv, const char *s0, BCinfo *bc)1288{1289Bigint *b, *d;1290int b2, d2, dd, i, nd, nd0, odd, p2, p5;12911292nd = bc->nd;1293nd0 = bc->nd0;1294p5 = nd + bc->e0;1295b = sd2b(rv, bc->scale, &p2);1296if (b == NULL)1297return -1;12981299/* record whether the lsb of rv/2^(bc->scale) is odd: in the exact halfway1300case, this is used for round to even. */1301odd = b->x[0] & 1;13021303/* left shift b by 1 bit and or a 1 into the least significant bit;1304this gives us b * 2**p2 = rv/2^(bc->scale) + 0.5 ulp. */1305b = lshift(b, 1);1306if (b == NULL)1307return -1;1308b->x[0] |= 1;1309p2--;13101311p2 -= p5;1312d = i2b(1);1313if (d == NULL) {1314Bfree(b);1315return -1;1316}1317/* Arrange for convenient computation of quotients:1318* shift left if necessary so divisor has 4 leading 0 bits.1319*/1320if (p5 > 0) {1321d = pow5mult(d, p5);1322if (d == NULL) {1323Bfree(b);1324return -1;1325}1326}1327else if (p5 < 0) {1328b = pow5mult(b, -p5);1329if (b == NULL) {1330Bfree(d);1331return -1;1332}1333}1334if (p2 > 0) {1335b2 = p2;1336d2 = 0;1337}1338else {1339b2 = 0;1340d2 = -p2;1341}1342i = dshift(d, d2);1343if ((b2 += i) > 0) {1344b = lshift(b, b2);1345if (b == NULL) {1346Bfree(d);1347return -1;1348}1349}1350if ((d2 += i) > 0) {1351d = lshift(d, d2);1352if (d == NULL) {1353Bfree(b);1354return -1;1355}1356}13571358/* Compare s0 with b/d: set dd to -1, 0, or 1 according as s0 < b/d, s0 ==1359* b/d, or s0 > b/d. Here the digits of s0 are thought of as representing1360* a number in the range [0.1, 1). */1361if (cmp(b, d) >= 0)1362/* b/d >= 1 */1363dd = -1;1364else {1365i = 0;1366for(;;) {1367b = multadd(b, 10, 0);1368if (b == NULL) {1369Bfree(d);1370return -1;1371}1372dd = s0[i < nd0 ? i : i+1] - '0' - quorem(b, d);1373i++;13741375if (dd)1376break;1377if (!b->x[0] && b->wds == 1) {1378/* b/d == 0 */1379dd = i < nd;1380break;1381}1382if (!(i < nd)) {1383/* b/d != 0, but digits of s0 exhausted */1384dd = -1;1385break;1386}1387}1388}1389Bfree(b);1390Bfree(d);1391if (dd > 0 || (dd == 0 && odd))1392dval(rv) += sulp(rv, bc);1393return 0;1394}139513961397double1398_Py_dg_strtod(const char *s00, char **se)1399{1400int bb2, bb5, bbe, bd2, bd5, bs2, c, dsign, e, e1, error;1401int esign, i, j, k, lz, nd, nd0, odd, sign;1402const char *s, *s0, *s1;1403double aadj, aadj1;1404U aadj2, adj, rv, rv0;1405ULong y, z, abs_exp;1406Long L;1407BCinfo bc;1408Bigint *bb = NULL, *bd = NULL, *bd0 = NULL, *bs = NULL, *delta = NULL;1409size_t ndigits, fraclen;1410double result;14111412dval(&rv) = 0.;14131414/* Start parsing. */1415c = *(s = s00);14161417/* Parse optional sign, if present. */1418sign = 0;1419switch (c) {1420case '-':1421sign = 1;1422/* fall through */1423case '+':1424c = *++s;1425}14261427/* Skip leading zeros: lz is true iff there were leading zeros. */1428s1 = s;1429while (c == '0')1430c = *++s;1431lz = s != s1;14321433/* Point s0 at the first nonzero digit (if any). fraclen will be the1434number of digits between the decimal point and the end of the1435digit string. ndigits will be the total number of digits ignoring1436leading zeros. */1437s0 = s1 = s;1438while ('0' <= c && c <= '9')1439c = *++s;1440ndigits = s - s1;1441fraclen = 0;14421443/* Parse decimal point and following digits. */1444if (c == '.') {1445c = *++s;1446if (!ndigits) {1447s1 = s;1448while (c == '0')1449c = *++s;1450lz = lz || s != s1;1451fraclen += (s - s1);1452s0 = s;1453}1454s1 = s;1455while ('0' <= c && c <= '9')1456c = *++s;1457ndigits += s - s1;1458fraclen += s - s1;1459}14601461/* Now lz is true if and only if there were leading zero digits, and1462ndigits gives the total number of digits ignoring leading zeros. A1463valid input must have at least one digit. */1464if (!ndigits && !lz) {1465if (se)1466*se = (char *)s00;1467goto parse_error;1468}14691470/* Range check ndigits and fraclen to make sure that they, and values1471computed with them, can safely fit in an int. */1472if (ndigits > MAX_DIGITS || fraclen > MAX_DIGITS) {1473if (se)1474*se = (char *)s00;1475goto parse_error;1476}1477nd = (int)ndigits;1478nd0 = (int)ndigits - (int)fraclen;14791480/* Parse exponent. */1481e = 0;1482if (c == 'e' || c == 'E') {1483s00 = s;1484c = *++s;14851486/* Exponent sign. */1487esign = 0;1488switch (c) {1489case '-':1490esign = 1;1491/* fall through */1492case '+':1493c = *++s;1494}14951496/* Skip zeros. lz is true iff there are leading zeros. */1497s1 = s;1498while (c == '0')1499c = *++s;1500lz = s != s1;15011502/* Get absolute value of the exponent. */1503s1 = s;1504abs_exp = 0;1505while ('0' <= c && c <= '9') {1506abs_exp = 10*abs_exp + (c - '0');1507c = *++s;1508}15091510/* abs_exp will be correct modulo 2**32. But 10**9 < 2**32, so if1511there are at most 9 significant exponent digits then overflow is1512impossible. */1513if (s - s1 > 9 || abs_exp > MAX_ABS_EXP)1514e = (int)MAX_ABS_EXP;1515else1516e = (int)abs_exp;1517if (esign)1518e = -e;15191520/* A valid exponent must have at least one digit. */1521if (s == s1 && !lz)1522s = s00;1523}15241525/* Adjust exponent to take into account position of the point. */1526e -= nd - nd0;1527if (nd0 <= 0)1528nd0 = nd;15291530/* Finished parsing. Set se to indicate how far we parsed */1531if (se)1532*se = (char *)s;15331534/* If all digits were zero, exit with return value +-0.0. Otherwise,1535strip trailing zeros: scan back until we hit a nonzero digit. */1536if (!nd)1537goto ret;1538for (i = nd; i > 0; ) {1539--i;1540if (s0[i < nd0 ? i : i+1] != '0') {1541++i;1542break;1543}1544}1545e += nd - i;1546nd = i;1547if (nd0 > nd)1548nd0 = nd;15491550/* Summary of parsing results. After parsing, and dealing with zero1551* inputs, we have values s0, nd0, nd, e, sign, where:1552*1553* - s0 points to the first significant digit of the input string1554*1555* - nd is the total number of significant digits (here, and1556* below, 'significant digits' means the set of digits of the1557* significand of the input that remain after ignoring leading1558* and trailing zeros).1559*1560* - nd0 indicates the position of the decimal point, if present; it1561* satisfies 1 <= nd0 <= nd. The nd significant digits are in1562* s0[0:nd0] and s0[nd0+1:nd+1] using the usual Python half-open slice1563* notation. (If nd0 < nd, then s0[nd0] contains a '.' character; if1564* nd0 == nd, then s0[nd0] could be any non-digit character.)1565*1566* - e is the adjusted exponent: the absolute value of the number1567* represented by the original input string is n * 10**e, where1568* n is the integer represented by the concatenation of1569* s0[0:nd0] and s0[nd0+1:nd+1]1570*1571* - sign gives the sign of the input: 1 for negative, 0 for positive1572*1573* - the first and last significant digits are nonzero1574*/15751576/* put first DBL_DIG+1 digits into integer y and z.1577*1578* - y contains the value represented by the first min(9, nd)1579* significant digits1580*1581* - if nd > 9, z contains the value represented by significant digits1582* with indices in [9, min(16, nd)). So y * 10**(min(16, nd) - 9) + z1583* gives the value represented by the first min(16, nd) sig. digits.1584*/15851586bc.e0 = e1 = e;1587y = z = 0;1588for (i = 0; i < nd; i++) {1589if (i < 9)1590y = 10*y + s0[i < nd0 ? i : i+1] - '0';1591else if (i < DBL_DIG+1)1592z = 10*z + s0[i < nd0 ? i : i+1] - '0';1593else1594break;1595}15961597k = nd < DBL_DIG + 1 ? nd : DBL_DIG + 1;1598dval(&rv) = y;1599if (k > 9) {1600dval(&rv) = tens[k - 9] * dval(&rv) + z;1601}1602if (nd <= DBL_DIG1603&& Flt_Rounds == 11604) {1605if (!e)1606goto ret;1607if (e > 0) {1608if (e <= Ten_pmax) {1609dval(&rv) *= tens[e];1610goto ret;1611}1612i = DBL_DIG - nd;1613if (e <= Ten_pmax + i) {1614/* A fancier test would sometimes let us do1615* this for larger i values.1616*/1617e -= i;1618dval(&rv) *= tens[i];1619dval(&rv) *= tens[e];1620goto ret;1621}1622}1623else if (e >= -Ten_pmax) {1624dval(&rv) /= tens[-e];1625goto ret;1626}1627}1628e1 += nd - k;16291630bc.scale = 0;16311632/* Get starting approximation = rv * 10**e1 */16331634if (e1 > 0) {1635if ((i = e1 & 15))1636dval(&rv) *= tens[i];1637if (e1 &= ~15) {1638if (e1 > DBL_MAX_10_EXP)1639goto ovfl;1640e1 >>= 4;1641for(j = 0; e1 > 1; j++, e1 >>= 1)1642if (e1 & 1)1643dval(&rv) *= bigtens[j];1644/* The last multiplication could overflow. */1645word0(&rv) -= P*Exp_msk1;1646dval(&rv) *= bigtens[j];1647if ((z = word0(&rv) & Exp_mask)1648> Exp_msk1*(DBL_MAX_EXP+Bias-P))1649goto ovfl;1650if (z > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) {1651/* set to largest number */1652/* (Can't trust DBL_MAX) */1653word0(&rv) = Big0;1654word1(&rv) = Big1;1655}1656else1657word0(&rv) += P*Exp_msk1;1658}1659}1660else if (e1 < 0) {1661/* The input decimal value lies in [10**e1, 10**(e1+16)).16621663If e1 <= -512, underflow immediately.1664If e1 <= -256, set bc.scale to 2*P.16651666So for input value < 1e-256, bc.scale is always set;1667for input value >= 1e-240, bc.scale is never set.1668For input values in [1e-256, 1e-240), bc.scale may or may1669not be set. */16701671e1 = -e1;1672if ((i = e1 & 15))1673dval(&rv) /= tens[i];1674if (e1 >>= 4) {1675if (e1 >= 1 << n_bigtens)1676goto undfl;1677if (e1 & Scale_Bit)1678bc.scale = 2*P;1679for(j = 0; e1 > 0; j++, e1 >>= 1)1680if (e1 & 1)1681dval(&rv) *= tinytens[j];1682if (bc.scale && (j = 2*P + 1 - ((word0(&rv) & Exp_mask)1683>> Exp_shift)) > 0) {1684/* scaled rv is denormal; clear j low bits */1685if (j >= 32) {1686word1(&rv) = 0;1687if (j >= 53)1688word0(&rv) = (P+2)*Exp_msk1;1689else1690word0(&rv) &= 0xffffffff << (j-32);1691}1692else1693word1(&rv) &= 0xffffffff << j;1694}1695if (!dval(&rv))1696goto undfl;1697}1698}16991700/* Now the hard part -- adjusting rv to the correct value.*/17011702/* Put digits into bd: true value = bd * 10^e */17031704bc.nd = nd;1705bc.nd0 = nd0; /* Only needed if nd > STRTOD_DIGLIM, but done here */1706/* to silence an erroneous warning about bc.nd0 */1707/* possibly not being initialized. */1708if (nd > STRTOD_DIGLIM) {1709/* ASSERT(STRTOD_DIGLIM >= 18); 18 == one more than the */1710/* minimum number of decimal digits to distinguish double values */1711/* in IEEE arithmetic. */17121713/* Truncate input to 18 significant digits, then discard any trailing1714zeros on the result by updating nd, nd0, e and y suitably. (There's1715no need to update z; it's not reused beyond this point.) */1716for (i = 18; i > 0; ) {1717/* scan back until we hit a nonzero digit. significant digit 'i'1718is s0[i] if i < nd0, s0[i+1] if i >= nd0. */1719--i;1720if (s0[i < nd0 ? i : i+1] != '0') {1721++i;1722break;1723}1724}1725e += nd - i;1726nd = i;1727if (nd0 > nd)1728nd0 = nd;1729if (nd < 9) { /* must recompute y */1730y = 0;1731for(i = 0; i < nd0; ++i)1732y = 10*y + s0[i] - '0';1733for(; i < nd; ++i)1734y = 10*y + s0[i+1] - '0';1735}1736}1737bd0 = s2b(s0, nd0, nd, y);1738if (bd0 == NULL)1739goto failed_malloc;17401741/* Notation for the comments below. Write:17421743- dv for the absolute value of the number represented by the original1744decimal input string.17451746- if we've truncated dv, write tdv for the truncated value.1747Otherwise, set tdv == dv.17481749- srv for the quantity rv/2^bc.scale; so srv is the current binary1750approximation to tdv (and dv). It should be exactly representable1751in an IEEE 754 double.1752*/17531754for(;;) {17551756/* This is the main correction loop for _Py_dg_strtod.17571758We've got a decimal value tdv, and a floating-point approximation1759srv=rv/2^bc.scale to tdv. The aim is to determine whether srv is1760close enough (i.e., within 0.5 ulps) to tdv, and to compute a new1761approximation if not.17621763To determine whether srv is close enough to tdv, compute integers1764bd, bb and bs proportional to tdv, srv and 0.5 ulp(srv)1765respectively, and then use integer arithmetic to determine whether1766|tdv - srv| is less than, equal to, or greater than 0.5 ulp(srv).1767*/17681769bd = Balloc(bd0->k);1770if (bd == NULL) {1771goto failed_malloc;1772}1773Bcopy(bd, bd0);1774bb = sd2b(&rv, bc.scale, &bbe); /* srv = bb * 2^bbe */1775if (bb == NULL) {1776goto failed_malloc;1777}1778/* Record whether lsb of bb is odd, in case we need this1779for the round-to-even step later. */1780odd = bb->x[0] & 1;17811782/* tdv = bd * 10**e; srv = bb * 2**bbe */1783bs = i2b(1);1784if (bs == NULL) {1785goto failed_malloc;1786}17871788if (e >= 0) {1789bb2 = bb5 = 0;1790bd2 = bd5 = e;1791}1792else {1793bb2 = bb5 = -e;1794bd2 = bd5 = 0;1795}1796if (bbe >= 0)1797bb2 += bbe;1798else1799bd2 -= bbe;1800bs2 = bb2;1801bb2++;1802bd2++;18031804/* At this stage bd5 - bb5 == e == bd2 - bb2 + bbe, bb2 - bs2 == 1,1805and bs == 1, so:18061807tdv == bd * 10**e = bd * 2**(bbe - bb2 + bd2) * 5**(bd5 - bb5)1808srv == bb * 2**bbe = bb * 2**(bbe - bb2 + bb2)18090.5 ulp(srv) == 2**(bbe-1) = bs * 2**(bbe - bb2 + bs2)18101811It follows that:18121813M * tdv = bd * 2**bd2 * 5**bd51814M * srv = bb * 2**bb2 * 5**bb51815M * 0.5 ulp(srv) = bs * 2**bs2 * 5**bb518161817for some constant M. (Actually, M == 2**(bb2 - bbe) * 5**bb5, but1818this fact is not needed below.)1819*/18201821/* Remove factor of 2**i, where i = min(bb2, bd2, bs2). */1822i = bb2 < bd2 ? bb2 : bd2;1823if (i > bs2)1824i = bs2;1825if (i > 0) {1826bb2 -= i;1827bd2 -= i;1828bs2 -= i;1829}18301831/* Scale bb, bd, bs by the appropriate powers of 2 and 5. */1832if (bb5 > 0) {1833bs = pow5mult(bs, bb5);1834if (bs == NULL) {1835goto failed_malloc;1836}1837Bigint *bb1 = mult(bs, bb);1838Bfree(bb);1839bb = bb1;1840if (bb == NULL) {1841goto failed_malloc;1842}1843}1844if (bb2 > 0) {1845bb = lshift(bb, bb2);1846if (bb == NULL) {1847goto failed_malloc;1848}1849}1850if (bd5 > 0) {1851bd = pow5mult(bd, bd5);1852if (bd == NULL) {1853goto failed_malloc;1854}1855}1856if (bd2 > 0) {1857bd = lshift(bd, bd2);1858if (bd == NULL) {1859goto failed_malloc;1860}1861}1862if (bs2 > 0) {1863bs = lshift(bs, bs2);1864if (bs == NULL) {1865goto failed_malloc;1866}1867}18681869/* Now bd, bb and bs are scaled versions of tdv, srv and 0.5 ulp(srv),1870respectively. Compute the difference |tdv - srv|, and compare1871with 0.5 ulp(srv). */18721873delta = diff(bb, bd);1874if (delta == NULL) {1875goto failed_malloc;1876}1877dsign = delta->sign;1878delta->sign = 0;1879i = cmp(delta, bs);1880if (bc.nd > nd && i <= 0) {1881if (dsign)1882break; /* Must use bigcomp(). */18831884/* Here rv overestimates the truncated decimal value by at most18850.5 ulp(rv). Hence rv either overestimates the true decimal1886value by <= 0.5 ulp(rv), or underestimates it by some small1887amount (< 0.1 ulp(rv)); either way, rv is within 0.5 ulps of1888the true decimal value, so it's possible to exit.18891890Exception: if scaled rv is a normal exact power of 2, but not1891DBL_MIN, then rv - 0.5 ulp(rv) takes us all the way down to the1892next double, so the correctly rounded result is either rv - 0.51893ulp(rv) or rv; in this case, use bigcomp to distinguish. */18941895if (!word1(&rv) && !(word0(&rv) & Bndry_mask)) {1896/* rv can't be 0, since it's an overestimate for some1897nonzero value. So rv is a normal power of 2. */1898j = (int)(word0(&rv) & Exp_mask) >> Exp_shift;1899/* rv / 2^bc.scale = 2^(j - 1023 - bc.scale); use bigcomp if1900rv / 2^bc.scale >= 2^-1021. */1901if (j - bc.scale >= 2) {1902dval(&rv) -= 0.5 * sulp(&rv, &bc);1903break; /* Use bigcomp. */1904}1905}19061907{1908bc.nd = nd;1909i = -1; /* Discarded digits make delta smaller. */1910}1911}19121913if (i < 0) {1914/* Error is less than half an ulp -- check for1915* special case of mantissa a power of two.1916*/1917if (dsign || word1(&rv) || word0(&rv) & Bndry_mask1918|| (word0(&rv) & Exp_mask) <= (2*P+1)*Exp_msk11919) {1920break;1921}1922if (!delta->x[0] && delta->wds <= 1) {1923/* exact result */1924break;1925}1926delta = lshift(delta,Log2P);1927if (delta == NULL) {1928goto failed_malloc;1929}1930if (cmp(delta, bs) > 0)1931goto drop_down;1932break;1933}1934if (i == 0) {1935/* exactly half-way between */1936if (dsign) {1937if ((word0(&rv) & Bndry_mask1) == Bndry_mask11938&& word1(&rv) == (1939(bc.scale &&1940(y = word0(&rv) & Exp_mask) <= 2*P*Exp_msk1) ?1941(0xffffffff & (0xffffffff << (2*P+1-(y>>Exp_shift)))) :19420xffffffff)) {1943/*boundary case -- increment exponent*/1944word0(&rv) = (word0(&rv) & Exp_mask)1945+ Exp_msk11946;1947word1(&rv) = 0;1948/* dsign = 0; */1949break;1950}1951}1952else if (!(word0(&rv) & Bndry_mask) && !word1(&rv)) {1953drop_down:1954/* boundary case -- decrement exponent */1955if (bc.scale) {1956L = word0(&rv) & Exp_mask;1957if (L <= (2*P+1)*Exp_msk1) {1958if (L > (P+2)*Exp_msk1)1959/* round even ==> */1960/* accept rv */1961break;1962/* rv = smallest denormal */1963if (bc.nd > nd)1964break;1965goto undfl;1966}1967}1968L = (word0(&rv) & Exp_mask) - Exp_msk1;1969word0(&rv) = L | Bndry_mask1;1970word1(&rv) = 0xffffffff;1971break;1972}1973if (!odd)1974break;1975if (dsign)1976dval(&rv) += sulp(&rv, &bc);1977else {1978dval(&rv) -= sulp(&rv, &bc);1979if (!dval(&rv)) {1980if (bc.nd >nd)1981break;1982goto undfl;1983}1984}1985/* dsign = 1 - dsign; */1986break;1987}1988if ((aadj = ratio(delta, bs)) <= 2.) {1989if (dsign)1990aadj = aadj1 = 1.;1991else if (word1(&rv) || word0(&rv) & Bndry_mask) {1992if (word1(&rv) == Tiny1 && !word0(&rv)) {1993if (bc.nd >nd)1994break;1995goto undfl;1996}1997aadj = 1.;1998aadj1 = -1.;1999}2000else {2001/* special case -- power of FLT_RADIX to be */2002/* rounded down... */20032004if (aadj < 2./FLT_RADIX)2005aadj = 1./FLT_RADIX;2006else2007aadj *= 0.5;2008aadj1 = -aadj;2009}2010}2011else {2012aadj *= 0.5;2013aadj1 = dsign ? aadj : -aadj;2014if (Flt_Rounds == 0)2015aadj1 += 0.5;2016}2017y = word0(&rv) & Exp_mask;20182019/* Check for overflow */20202021if (y == Exp_msk1*(DBL_MAX_EXP+Bias-1)) {2022dval(&rv0) = dval(&rv);2023word0(&rv) -= P*Exp_msk1;2024adj.d = aadj1 * ulp(&rv);2025dval(&rv) += adj.d;2026if ((word0(&rv) & Exp_mask) >=2027Exp_msk1*(DBL_MAX_EXP+Bias-P)) {2028if (word0(&rv0) == Big0 && word1(&rv0) == Big1) {2029goto ovfl;2030}2031word0(&rv) = Big0;2032word1(&rv) = Big1;2033goto cont;2034}2035else2036word0(&rv) += P*Exp_msk1;2037}2038else {2039if (bc.scale && y <= 2*P*Exp_msk1) {2040if (aadj <= 0x7fffffff) {2041if ((z = (ULong)aadj) <= 0)2042z = 1;2043aadj = z;2044aadj1 = dsign ? aadj : -aadj;2045}2046dval(&aadj2) = aadj1;2047word0(&aadj2) += (2*P+1)*Exp_msk1 - y;2048aadj1 = dval(&aadj2);2049}2050adj.d = aadj1 * ulp(&rv);2051dval(&rv) += adj.d;2052}2053z = word0(&rv) & Exp_mask;2054if (bc.nd == nd) {2055if (!bc.scale)2056if (y == z) {2057/* Can we stop now? */2058L = (Long)aadj;2059aadj -= L;2060/* The tolerances below are conservative. */2061if (dsign || word1(&rv) || word0(&rv) & Bndry_mask) {2062if (aadj < .4999999 || aadj > .5000001)2063break;2064}2065else if (aadj < .4999999/FLT_RADIX)2066break;2067}2068}2069cont:2070Bfree(bb); bb = NULL;2071Bfree(bd); bd = NULL;2072Bfree(bs); bs = NULL;2073Bfree(delta); delta = NULL;2074}2075if (bc.nd > nd) {2076error = bigcomp(&rv, s0, &bc);2077if (error)2078goto failed_malloc;2079}20802081if (bc.scale) {2082word0(&rv0) = Exp_1 - 2*P*Exp_msk1;2083word1(&rv0) = 0;2084dval(&rv) *= dval(&rv0);2085}20862087ret:2088result = sign ? -dval(&rv) : dval(&rv);2089goto done;20902091parse_error:2092result = 0.0;2093goto done;20942095failed_malloc:2096errno = ENOMEM;2097result = -1.0;2098goto done;20992100undfl:2101result = sign ? -0.0 : 0.0;2102goto done;21032104ovfl:2105errno = ERANGE;2106/* Can't trust HUGE_VAL */2107word0(&rv) = Exp_mask;2108word1(&rv) = 0;2109result = sign ? -dval(&rv) : dval(&rv);2110goto done;21112112done:2113Bfree(bb);2114Bfree(bd);2115Bfree(bs);2116Bfree(bd0);2117Bfree(delta);2118return result;21192120}21212122static char *2123rv_alloc(int i)2124{2125int j, k, *r;21262127j = sizeof(ULong);2128for(k = 0;2129sizeof(Bigint) - sizeof(ULong) - sizeof(int) + j <= (unsigned)i;2130j <<= 1)2131k++;2132r = (int*)Balloc(k);2133if (r == NULL)2134return NULL;2135*r = k;2136return (char *)(r+1);2137}21382139static char *2140nrv_alloc(const char *s, char **rve, int n)2141{2142char *rv, *t;21432144rv = rv_alloc(n);2145if (rv == NULL)2146return NULL;2147t = rv;2148while((*t = *s++)) t++;2149if (rve)2150*rve = t;2151return rv;2152}21532154/* freedtoa(s) must be used to free values s returned by dtoa2155* when MULTIPLE_THREADS is #defined. It should be used in all cases,2156* but for consistency with earlier versions of dtoa, it is optional2157* when MULTIPLE_THREADS is not defined.2158*/21592160void2161_Py_dg_freedtoa(char *s)2162{2163Bigint *b = (Bigint *)((int *)s - 1);2164b->maxwds = 1 << (b->k = *(int*)b);2165Bfree(b);2166}21672168/* dtoa for IEEE arithmetic (dmg): convert double to ASCII string.2169*2170* Inspired by "How to Print Floating-Point Numbers Accurately" by2171* Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 112-126].2172*2173* Modifications:2174* 1. Rather than iterating, we use a simple numeric overestimate2175* to determine k = floor(log10(d)). We scale relevant2176* quantities using O(log2(k)) rather than O(k) multiplications.2177* 2. For some modes > 2 (corresponding to ecvt and fcvt), we don't2178* try to generate digits strictly left to right. Instead, we2179* compute with fewer bits and propagate the carry if necessary2180* when rounding the final digit up. This is often faster.2181* 3. Under the assumption that input will be rounded nearest,2182* mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22.2183* That is, we allow equality in stopping tests when the2184* round-nearest rule will give the same floating-point value2185* as would satisfaction of the stopping test with strict2186* inequality.2187* 4. We remove common factors of powers of 2 from relevant2188* quantities.2189* 5. When converting floating-point integers less than 1e16,2190* we use floating-point arithmetic rather than resorting2191* to multiple-precision integers.2192* 6. When asked to produce fewer than 15 digits, we first try2193* to get by with floating-point arithmetic; we resort to2194* multiple-precision integer arithmetic only if we cannot2195* guarantee that the floating-point calculation has given2196* the correctly rounded result. For k requested digits and2197* "uniformly" distributed input, the probability is2198* something like 10^(k-15) that we must resort to the Long2199* calculation.2200*/22012202/* Additional notes (METD): (1) returns NULL on failure. (2) to avoid memory2203leakage, a successful call to _Py_dg_dtoa should always be matched by a2204call to _Py_dg_freedtoa. */22052206char *2207_Py_dg_dtoa(double dd, int mode, int ndigits,2208int *decpt, int *sign, char **rve)2209{2210/* Arguments ndigits, decpt, sign are similar to those2211of ecvt and fcvt; trailing zeros are suppressed from2212the returned string. If not null, *rve is set to point2213to the end of the return value. If d is +-Infinity or NaN,2214then *decpt is set to 9999.22152216mode:22170 ==> shortest string that yields d when read in2218and rounded to nearest.22191 ==> like 0, but with Steele & White stopping rule;2220e.g. with IEEE P754 arithmetic , mode 0 gives22211e23 whereas mode 1 gives 9.999999999999999e22.22222 ==> max(1,ndigits) significant digits. This gives a2223return value similar to that of ecvt, except2224that trailing zeros are suppressed.22253 ==> through ndigits past the decimal point. This2226gives a return value similar to that from fcvt,2227except that trailing zeros are suppressed, and2228ndigits can be negative.22294,5 ==> similar to 2 and 3, respectively, but (in2230round-nearest mode) with the tests of mode 0 to2231possibly return a shorter string that rounds to d.2232With IEEE arithmetic and compilation with2233-DHonor_FLT_ROUNDS, modes 4 and 5 behave the same2234as modes 2 and 3 when FLT_ROUNDS != 1.22356-9 ==> Debugging modes similar to mode - 4: don't try2236fast floating-point estimate (if applicable).22372238Values of mode other than 0-9 are treated as mode 0.22392240Sufficient space is allocated to the return value2241to hold the suppressed trailing zeros.2242*/22432244int bbits, b2, b5, be, dig, i, ieps, ilim, ilim0, ilim1,2245j, j1, k, k0, k_check, leftright, m2, m5, s2, s5,2246spec_case, try_quick;2247Long L;2248int denorm;2249ULong x;2250Bigint *b, *b1, *delta, *mlo, *mhi, *S;2251U d2, eps, u;2252double ds;2253char *s, *s0;22542255/* set pointers to NULL, to silence gcc compiler warnings and make2256cleanup easier on error */2257mlo = mhi = S = 0;2258s0 = 0;22592260u.d = dd;2261if (word0(&u) & Sign_bit) {2262/* set sign for everything, including 0's and NaNs */2263*sign = 1;2264word0(&u) &= ~Sign_bit; /* clear sign bit */2265}2266else2267*sign = 0;22682269/* quick return for Infinities, NaNs and zeros */2270if ((word0(&u) & Exp_mask) == Exp_mask)2271{2272/* Infinity or NaN */2273*decpt = 9999;2274if (!word1(&u) && !(word0(&u) & 0xfffff))2275return nrv_alloc("Infinity", rve, 8);2276return nrv_alloc("NaN", rve, 3);2277}2278if (!dval(&u)) {2279*decpt = 1;2280return nrv_alloc("0", rve, 1);2281}22822283/* compute k = floor(log10(d)). The computation may leave k2284one too large, but should never leave k too small. */2285b = d2b(&u, &be, &bbits);2286if (b == NULL)2287goto failed_malloc;2288if ((i = (int)(word0(&u) >> Exp_shift1 & (Exp_mask>>Exp_shift1)))) {2289dval(&d2) = dval(&u);2290word0(&d2) &= Frac_mask1;2291word0(&d2) |= Exp_11;22922293/* log(x) ~=~ log(1.5) + (x-1.5)/1.52294* log10(x) = log(x) / log(10)2295* ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10))2296* log10(d) = (i-Bias)*log(2)/log(10) + log10(d2)2297*2298* This suggests computing an approximation k to log10(d) by2299*2300* k = (i - Bias)*0.3010299956639812301* + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 );2302*2303* We want k to be too large rather than too small.2304* The error in the first-order Taylor series approximation2305* is in our favor, so we just round up the constant enough2306* to compensate for any error in the multiplication of2307* (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077,2308* and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14,2309* adding 1e-13 to the constant term more than suffices.2310* Hence we adjust the constant term to 0.1760912590558.2311* (We could get a more accurate k by invoking log10,2312* but this is probably not worthwhile.)2313*/23142315i -= Bias;2316denorm = 0;2317}2318else {2319/* d is denormalized */23202321i = bbits + be + (Bias + (P-1) - 1);2322x = i > 32 ? word0(&u) << (64 - i) | word1(&u) >> (i - 32)2323: word1(&u) << (32 - i);2324dval(&d2) = x;2325word0(&d2) -= 31*Exp_msk1; /* adjust exponent */2326i -= (Bias + (P-1) - 1) + 1;2327denorm = 1;2328}2329ds = (dval(&d2)-1.5)*0.289529654602168 + 0.1760912590558 +2330i*0.301029995663981;2331k = (int)ds;2332if (ds < 0. && ds != k)2333k--; /* want k = floor(ds) */2334k_check = 1;2335if (k >= 0 && k <= Ten_pmax) {2336if (dval(&u) < tens[k])2337k--;2338k_check = 0;2339}2340j = bbits - i - 1;2341if (j >= 0) {2342b2 = 0;2343s2 = j;2344}2345else {2346b2 = -j;2347s2 = 0;2348}2349if (k >= 0) {2350b5 = 0;2351s5 = k;2352s2 += k;2353}2354else {2355b2 -= k;2356b5 = -k;2357s5 = 0;2358}2359if (mode < 0 || mode > 9)2360mode = 0;23612362try_quick = 1;23632364if (mode > 5) {2365mode -= 4;2366try_quick = 0;2367}2368leftright = 1;2369ilim = ilim1 = -1; /* Values for cases 0 and 1; done here to */2370/* silence erroneous "gcc -Wall" warning. */2371switch(mode) {2372case 0:2373case 1:2374i = 18;2375ndigits = 0;2376break;2377case 2:2378leftright = 0;2379/* fall through */2380case 4:2381if (ndigits <= 0)2382ndigits = 1;2383ilim = ilim1 = i = ndigits;2384break;2385case 3:2386leftright = 0;2387/* fall through */2388case 5:2389i = ndigits + k + 1;2390ilim = i;2391ilim1 = i - 1;2392if (i <= 0)2393i = 1;2394}2395s0 = rv_alloc(i);2396if (s0 == NULL)2397goto failed_malloc;2398s = s0;239924002401if (ilim >= 0 && ilim <= Quick_max && try_quick) {24022403/* Try to get by with floating-point arithmetic. */24042405i = 0;2406dval(&d2) = dval(&u);2407k0 = k;2408ilim0 = ilim;2409ieps = 2; /* conservative */2410if (k > 0) {2411ds = tens[k&0xf];2412j = k >> 4;2413if (j & Bletch) {2414/* prevent overflows */2415j &= Bletch - 1;2416dval(&u) /= bigtens[n_bigtens-1];2417ieps++;2418}2419for(; j; j >>= 1, i++)2420if (j & 1) {2421ieps++;2422ds *= bigtens[i];2423}2424dval(&u) /= ds;2425}2426else if ((j1 = -k)) {2427dval(&u) *= tens[j1 & 0xf];2428for(j = j1 >> 4; j; j >>= 1, i++)2429if (j & 1) {2430ieps++;2431dval(&u) *= bigtens[i];2432}2433}2434if (k_check && dval(&u) < 1. && ilim > 0) {2435if (ilim1 <= 0)2436goto fast_failed;2437ilim = ilim1;2438k--;2439dval(&u) *= 10.;2440ieps++;2441}2442dval(&eps) = ieps*dval(&u) + 7.;2443word0(&eps) -= (P-1)*Exp_msk1;2444if (ilim == 0) {2445S = mhi = 0;2446dval(&u) -= 5.;2447if (dval(&u) > dval(&eps))2448goto one_digit;2449if (dval(&u) < -dval(&eps))2450goto no_digits;2451goto fast_failed;2452}2453if (leftright) {2454/* Use Steele & White method of only2455* generating digits needed.2456*/2457dval(&eps) = 0.5/tens[ilim-1] - dval(&eps);2458for(i = 0;;) {2459L = (Long)dval(&u);2460dval(&u) -= L;2461*s++ = '0' + (int)L;2462if (dval(&u) < dval(&eps))2463goto ret1;2464if (1. - dval(&u) < dval(&eps))2465goto bump_up;2466if (++i >= ilim)2467break;2468dval(&eps) *= 10.;2469dval(&u) *= 10.;2470}2471}2472else {2473/* Generate ilim digits, then fix them up. */2474dval(&eps) *= tens[ilim-1];2475for(i = 1;; i++, dval(&u) *= 10.) {2476L = (Long)(dval(&u));2477if (!(dval(&u) -= L))2478ilim = i;2479*s++ = '0' + (int)L;2480if (i == ilim) {2481if (dval(&u) > 0.5 + dval(&eps))2482goto bump_up;2483else if (dval(&u) < 0.5 - dval(&eps)) {2484while(*--s == '0');2485s++;2486goto ret1;2487}2488break;2489}2490}2491}2492fast_failed:2493s = s0;2494dval(&u) = dval(&d2);2495k = k0;2496ilim = ilim0;2497}24982499/* Do we have a "small" integer? */25002501if (be >= 0 && k <= Int_max) {2502/* Yes. */2503ds = tens[k];2504if (ndigits < 0 && ilim <= 0) {2505S = mhi = 0;2506if (ilim < 0 || dval(&u) <= 5*ds)2507goto no_digits;2508goto one_digit;2509}2510for(i = 1;; i++, dval(&u) *= 10.) {2511L = (Long)(dval(&u) / ds);2512dval(&u) -= L*ds;2513*s++ = '0' + (int)L;2514if (!dval(&u)) {2515break;2516}2517if (i == ilim) {2518dval(&u) += dval(&u);2519if (dval(&u) > ds || (dval(&u) == ds && L & 1)) {2520bump_up:2521while(*--s == '9')2522if (s == s0) {2523k++;2524*s = '0';2525break;2526}2527++*s++;2528}2529else {2530/* Strip trailing zeros. This branch was missing from the2531original dtoa.c, leading to surplus trailing zeros in2532some cases. See bugs.python.org/issue40780. */2533while (s > s0 && s[-1] == '0') {2534--s;2535}2536}2537break;2538}2539}2540goto ret1;2541}25422543m2 = b2;2544m5 = b5;2545if (leftright) {2546i =2547denorm ? be + (Bias + (P-1) - 1 + 1) :25481 + P - bbits;2549b2 += i;2550s2 += i;2551mhi = i2b(1);2552if (mhi == NULL)2553goto failed_malloc;2554}2555if (m2 > 0 && s2 > 0) {2556i = m2 < s2 ? m2 : s2;2557b2 -= i;2558m2 -= i;2559s2 -= i;2560}2561if (b5 > 0) {2562if (leftright) {2563if (m5 > 0) {2564mhi = pow5mult(mhi, m5);2565if (mhi == NULL)2566goto failed_malloc;2567b1 = mult(mhi, b);2568Bfree(b);2569b = b1;2570if (b == NULL)2571goto failed_malloc;2572}2573if ((j = b5 - m5)) {2574b = pow5mult(b, j);2575if (b == NULL)2576goto failed_malloc;2577}2578}2579else {2580b = pow5mult(b, b5);2581if (b == NULL)2582goto failed_malloc;2583}2584}2585S = i2b(1);2586if (S == NULL)2587goto failed_malloc;2588if (s5 > 0) {2589S = pow5mult(S, s5);2590if (S == NULL)2591goto failed_malloc;2592}25932594/* Check for special case that d is a normalized power of 2. */25952596spec_case = 0;2597if ((mode < 2 || leftright)2598) {2599if (!word1(&u) && !(word0(&u) & Bndry_mask)2600&& word0(&u) & (Exp_mask & ~Exp_msk1)2601) {2602/* The special case */2603b2 += Log2P;2604s2 += Log2P;2605spec_case = 1;2606}2607}26082609/* Arrange for convenient computation of quotients:2610* shift left if necessary so divisor has 4 leading 0 bits.2611*2612* Perhaps we should just compute leading 28 bits of S once2613* and for all and pass them and a shift to quorem, so it2614* can do shifts and ors to compute the numerator for q.2615*/2616#define iInc 282617i = dshift(S, s2);2618b2 += i;2619m2 += i;2620s2 += i;2621if (b2 > 0) {2622b = lshift(b, b2);2623if (b == NULL)2624goto failed_malloc;2625}2626if (s2 > 0) {2627S = lshift(S, s2);2628if (S == NULL)2629goto failed_malloc;2630}2631if (k_check) {2632if (cmp(b,S) < 0) {2633k--;2634b = multadd(b, 10, 0); /* we botched the k estimate */2635if (b == NULL)2636goto failed_malloc;2637if (leftright) {2638mhi = multadd(mhi, 10, 0);2639if (mhi == NULL)2640goto failed_malloc;2641}2642ilim = ilim1;2643}2644}2645if (ilim <= 0 && (mode == 3 || mode == 5)) {2646if (ilim < 0) {2647/* no digits, fcvt style */2648no_digits:2649k = -1 - ndigits;2650goto ret;2651}2652else {2653S = multadd(S, 5, 0);2654if (S == NULL)2655goto failed_malloc;2656if (cmp(b, S) <= 0)2657goto no_digits;2658}2659one_digit:2660*s++ = '1';2661k++;2662goto ret;2663}2664if (leftright) {2665if (m2 > 0) {2666mhi = lshift(mhi, m2);2667if (mhi == NULL)2668goto failed_malloc;2669}26702671/* Compute mlo -- check for special case2672* that d is a normalized power of 2.2673*/26742675mlo = mhi;2676if (spec_case) {2677mhi = Balloc(mhi->k);2678if (mhi == NULL)2679goto failed_malloc;2680Bcopy(mhi, mlo);2681mhi = lshift(mhi, Log2P);2682if (mhi == NULL)2683goto failed_malloc;2684}26852686for(i = 1;;i++) {2687dig = quorem(b,S) + '0';2688/* Do we yet have the shortest decimal string2689* that will round to d?2690*/2691j = cmp(b, mlo);2692delta = diff(S, mhi);2693if (delta == NULL)2694goto failed_malloc;2695j1 = delta->sign ? 1 : cmp(b, delta);2696Bfree(delta);2697if (j1 == 0 && mode != 1 && !(word1(&u) & 1)2698) {2699if (dig == '9')2700goto round_9_up;2701if (j > 0)2702dig++;2703*s++ = dig;2704goto ret;2705}2706if (j < 0 || (j == 0 && mode != 12707&& !(word1(&u) & 1)2708)) {2709if (!b->x[0] && b->wds <= 1) {2710goto accept_dig;2711}2712if (j1 > 0) {2713b = lshift(b, 1);2714if (b == NULL)2715goto failed_malloc;2716j1 = cmp(b, S);2717if ((j1 > 0 || (j1 == 0 && dig & 1))2718&& dig++ == '9')2719goto round_9_up;2720}2721accept_dig:2722*s++ = dig;2723goto ret;2724}2725if (j1 > 0) {2726if (dig == '9') { /* possible if i == 1 */2727round_9_up:2728*s++ = '9';2729goto roundoff;2730}2731*s++ = dig + 1;2732goto ret;2733}2734*s++ = dig;2735if (i == ilim)2736break;2737b = multadd(b, 10, 0);2738if (b == NULL)2739goto failed_malloc;2740if (mlo == mhi) {2741mlo = mhi = multadd(mhi, 10, 0);2742if (mlo == NULL)2743goto failed_malloc;2744}2745else {2746mlo = multadd(mlo, 10, 0);2747if (mlo == NULL)2748goto failed_malloc;2749mhi = multadd(mhi, 10, 0);2750if (mhi == NULL)2751goto failed_malloc;2752}2753}2754}2755else2756for(i = 1;; i++) {2757*s++ = dig = quorem(b,S) + '0';2758if (!b->x[0] && b->wds <= 1) {2759goto ret;2760}2761if (i >= ilim)2762break;2763b = multadd(b, 10, 0);2764if (b == NULL)2765goto failed_malloc;2766}27672768/* Round off last digit */27692770b = lshift(b, 1);2771if (b == NULL)2772goto failed_malloc;2773j = cmp(b, S);2774if (j > 0 || (j == 0 && dig & 1)) {2775roundoff:2776while(*--s == '9')2777if (s == s0) {2778k++;2779*s++ = '1';2780goto ret;2781}2782++*s++;2783}2784else {2785while(*--s == '0');2786s++;2787}2788ret:2789Bfree(S);2790if (mhi) {2791if (mlo && mlo != mhi)2792Bfree(mlo);2793Bfree(mhi);2794}2795ret1:2796Bfree(b);2797*s = 0;2798*decpt = k + 1;2799if (rve)2800*rve = s;2801return s0;2802failed_malloc:2803if (S)2804Bfree(S);2805if (mlo && mlo != mhi)2806Bfree(mlo);2807if (mhi)2808Bfree(mhi);2809if (b)2810Bfree(b);2811if (s0)2812_Py_dg_freedtoa(s0);2813return NULL;2814}2815#ifdef __cplusplus2816}2817#endif28182819#endif // _PY_SHORT_FLOAT_REPR == 1282028212822