/****************************************************************
*
* The author of this software is David M. Gay.
*
* Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose without fee is hereby granted, provided that this entire notice
* is included in all copies of any software which is or includes a copy
* or modification of this software and in all copies of the supporting
* documentation for such software.
*
* THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
* REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
* OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
*
***************************************************************/
/****************************************************************
* This is dtoa.c by David M. Gay, downloaded from
* http://www.netlib.org/fp/dtoa.c on April 15, 2009 and modified for
* inclusion into the Python core by Mark E. T. Dickinson and Eric V. Smith.
*
* Please remember to check http://www.netlib.org/fp regularly (and especially
* before any Python release) for bugfixes and updates.
*
* The major modifications from Gay's original code are as follows:
*
* 0. The original code has been specialized to Python's needs by removing
* many of the #ifdef'd sections. In particular, code to support VAX and
* IBM floating-point formats, hex NaNs, hex floats, locale-aware
* treatment of the decimal point, and setting of the inexact flag have
* been removed.
*
* 1. We use PyMem_Malloc and PyMem_Free in place of malloc and free.
*
* 2. The public functions strtod, dtoa and freedtoa all now have
* a _Py_dg_ prefix.
*
* 3. Instead of assuming that PyMem_Malloc always succeeds, we thread
* PyMem_Malloc failures through the code. The functions
*
* Balloc, multadd, s2b, i2b, mult, pow5mult, lshift, diff, d2b
*
* of return type *Bigint all return NULL to indicate a malloc failure.
* Similarly, rv_alloc and nrv_alloc (return type char *) return NULL on
* failure. bigcomp now has return type int (it used to be void) and
* returns -1 on failure and 0 otherwise. _Py_dg_dtoa returns NULL
* on failure. _Py_dg_strtod indicates failure due to malloc failure
* by returning -1.0, setting errno=ENOMEM and *se to s00.
*
* 4. The static variable dtoa_result has been removed. Callers of
* _Py_dg_dtoa are expected to call _Py_dg_freedtoa to free
* the memory allocated by _Py_dg_dtoa.
*
* 5. The code has been reformatted to better fit with Python's
* C style guide (PEP 7).
*
* 6. A bug in the memory allocation has been fixed: to avoid FREEing memory
* that hasn't been MALLOC'ed, private_mem should only be used when k L[1]
#define word1(x) (x)->L[0]
#else
#define word0(x) (x)->L[0]
#define word1(x) (x)->L[1]
#endif
#define dval(x) (x)->d
#ifndef STRTOD_DIGLIM
#define STRTOD_DIGLIM 40
#endif
/* maximum permitted exponent value for strtod; exponents larger than
MAX_ABS_EXP in absolute value get truncated to +-MAX_ABS_EXP. MAX_ABS_EXP
should fit into an int. */
#ifndef MAX_ABS_EXP
#define MAX_ABS_EXP 1100000000U
#endif
/* Bound on length of pieces of input strings in _Py_dg_strtod; specifically,
this is used to bound the total number of digits ignoring leading zeros and
the number of digits that follow the decimal point. Ideally, MAX_DIGITS
should satisfy MAX_DIGITS + 400 < MAX_ABS_EXP; that ensures that the
exponent clipping in _Py_dg_strtod can't affect the value of the output. */
#ifndef MAX_DIGITS
#define MAX_DIGITS 1000000000U
#endif
/* Guard against trying to use the above values on unusual platforms with ints
* of width less than 32 bits. */
#if MAX_ABS_EXP > INT_MAX
#error "MAX_ABS_EXP should fit in an int"
#endif
#if MAX_DIGITS > INT_MAX
#error "MAX_DIGITS should fit in an int"
#endif
/* The following definition of Storeinc is appropriate for MIPS processors.
* An alternative that might be better on some machines is
* #define Storeinc(a,b,c) (*a++ = b wds >= 1, and either x->wds == 1 or x[wds-1] is nonzero.
The Bigint fields are as follows:
- next is a header used by Balloc and Bfree to keep track of lists
of freed Bigints; it's also used for the linked list of
powers of 5 of the form 5**2**i used by pow5mult.
- k indicates which pool this Bigint was allocated from
- maxwds is the maximum number of words space was allocated for
(usually maxwds == 2**k)
- sign is 1 for negative Bigints, 0 for positive. The sign is unused
(ignored on inputs, set to 0 on outputs) in almost all operations
involving Bigints: a notable exception is the diff function, which
ignores signs on inputs but sets the sign of the output correctly.
- wds is the actual number of significant words
- x contains the vector of words (digits) for this Bigint, from least
significant (x[0]) to most significant (x[wds-1]).
*/
struct
Bigint {
struct Bigint *next;
int k, maxwds, sign, wds;
ULong x[1];
};
typedef struct Bigint Bigint;
#ifndef Py_USING_MEMORY_DEBUGGER
/* Memory management: memory is allocated from, and returned to, Kmax+1 pools
of memory, where pool k (0 >= 2))
return b;
p5 = p5s;
if (!p5) {
/* first time */
p5 = i2b(625);
if (p5 == NULL) {
Bfree(b);
return NULL;
}
p5s = p5;
p5->next = 0;
}
for(;;) {
if (k & 1) {
b1 = mult(b, p5);
Bfree(b);
b = b1;
if (b == NULL)
return NULL;
}
if (!(k >>= 1))
break;
p51 = p5->next;
if (!p51) {
p51 = mult(p5,p5);
if (p51 == NULL) {
Bfree(b);
return NULL;
}
p51->next = 0;
p5->next = p51;
}
p5 = p51;
}
return b;
}
#else
/* Version of pow5mult that doesn't cache powers of 5. Provided for
the benefit of memory debugging tools like Valgrind. */
static Bigint *
pow5mult(Bigint *b, int k)
{
Bigint *b1, *p5, *p51;
int i;
static const int p05[3] = { 5, 25, 125 };
if ((i = k & 3)) {
b = multadd(b, p05[i-1], 0);
if (b == NULL)
return NULL;
}
if (!(k >>= 2))
return b;
p5 = i2b(625);
if (p5 == NULL) {
Bfree(b);
return NULL;
}
for(;;) {
if (k & 1) {
b1 = mult(b, p5);
Bfree(b);
b = b1;
if (b == NULL) {
Bfree(p5);
return NULL;
}
}
if (!(k >>= 1))
break;
p51 = mult(p5, p5);
Bfree(p5);
p5 = p51;
if (p5 == NULL) {
Bfree(b);
return NULL;
}
}
Bfree(p5);
return b;
}
#endif /* Py_USING_MEMORY_DEBUGGER */
/* shift a Bigint b left by k bits. Return a pointer to the shifted result,
or NULL on failure. If the returned pointer is distinct from b then the
original b will have been Bfree'd. Ignores the sign of b. */
static Bigint *
lshift(Bigint *b, int k)
{
int i, k1, n, n1;
Bigint *b1;
ULong *x, *x1, *xe, z;
if (!k || (!b->x[0] && b->wds == 1))
return b;
n = k >> 5;
k1 = b->k;
n1 = n + b->wds + 1;
for(i = b->maxwds; n1 > i; i x;
xe = x + b->wds;
if (k &= 0x1f) {
k1 = 32 - k;
z = 0;
do {
*x1++ = *x > k1;
}
while(x < xe);
if ((*x1 = z))
++n1;
}
else do
*x1++ = *x++;
while(x < xe);
b1->wds = n1 - 1;
Bfree(b);
return b1;
}
/* Do a three-way compare of a and b, returning -1 if a < b, 0 if a == b and
1 if a > b. Ignores signs of a and b. */
static int
cmp(Bigint *a, Bigint *b)
{
ULong *xa, *xa0, *xb, *xb0;
int i, j;
i = a->wds;
j = b->wds;
#ifdef DEBUG
if (i > 1 && !a->x[i-1])
Bug("cmp called with a->x[a->wds-1] == 0");
if (j > 1 && !b->x[j-1])
Bug("cmp called with b->x[b->wds-1] == 0");
#endif
if (i -= j)
return i;
xa0 = a->x;
xa = xa0 + j;
xb0 = b->x;
xb = xb0 + j;
for(;;) {
if (*--xa != *--xb)
return *xa < *xb ? -1 : 1;
if (xa wds = 1;
c->x[0] = 0;
return c;
}
if (i < 0) {
c = a;
a = b;
b = c;
i = 1;
}
else
i = 0;
c = Balloc(a->k);
if (c == NULL)
return NULL;
c->sign = i;
wa = a->wds;
xa = a->x;
xae = xa + wa;
wb = b->wds;
xb = b->x;
xbe = xb + wb;
xc = c->x;
borrow = 0;
do {
y = (ULLong)*xa++ - *xb++ - borrow;
borrow = y >> 32 & (ULong)1;
*xc++ = (ULong)(y & FFFFFFFF);
}
while(xb < xbe);
while(xa < xae) {
y = *xa++ - borrow;
borrow = y >> 32 & (ULong)1;
*xc++ = (ULong)(y & FFFFFFFF);
}
while(!*--xc)
wa--;
c->wds = wa;
return c;
}
/* Given a positive normal double x, return the difference between x and the
next double up. Doesn't give correct results for subnormals. */
static double
ulp(U *x)
{
Long L;
U u;
L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1;
word0(&u) = L;
word1(&u) = 0;
return dval(&u);
}
/* Convert a Bigint to a double plus an exponent */
static double
b2d(Bigint *a, int *e)
{
ULong *xa, *xa0, w, y, z;
int k;
U d;
xa0 = a->x;
xa = xa0 + a->wds;
y = *--xa;
#ifdef DEBUG
if (!y) Bug("zero y in b2d");
#endif
k = hi0bits(y);
*e = 32 - k;
if (k < Ebits) {
word0(&d) = Exp_1 | y >> (Ebits - k);
w = xa > xa0 ? *--xa : 0;
word1(&d) = y > (Ebits - k);
goto ret_d;
}
z = xa > xa0 ? *--xa : 0;
if (k -= Ebits) {
word0(&d) = Exp_1 | y > (32 - k);
y = xa > xa0 ? *--xa : 0;
word1(&d) = z > (32 - k);
}
else {
word0(&d) = Exp_1 | y;
word1(&d) = z;
}
ret_d:
return dval(&d);
}
/* Convert a scaled double to a Bigint plus an exponent. Similar to d2b,
except that it accepts the scale parameter used in _Py_dg_strtod (which
should be either 0 or 2*P), and the normalization for the return value is
different (see below). On input, d should be finite and nonnegative, and d
/ 2**scale should be exactly representable as an IEEE 754 double.
Returns a Bigint b and an integer e such that
dval(d) / 2**scale = b * 2**e.
Unlike d2b, b is not necessarily odd: b and e are normalized so
that either 2**(P-1) = Etiny, or b < 2**P
and e == Etiny. This applies equally to an input of 0.0: in that
case the return values are b = 0 and e = Etiny.
The above normalization ensures that for all possible inputs d,
2**e gives ulp(d/2**scale).
Returns NULL on failure.
*/
static Bigint *
sd2b(U *d, int scale, int *e)
{
Bigint *b;
b = Balloc(1);
if (b == NULL)
return NULL;
/* First construct b and e assuming that scale == 0. */
b->wds = 2;
b->x[0] = word1(d);
b->x[1] = word0(d) & Frac_mask;
*e = Etiny - 1 + (int)((word0(d) & Exp_mask) >> Exp_shift);
if (*e < Etiny)
*e = Etiny;
else
b->x[1] |= Exp_msk1;
/* Now adjust for scale, provided that b != 0. */
if (scale && (b->x[0] || b->x[1])) {
*e -= scale;
if (*e < Etiny) {
scale = Etiny - *e;
*e = Etiny;
/* We can't shift more than P-1 bits without shifting out a 1. */
assert(0 < scale && scale = 32) {
/* The bits shifted out should all be zero. */
assert(b->x[0] == 0);
b->x[0] = b->x[1];
b->x[1] = 0;
scale -= 32;
}
if (scale) {
/* The bits shifted out should all be zero. */
assert(b->x[0] x[0] = (b->x[0] >> scale) | (b->x[1] x[1] >>= scale;
}
}
}
/* Ensure b is normalized. */
if (!b->x[1])
b->wds = 1;
return b;
}
/* Convert a double to a Bigint plus an exponent. Return NULL on failure.
Given a finite nonzero double d, return an odd Bigint b and exponent *e
such that fabs(d) = b * 2**e. On return, *bbits gives the number of
significant bits of b; that is, 2**(*bbits-1) x;
z = word0(d) & Frac_mask;
word0(d) &= 0x7fffffff; /* clear sign bit, which we ignore */
if ((de = (int)(word0(d) >> Exp_shift)))
z |= Exp_msk1;
if ((y = word1(d))) {
if ((k = lo0bits(&y))) {
x[0] = y | z >= k;
}
else
x[0] = y;
i =
b->wds = (x[1] = z) ? 2 : 1;
}
else {
k = lo0bits(&z);
x[0] = z;
i =
b->wds = 1;
k += 32;
}
if (de) {
*e = de - Bias - (P-1) + k;
*bits = P - k;
}
else {
*e = de - Bias - (P-1) + 1 + k;
*bits = 32*i - hi0bits(x[i-1]);
}
return b;
}
/* Compute the ratio of two Bigints, as a double. The result may have an
error of up to 2.5 ulps. */
static double
ratio(Bigint *a, Bigint *b)
{
U da, db;
int k, ka, kb;
dval(&da) = b2d(a, &ka);
dval(&db) = b2d(b, &kb);
k = ka - kb + 32*(a->wds - b->wds);
if (k > 0)
word0(&da) += k*Exp_msk1;
else {
k = -k;
word0(&db) += k*Exp_msk1;
}
return dval(&da) / dval(&db);
}
static const double
tens[] = {
1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
1e20, 1e21, 1e22
};
static const double
bigtens[] = { 1e16, 1e32, 1e64, 1e128, 1e256 };
static const double tinytens[] = { 1e-16, 1e-32, 1e-64, 1e-128,
9007199254740992.*9007199254740992.e-256
/* = 2^106 * 1e-256 */
};
/* The factor of 2^53 in tinytens[4] helps us avoid setting the underflow */
/* flag unnecessarily. It leads to a song and dance at the end of strtod. */
#define Scale_Bit 0x10
#define n_bigtens 5
#define ULbits 32
#define kshift 5
#define kmask 31
static int
dshift(Bigint *b, int p2)
{
int rv = hi0bits(b->x[b->wds-1]) - 4;
if (p2 > 0)
rv -= p2;
return rv & kmask;
}
/* special case of Bigint division. The quotient is always in the range 0 wds;
#ifdef DEBUG
/*debug*/ if (b->wds > n)
/*debug*/ Bug("oversize b in quorem");
#endif
if (b->wds < n)
return 0;
sx = S->x;
sxe = sx + --n;
bx = b->x;
bxe = bx + n;
q = *bxe / (*sxe + 1); /* ensure q 9)
/*debug*/ Bug("oversized quotient in quorem");
#endif
if (q) {
borrow = 0;
carry = 0;
do {
ys = *sx++ * (ULLong)q + carry;
carry = ys >> 32;
y = *bx - (ys & FFFFFFFF) - borrow;
borrow = y >> 32 & (ULong)1;
*bx++ = (ULong)(y & FFFFFFFF);
}
while(sx x;
while(--bxe > bx && !*bxe)
--n;
b->wds = n;
}
}
if (cmp(b, S) >= 0) {
q++;
borrow = 0;
carry = 0;
bx = b->x;
sx = S->x;
do {
ys = *sx++ + carry;
carry = ys >> 32;
y = *bx - (ys & FFFFFFFF) - borrow;
borrow = y >> 32 & (ULong)1;
*bx++ = (ULong)(y & FFFFFFFF);
}
while(sx x;
bxe = bx + n;
if (!*bxe) {
while(--bxe > bx && !*bxe)
--n;
b->wds = n;
}
}
return q;
}
/* sulp(x) is a version of ulp(x) that takes bc.scale into account.
Assuming that x is finite and nonnegative (positive zero is fine
here) and x / 2^bc.scale is exactly representable as a double,
sulp(x) is equivalent to 2^bc.scale * ulp(x / 2^bc.scale). */
static double
sulp(U *x, BCinfo *bc)
{
U u;
if (bc->scale && 2*P + 1 > (int)((word0(x) & Exp_mask) >> Exp_shift)) {
/* rv/2^bc->scale is subnormal */
word0(&u) = (P+2)*Exp_msk1;
word1(&u) = 0;
return u.d;
}
else {
assert(word0(x) || word1(x)); /* x != 0.0 */
return ulp(x);
}
}
/* The bigcomp function handles some hard cases for strtod, for inputs
with more than STRTOD_DIGLIM digits. It's called once an initial
estimate for the double corresponding to the input string has
already been obtained by the code in _Py_dg_strtod.
The bigcomp function is only called after _Py_dg_strtod has found a
double value rv such that either rv or rv + 1ulp represents the
correctly rounded value corresponding to the original string. It
determines which of these two values is the correct one by
computing the decimal digits of rv + 0.5ulp and comparing them with
the corresponding digits of s0.
In the following, write dv for the absolute value of the number represented
by the input string.
Inputs:
s0 points to the first significant digit of the input string.
rv is a (possibly scaled) estimate for the closest double value to the
value represented by the original input to _Py_dg_strtod. If
bc->scale is nonzero, then rv/2^(bc->scale) is the approximation to
the input value.
bc is a struct containing information gathered during the parsing and
estimation steps of _Py_dg_strtod. Description of fields follows:
bc->e0 gives the exponent of the input value, such that dv = (integer
given by the bd->nd digits of s0) * 10**e0
bc->nd gives the total number of significant digits of s0. It will
be at least 1.
bc->nd0 gives the number of significant digits of s0 before the
decimal separator. If there's no decimal separator, bc->nd0 ==
bc->nd.
bc->scale is the value used to scale rv to avoid doing arithmetic with
subnormal values. It's either 0 or 2*P (=106).
Outputs:
On successful exit, rv/2^(bc->scale) is the closest double to dv.
Returns 0 on success, -1 on failure (e.g., due to a failed malloc call). */
static int
bigcomp(U *rv, const char *s0, BCinfo *bc)
{
Bigint *b, *d;
int b2, d2, dd, i, nd, nd0, odd, p2, p5;
nd = bc->nd;
nd0 = bc->nd0;
p5 = nd + bc->e0;
b = sd2b(rv, bc->scale, &p2);
if (b == NULL)
return -1;
/* record whether the lsb of rv/2^(bc->scale) is odd: in the exact halfway
case, this is used for round to even. */
odd = b->x[0] & 1;
/* left shift b by 1 bit and or a 1 into the least significant bit;
this gives us b * 2**p2 = rv/2^(bc->scale) + 0.5 ulp. */
b = lshift(b, 1);
if (b == NULL)
return -1;
b->x[0] |= 1;
p2--;
p2 -= p5;
d = i2b(1);
if (d == NULL) {
Bfree(b);
return -1;
}
/* Arrange for convenient computation of quotients:
* shift left if necessary so divisor has 4 leading 0 bits.
*/
if (p5 > 0) {
d = pow5mult(d, p5);
if (d == NULL) {
Bfree(b);
return -1;
}
}
else if (p5 < 0) {
b = pow5mult(b, -p5);
if (b == NULL) {
Bfree(d);
return -1;
}
}
if (p2 > 0) {
b2 = p2;
d2 = 0;
}
else {
b2 = 0;
d2 = -p2;
}
i = dshift(d, d2);
if ((b2 += i) > 0) {
b = lshift(b, b2);
if (b == NULL) {
Bfree(d);
return -1;
}
}
if ((d2 += i) > 0) {
d = lshift(d, d2);
if (d == NULL) {
Bfree(b);
return -1;
}
}
/* Compare s0 with b/d: set dd to -1, 0, or 1 according as s0 < b/d, s0 ==
* b/d, or s0 > b/d. Here the digits of s0 are thought of as representing
* a number in the range [0.1, 1). */
if (cmp(b, d) >= 0)
/* b/d >= 1 */
dd = -1;
else {
i = 0;
for(;;) {
b = multadd(b, 10, 0);
if (b == NULL) {
Bfree(d);
return -1;
}
dd = s0[i < nd0 ? i : i+1] - '0' - quorem(b, d);
i++;
if (dd)
break;
if (!b->x[0] && b->wds == 1) {
/* b/d == 0 */
dd = i < nd;
break;
}
if (!(i < nd)) {
/* b/d != 0, but digits of s0 exhausted */
dd = -1;
break;
}
}
}
Bfree(b);
Bfree(d);
if (dd > 0 || (dd == 0 && odd))
dval(rv) += sulp(rv, bc);
return 0;
}
/* Return a 'standard' NaN value.
There are exactly two quiet NaNs that don't arise by 'quieting' signaling
NaNs (see IEEE 754-2008, section 6.2.1). If sign == 0, return the one whose
sign bit is cleared. Otherwise, return the one whose sign bit is set.
*/
double
_Py_dg_stdnan(int sign)
{
U rv;
word0(&rv) = NAN_WORD0;
word1(&rv) = NAN_WORD1;
if (sign)
word0(&rv) |= Sign_bit;
return dval(&rv);
}
/* Return positive or negative infinity, according to the given sign (0 for
* positive infinity, 1 for negative infinity). */
double
_Py_dg_infinity(int sign)
{
U rv;
word0(&rv) = POSINF_WORD0;
word1(&rv) = POSINF_WORD1;
return sign ? -dval(&rv) : dval(&rv);
}
double
_Py_dg_strtod(const char *s00, char **se)
{
int bb2, bb5, bbe, bd2, bd5, bs2, c, dsign, e, e1, error;
int esign, i, j, k, lz, nd, nd0, odd, sign;
const char *s, *s0, *s1;
double aadj, aadj1;
U aadj2, adj, rv, rv0;
ULong y, z, abs_exp;
Long L;
BCinfo bc;
Bigint *bb = NULL, *bd = NULL, *bd0 = NULL, *bs = NULL, *delta = NULL;
size_t ndigits, fraclen;
double result;
dval(&rv) = 0.;
/* Start parsing. */
c = *(s = s00);
/* Parse optional sign, if present. */
sign = 0;
switch (c) {
case '-':
sign = 1;
/* fall through */
case '+':
c = *++s;
}
/* Skip leading zeros: lz is true iff there were leading zeros. */
s1 = s;
while (c == '0')
c = *++s;
lz = s != s1;
/* Point s0 at the first nonzero digit (if any). fraclen will be the
number of digits between the decimal point and the end of the
digit string. ndigits will be the total number of digits ignoring
leading zeros. */
s0 = s1 = s;
while ('0' DBL_MAX_10_EXP)
goto ovfl;
e1 >>= 4;
for(j = 0; e1 > 1; j++, e1 >>= 1)
if (e1 & 1)
dval(&rv) *= bigtens[j];
/* The last multiplication could overflow. */
word0(&rv) -= P*Exp_msk1;
dval(&rv) *= bigtens[j];
if ((z = word0(&rv) & Exp_mask)
> Exp_msk1*(DBL_MAX_EXP+Bias-P))
goto ovfl;
if (z > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) {
/* set to largest number */
/* (Can't trust DBL_MAX) */
word0(&rv) = Big0;
word1(&rv) = Big1;
}
else
word0(&rv) += P*Exp_msk1;
}
}
else if (e1 < 0) {
/* The input decimal value lies in [10**e1, 10**(e1+16)).
If e1 >= 4) {
if (e1 >= 1 0; j++, e1 >>= 1)
if (e1 & 1)
dval(&rv) *= tinytens[j];
if (bc.scale && (j = 2*P + 1 - ((word0(&rv) & Exp_mask)
>> Exp_shift)) > 0) {
/* scaled rv is denormal; clear j low bits */
if (j >= 32) {
word1(&rv) = 0;
if (j >= 53)
word0(&rv) = (P+2)*Exp_msk1;
else
word0(&rv) &= 0xffffffff STRTOD_DIGLIM) {
/* ASSERT(STRTOD_DIGLIM >= 18); 18 == one more than the */
/* minimum number of decimal digits to distinguish double values */
/* in IEEE arithmetic. */
/* Truncate input to 18 significant digits, then discard any trailing
zeros on the result by updating nd, nd0, e and y suitably. (There's
no need to update z; it's not reused beyond this point.) */
for (i = 18; i > 0; ) {
/* scan back until we hit a nonzero digit. significant digit 'i'
is s0[i] if i < nd0, s0[i+1] if i >= nd0. */
--i;
if (s0[i < nd0 ? i : i+1] != '0') {
++i;
break;
}
}
e += nd - i;
nd = i;
if (nd0 > nd)
nd0 = nd;
if (nd < 9) { /* must recompute y */
y = 0;
for(i = 0; i < nd0; ++i)
y = 10*y + s0[i] - '0';
for(; i < nd; ++i)
y = 10*y + s0[i+1] - '0';
}
}
bd0 = s2b(s0, nd0, nd, y);
if (bd0 == NULL)
goto failed_malloc;
/* Notation for the comments below. Write:
- dv for the absolute value of the number represented by the original
decimal input string.
- if we've truncated dv, write tdv for the truncated value.
Otherwise, set tdv == dv.
- srv for the quantity rv/2^bc.scale; so srv is the current binary
approximation to tdv (and dv). It should be exactly representable
in an IEEE 754 double.
*/
for(;;) {
/* This is the main correction loop for _Py_dg_strtod.
We've got a decimal value tdv, and a floating-point approximation
srv=rv/2^bc.scale to tdv. The aim is to determine whether srv is
close enough (i.e., within 0.5 ulps) to tdv, and to compute a new
approximation if not.
To determine whether srv is close enough to tdv, compute integers
bd, bb and bs proportional to tdv, srv and 0.5 ulp(srv)
respectively, and then use integer arithmetic to determine whether
|tdv - srv| is less than, equal to, or greater than 0.5 ulp(srv).
*/
bd = Balloc(bd0->k);
if (bd == NULL) {
goto failed_malloc;
}
Bcopy(bd, bd0);
bb = sd2b(&rv, bc.scale, &bbe); /* srv = bb * 2^bbe */
if (bb == NULL) {
goto failed_malloc;
}
/* Record whether lsb of bb is odd, in case we need this
for the round-to-even step later. */
odd = bb->x[0] & 1;
/* tdv = bd * 10**e; srv = bb * 2**bbe */
bs = i2b(1);
if (bs == NULL) {
goto failed_malloc;
}
if (e >= 0) {
bb2 = bb5 = 0;
bd2 = bd5 = e;
}
else {
bb2 = bb5 = -e;
bd2 = bd5 = 0;
}
if (bbe >= 0)
bb2 += bbe;
else
bd2 -= bbe;
bs2 = bb2;
bb2++;
bd2++;
/* At this stage bd5 - bb5 == e == bd2 - bb2 + bbe, bb2 - bs2 == 1,
and bs == 1, so:
tdv == bd * 10**e = bd * 2**(bbe - bb2 + bd2) * 5**(bd5 - bb5)
srv == bb * 2**bbe = bb * 2**(bbe - bb2 + bb2)
0.5 ulp(srv) == 2**(bbe-1) = bs * 2**(bbe - bb2 + bs2)
It follows that:
M * tdv = bd * 2**bd2 * 5**bd5
M * srv = bb * 2**bb2 * 5**bb5
M * 0.5 ulp(srv) = bs * 2**bs2 * 5**bb5
for some constant M. (Actually, M == 2**(bb2 - bbe) * 5**bb5, but
this fact is not needed below.)
*/
/* Remove factor of 2**i, where i = min(bb2, bd2, bs2). */
i = bb2 < bd2 ? bb2 : bd2;
if (i > bs2)
i = bs2;
if (i > 0) {
bb2 -= i;
bd2 -= i;
bs2 -= i;
}
/* Scale bb, bd, bs by the appropriate powers of 2 and 5. */
if (bb5 > 0) {
bs = pow5mult(bs, bb5);
if (bs == NULL) {
goto failed_malloc;
}
Bigint *bb1 = mult(bs, bb);
Bfree(bb);
bb = bb1;
if (bb == NULL) {
goto failed_malloc;
}
}
if (bb2 > 0) {
bb = lshift(bb, bb2);
if (bb == NULL) {
goto failed_malloc;
}
}
if (bd5 > 0) {
bd = pow5mult(bd, bd5);
if (bd == NULL) {
goto failed_malloc;
}
}
if (bd2 > 0) {
bd = lshift(bd, bd2);
if (bd == NULL) {
goto failed_malloc;
}
}
if (bs2 > 0) {
bs = lshift(bs, bs2);
if (bs == NULL) {
goto failed_malloc;
}
}
/* Now bd, bb and bs are scaled versions of tdv, srv and 0.5 ulp(srv),
respectively. Compute the difference |tdv - srv|, and compare
with 0.5 ulp(srv). */
delta = diff(bb, bd);
if (delta == NULL) {
goto failed_malloc;
}
dsign = delta->sign;
delta->sign = 0;
i = cmp(delta, bs);
if (bc.nd > nd && i like 0, but with Steele & White stopping rule;
e.g. with IEEE P754 arithmetic , mode 0 gives
1e23 whereas mode 1 gives 9.999999999999999e22.
2 ==> max(1,ndigits) significant digits. This gives a
return value similar to that of ecvt, except
that trailing zeros are suppressed.
3 ==> through ndigits past the decimal point. This
gives a return value similar to that from fcvt,
except that trailing zeros are suppressed, and
ndigits can be negative.
4,5 ==> similar to 2 and 3, respectively, but (in
round-nearest mode) with the tests of mode 0 to
possibly return a shorter string that rounds to d.
With IEEE arithmetic and compilation with
-DHonor_FLT_ROUNDS, modes 4 and 5 behave the same
as modes 2 and 3 when FLT_ROUNDS != 1.
6-9 ==> Debugging modes similar to mode - 4: don't try
fast floating-point estimate (if applicable).
Values of mode other than 0-9 are treated as mode 0.
Sufficient space is allocated to the return value
to hold the suppressed trailing zeros.
*/
int bbits, b2, b5, be, dig, i, ieps, ilim, ilim0, ilim1,
j, j1, k, k0, k_check, leftright, m2, m5, s2, s5,
spec_case, try_quick;
Long L;
int denorm;
ULong x;
Bigint *b, *b1, *delta, *mlo, *mhi, *S;
U d2, eps, u;
double ds;
char *s, *s0;
/* set pointers to NULL, to silence gcc compiler warnings and make
cleanup easier on error */
mlo = mhi = S = 0;
s0 = 0;
u.d = dd;
if (word0(&u) & Sign_bit) {
/* set sign for everything, including 0's and NaNs */
*sign = 1;
word0(&u) &= ~Sign_bit; /* clear sign bit */
}
else
*sign = 0;
/* quick return for Infinities, NaNs and zeros */
if ((word0(&u) & Exp_mask) == Exp_mask)
{
/* Infinity or NaN */
*decpt = 9999;
if (!word1(&u) && !(word0(&u) & 0xfffff))
return nrv_alloc("Infinity", rve, 8);
return nrv_alloc("NaN", rve, 3);
}
if (!dval(&u)) {
*decpt = 1;
return nrv_alloc("0", rve, 1);
}
/* compute k = floor(log10(d)). The computation may leave k
one too large, but should never leave k too small. */
b = d2b(&u, &be, &bbits);
if (b == NULL)
goto failed_malloc;
if ((i = (int)(word0(&u) >> Exp_shift1 & (Exp_mask>>Exp_shift1)))) {
dval(&d2) = dval(&u);
word0(&d2) &= Frac_mask1;
word0(&d2) |= Exp_11;
/* log(x) ~=~ log(1.5) + (x-1.5)/1.5
* log10(x) = log(x) / log(10)
* ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10))
* log10(d) = (i-Bias)*log(2)/log(10) + log10(d2)
*
* This suggests computing an approximation k to log10(d) by
*
* k = (i - Bias)*0.301029995663981
* + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 );
*
* We want k to be too large rather than too small.
* The error in the first-order Taylor series approximation
* is in our favor, so we just round up the constant enough
* to compensate for any error in the multiplication of
* (i - Bias) by 0.301029995663981; since |i - Bias| 32 ? word0(&u) > (i - 32)
: word1(&u) = 0 && k = 0) {
b2 = 0;
s2 = j;
}
else {
b2 = -j;
s2 = 0;
}
if (k >= 0) {
b5 = 0;
s5 = k;
s2 += k;
}
else {
b2 -= k;
b5 = -k;
s5 = 0;
}
if (mode < 0 || mode > 9)
mode = 0;
try_quick = 1;
if (mode > 5) {
mode -= 4;
try_quick = 0;
}
leftright = 1;
ilim = ilim1 = -1; /* Values for cases 0 and 1; done here to */
/* silence erroneous "gcc -Wall" warning. */
switch(mode) {
case 0:
case 1:
i = 18;
ndigits = 0;
break;
case 2:
leftright = 0;
/* fall through */
case 4:
if (ndigits > 4;
if (j & Bletch) {
/* prevent overflows */
j &= Bletch - 1;
dval(&u) /= bigtens[n_bigtens-1];
ieps++;
}
for(; j; j >>= 1, i++)
if (j & 1) {
ieps++;
ds *= bigtens[i];
}
dval(&u) /= ds;
}
else if ((j1 = -k)) {
dval(&u) *= tens[j1 & 0xf];
for(j = j1 >> 4; j; j >>= 1, i++)
if (j & 1) {
ieps++;
dval(&u) *= bigtens[i];
}
}
if (k_check && dval(&u) < 1. && ilim > 0) {
if (ilim1 dval(&eps))
goto one_digit;
if (dval(&u) < -dval(&eps))
goto no_digits;
goto fast_failed;
}
if (leftright) {
/* Use Steele & White method of only
* generating digits needed.
*/
dval(&eps) = 0.5/tens[ilim-1] - dval(&eps);
for(i = 0;;) {
L = (Long)dval(&u);
dval(&u) -= L;
*s++ = '0' + (int)L;
if (dval(&u) < dval(&eps))
goto ret1;
if (1. - dval(&u) < dval(&eps))
goto bump_up;
if (++i >= ilim)
break;
dval(&eps) *= 10.;
dval(&u) *= 10.;
}
}
else {
/* Generate ilim digits, then fix them up. */
dval(&eps) *= tens[ilim-1];
for(i = 1;; i++, dval(&u) *= 10.) {
L = (Long)(dval(&u));
if (!(dval(&u) -= L))
ilim = i;
*s++ = '0' + (int)L;
if (i == ilim) {
if (dval(&u) > 0.5 + dval(&eps))
goto bump_up;
else if (dval(&u) < 0.5 - dval(&eps)) {
while(*--s == '0');
s++;
goto ret1;
}
break;
}
}
}
fast_failed:
s = s0;
dval(&u) = dval(&d2);
k = k0;
ilim = ilim0;
}
/* Do we have a "small" integer? */
if (be >= 0 && k 0) {
i = m2 < s2 ? m2 : s2;
b2 -= i;
m2 -= i;
s2 -= i;
}
if (b5 > 0) {
if (leftright) {
if (m5 > 0) {
mhi = pow5mult(mhi, m5);
if (mhi == NULL)
goto failed_malloc;
b1 = mult(mhi, b);
Bfree(b);
b = b1;
if (b == NULL)
goto failed_malloc;
}
if ((j = b5 - m5)) {
b = pow5mult(b, j);
if (b == NULL)
goto failed_malloc;
}
}
else {
b = pow5mult(b, b5);
if (b == NULL)
goto failed_malloc;
}
}
S = i2b(1);
if (S == NULL)
goto failed_malloc;
if (s5 > 0) {
S = pow5mult(S, s5);
if (S == NULL)
goto failed_malloc;
}
/* Check for special case that d is a normalized power of 2. */
spec_case = 0;
if ((mode < 2 || leftright)
) {
if (!word1(&u) && !(word0(&u) & Bndry_mask)
&& word0(&u) & (Exp_mask & ~Exp_msk1)
) {
/* The special case */
b2 += Log2P;
s2 += Log2P;
spec_case = 1;
}
}
/* Arrange for convenient computation of quotients:
* shift left if necessary so divisor has 4 leading 0 bits.
*
* Perhaps we should just compute leading 28 bits of S once
* and for all and pass them and a shift to quorem, so it
* can do shifts and ors to compute the numerator for q.
*/
#define iInc 28
i = dshift(S, s2);
b2 += i;
m2 += i;
s2 += i;
if (b2 > 0) {
b = lshift(b, b2);
if (b == NULL)
goto failed_malloc;
}
if (s2 > 0) {
S = lshift(S, s2);
if (S == NULL)
goto failed_malloc;
}
if (k_check) {
if (cmp(b,S) < 0) {
k--;
b = multadd(b, 10, 0); /* we botched the k estimate */
if (b == NULL)
goto failed_malloc;
if (leftright) {
mhi = multadd(mhi, 10, 0);
if (mhi == NULL)
goto failed_malloc;
}
ilim = ilim1;
}
}
if (ilim k);
if (mhi == NULL)
goto failed_malloc;
Bcopy(mhi, mlo);
mhi = lshift(mhi, Log2P);
if (mhi == NULL)
goto failed_malloc;
}
for(i = 1;;i++) {
dig = quorem(b,S) + '0';
/* Do we yet have the shortest decimal string
* that will round to d?
*/
j = cmp(b, mlo);
delta = diff(S, mhi);
if (delta == NULL)
goto failed_malloc;
j1 = delta->sign ? 1 : cmp(b, delta);
Bfree(delta);
if (j1 == 0 && mode != 1 && !(word1(&u) & 1)
) {
if (dig == '9')
goto round_9_up;
if (j > 0)
dig++;
*s++ = dig;
goto ret;
}
if (j < 0 || (j == 0 && mode != 1
&& !(word1(&u) & 1)
)) {
if (!b->x[0] && b->wds 0) {
b = lshift(b, 1);
if (b == NULL)
goto failed_malloc;
j1 = cmp(b, S);
if ((j1 > 0 || (j1 == 0 && dig & 1))
&& dig++ == '9')
goto round_9_up;
}
accept_dig:
*s++ = dig;
goto ret;
}
if (j1 > 0) {
if (dig == '9') { /* possible if i == 1 */
round_9_up:
*s++ = '9';
goto roundoff;
}
*s++ = dig + 1;
goto ret;
}
*s++ = dig;
if (i == ilim)
break;
b = multadd(b, 10, 0);
if (b == NULL)
goto failed_malloc;
if (mlo == mhi) {
mlo = mhi = multadd(mhi, 10, 0);
if (mlo == NULL)
goto failed_malloc;
}
else {
mlo = multadd(mlo, 10, 0);
if (mlo == NULL)
goto failed_malloc;
mhi = multadd(mhi, 10, 0);
if (mhi == NULL)
goto failed_malloc;
}
}
}
else
for(i = 1;; i++) {
*s++ = dig = quorem(b,S) + '0';
if (!b->x[0] && b->wds = ilim)
break;
b = multadd(b, 10, 0);
if (b == NULL)
goto failed_malloc;
}
/* Round off last digit */
b = lshift(b, 1);
if (b == NULL)
goto failed_malloc;
j = cmp(b, S);
if (j > 0 || (j == 0 && dig & 1)) {
roundoff:
while(*--s == '9')
if (s == s0) {
k++;
*s++ = '1';
goto ret;
}
++*s++;
}
else {
while(*--s == '0');
s++;
}
ret:
Bfree(S);
if (mhi) {
if (mlo && mlo != mhi)
Bfree(mlo);
Bfree(mhi);
}
ret1:
Bfree(b);
*s = 0;
*decpt = k + 1;
if (rve)
*rve = s;
return s0;
failed_malloc:
if (S)
Bfree(S);
if (mlo && mlo != mhi)
Bfree(mlo);
if (mhi)
Bfree(mhi);
if (b)
Bfree(b);
if (s0)
_Py_dg_freedtoa(s0);
return NULL;
}
#ifdef __cplusplus
}
#endif
#endif /* PY_NO_SHORT_FLOAT_REPR */