cpython/Python/dtoa.c

/****************************************************************
 *
 * 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 <=
 *     Kmax.
 *
 *  7. _Py_dg_strtod has been modified so that it doesn't accept strings with
 *     leading whitespace.
 *
 *  8. A corner case where _Py_dg_dtoa didn't strip trailing zeros has been
 *     fixed. (bugs.python.org/issue40780)
 *
 ***************************************************************/

/* Please send bug reports for the original dtoa.c code to David M. Gay (dmg
 * at acm dot org, with " at " changed at "@" and " dot " changed to ".").
 * Please report bugs for this modified version using the Python issue tracker
 * as detailed at (https://devguide.python.org/triage/issue-tracker/). */

/* On a machine with IEEE extended-precision registers, it is
 * necessary to specify double-precision (53-bit) rounding precision
 * before invoking strtod or dtoa.  If the machine uses (the equivalent
 * of) Intel 80x87 arithmetic, the call
 *      _control87(PC_53, MCW_PC);
 * does this with many compilers.  Whether this or another call is
 * appropriate depends on the compiler; for this to work, it may be
 * necessary to #include "float.h" or another system-dependent header
 * file.
 */

/* strtod for IEEE-, VAX-, and IBM-arithmetic machines.
 *
 * This strtod returns a nearest machine number to the input decimal
 * string (or sets errno to ERANGE).  With IEEE arithmetic, ties are
 * broken by the IEEE round-even rule.  Otherwise ties are broken by
 * biased rounding (add half and chop).
 *
 * Inspired loosely by William D. Clinger's paper "How to Read Floating
 * Point Numbers Accurately" [Proc. ACM SIGPLAN '90, pp. 92-101].
 *
 * Modifications:
 *
 *      1. We only require IEEE, IBM, or VAX double-precision
 *              arithmetic (not IEEE double-extended).
 *      2. We get by with floating-point arithmetic in a case that
 *              Clinger missed -- when we're computing d * 10^n
 *              for a small integer d and the integer n is not too
 *              much larger than 22 (the maximum integer k for which
 *              we can represent 10^k exactly), we may be able to
 *              compute (d*10^k) * 10^(e-k) with just one roundoff.
 *      3. Rather than a bit-at-a-time adjustment of the binary
 *              result in the hard case, we use floating-point
 *              arithmetic to determine the adjustment to within
 *              one bit; only in really hard cases do we need to
 *              compute a second residual.
 *      4. Because of 3., we don't need a large table of powers of 10
 *              for ten-to-e (just some small tables, e.g. of 10^k
 *              for 0 <= k <= 22).
 */

/* Linking of Python's #defines to Gay's #defines starts here. */

#include "Python.h"
#include "pycore_dtoa.h"          // _PY_SHORT_FLOAT_REPR
#include "pycore_pystate.h"       // _PyInterpreterState_GET()
#include <stdlib.h>               // exit()

/* if _PY_SHORT_FLOAT_REPR == 0, then don't even try to compile
   the following code */
#if _PY_SHORT_FLOAT_REPR == 1

#include "float.h"

#define MALLOC
#define FREE

/* This code should also work for ARM mixed-endian format on little-endian
   machines, where doubles have byte order 45670123 (in increasing address
   order, 0 being the least significant byte). */
#ifdef DOUBLE_IS_LITTLE_ENDIAN_IEEE754
#define IEEE_8087
#endif
#if defined(DOUBLE_IS_BIG_ENDIAN_IEEE754) ||  \
  defined(DOUBLE_IS_ARM_MIXED_ENDIAN_IEEE754)
#define IEEE_MC68k
#endif
#if defined(IEEE_8087) + defined(IEEE_MC68k) != 1
#error "Exactly one of IEEE_8087 or IEEE_MC68k should be defined."
#endif

/* The code below assumes that the endianness of integers matches the
   endianness of the two 32-bit words of a double.  Check this. */
#if defined(WORDS_BIGENDIAN) && (defined(DOUBLE_IS_LITTLE_ENDIAN_IEEE754) || \
                                 defined(DOUBLE_IS_ARM_MIXED_ENDIAN_IEEE754))
#error "doubles and ints have incompatible endianness"
#endif

#if !defined(WORDS_BIGENDIAN) && defined(DOUBLE_IS_BIG_ENDIAN_IEEE754)
#error "doubles and ints have incompatible endianness"
#endif


// ULong is defined in pycore_dtoa.h.
Long;
ULLong;

#undef DEBUG
#ifdef Py_DEBUG
#define DEBUG
#endif

/* End Python #define linking */

#ifdef DEBUG
#define Bug
#endif

U;

#ifdef IEEE_8087
#define word0(x)
#define word1(x)
#else
#define word0
#define word1
#endif
#define dval(x)

#ifndef STRTOD_DIGLIM
#define STRTOD_DIGLIM
#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
#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
#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 << 16 | c & 0xffff)
 */
#if defined(IEEE_8087)
#define Storeinc(a,b,c)
#else
#define Storeinc
#endif

/* #define P DBL_MANT_DIG */
/* Ten_pmax = floor(P*log(2)/log(5)) */
/* Bletch = (highest power of 2 < DBL_MAX_10_EXP) / 16 */
/* Quick_max = floor((P-1)*log(FLT_RADIX)/log(10) - 1) */
/* Int_max = floor(P*log(FLT_RADIX)/log(10) - 1) */

#define Exp_shift
#define Exp_shift1
#define Exp_msk1
#define Exp_msk11
#define Exp_mask
#define P
#define Nbits
#define Bias
#define Emax
#define Emin
#define Etiny
#define Exp_1
#define Exp_11
#define Ebits
#define Frac_mask
#define Frac_mask1
#define Ten_pmax
#define Bletch
#define Bndry_mask
#define Bndry_mask1
#define Sign_bit
#define Log2P
#define Tiny0
#define Tiny1
#define Quick_max
#define Int_max

#ifndef Flt_Rounds
#ifdef FLT_ROUNDS
#define Flt_Rounds
#else
#define Flt_Rounds
#endif
#endif /*Flt_Rounds*/

#define Rounding

#define Big0
#define Big1

/* Bits of the representation of positive infinity. */

#define POSINF_WORD0
#define POSINF_WORD1

/* struct BCinfo is used to pass information from _Py_dg_strtod to bigcomp */

BCinfo;
struct
BCinfo {};

#define FFFFFFFF

/* struct Bigint is used to represent arbitrary-precision integers.  These
   integers are stored in sign-magnitude format, with the magnitude stored as
   an array of base 2**32 digits.  Bigints are always normalized: if x is a
   Bigint then x->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 is defined in pycore_dtoa.h.
Bigint;

#if !defined(Py_GIL_DISABLED) && !defined(Py_USING_MEMORY_DEBUGGER)

/* Memory management: memory is allocated from, and returned to, Kmax+1 pools
   of memory, where pool k (0 <= k <= Kmax) is for Bigints b with b->maxwds ==
   1 << k.  These pools are maintained as linked lists, with freelist[k]
   pointing to the head of the list for pool k.

   On allocation, if there's no free slot in the appropriate pool, MALLOC is
   called to get more memory.  This memory is not returned to the system until
   Python quits.  There's also a private memory pool that's allocated from
   in preference to using MALLOC.

   For Bigints with more than (1 << Kmax) digits (which implies at least 1233
   decimal digits), memory is directly allocated using MALLOC, and freed using
   FREE.

   XXX: it would be easy to bypass this memory-management system and
   translate each call to Balloc into a call to PyMem_Malloc, and each
   Bfree to PyMem_Free.  Investigate whether this has any significant
   performance on impact. */

#define freelist
#define private_mem
#define pmem_next

/* Allocate space for a Bigint with up to 1<<k digits */

static Bigint *
Balloc(int k)
{}

/* Free a Bigint allocated with Balloc */

static void
Bfree(Bigint *v)
{}

#undef pmem_next
#undef private_mem
#undef freelist

#else

/* Alternative versions of Balloc and Bfree that use PyMem_Malloc and
   PyMem_Free directly in place of the custom memory allocation scheme above.
   These are provided for the benefit of memory debugging tools like
   Valgrind. */

/* Allocate space for a Bigint with up to 1<<k digits */

static Bigint *
Balloc(int k)
{
    int x;
    Bigint *rv;
    unsigned int len;

    x = 1 << k;
    len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1)
        /sizeof(double);

    rv = (Bigint*)MALLOC(len*sizeof(double));
    if (rv == NULL)
        return NULL;

    rv->k = k;
    rv->maxwds = x;
    rv->sign = rv->wds = 0;
    return rv;
}

/* Free a Bigint allocated with Balloc */

static void
Bfree(Bigint *v)
{
    if (v) {
        FREE((void*)v);
    }
}

#endif /* !defined(Py_GIL_DISABLED) && !defined(Py_USING_MEMORY_DEBUGGER) */

#define Bcopy(x,y)

/* Multiply a Bigint b by m and add a.  Either modifies b in place and returns
   a pointer to the modified b, or Bfrees b and returns a pointer to a copy.
   On failure, return NULL.  In this case, b will have been already freed. */

static Bigint *
multadd(Bigint *b, int m, int a)       /* multiply by m and add a */
{}

/* convert a string s containing nd decimal digits (possibly containing a
   decimal separator at position nd0, which is ignored) to a Bigint.  This
   function carries on where the parsing code in _Py_dg_strtod leaves off: on
   entry, y9 contains the result of converting the first 9 digits.  Returns
   NULL on failure. */

static Bigint *
s2b(const char *s, int nd0, int nd, ULong y9)
{}

/* count leading 0 bits in the 32-bit integer x. */

static int
hi0bits(ULong x)
{}

/* count trailing 0 bits in the 32-bit integer y, and shift y right by that
   number of bits. */

static int
lo0bits(ULong *y)
{}

/* convert a small nonnegative integer to a Bigint */

static Bigint *
i2b(int i)
{}

/* multiply two Bigints.  Returns a new Bigint, or NULL on failure.  Ignores
   the signs of a and b. */

static Bigint *
mult(Bigint *a, Bigint *b)
{}

#ifndef Py_USING_MEMORY_DEBUGGER

/* multiply the Bigint b by 5**k.  Returns a pointer to the result, or NULL on
   failure; if the returned pointer is distinct from b then the original
   Bigint b will have been Bfree'd.   Ignores the sign of b. */

static Bigint *
pow5mult(Bigint *b, int k)
{}

#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)
{}

/* 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)
{}

/* Take the difference of Bigints a and b, returning a new Bigint.  Returns
   NULL on failure.  The signs of a and b are ignored, but the sign of the
   result is set appropriately. */

static Bigint *
diff(Bigint *a, Bigint *b)
{}

/* 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)
{}

/* Convert a Bigint to a double plus an exponent */

static double
b2d(Bigint *a, int *e)
{}

/* 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) <= b < 2**P and e >= 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)
{}

/* 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) <= b < 2**(*bbits).

   If d is zero, then b == 0, *e == -1010, *bbits = 0.
 */

static Bigint *
d2b(U *d, int *e, int *bits)
{}

/* 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)
{}

static const double
tens[] =;

static const double
bigtens[] =;
static const double tinytens[] =;
/* 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
#define n_bigtens

#define ULbits
#define kshift
#define kmask


static int
dshift(Bigint *b, int p2)
{}

/* special case of Bigint division.  The quotient is always in the range 0 <=
   quotient < 10, and on entry the divisor S is normalized so that its top 4
   bits (28--31) are zero and bit 27 is set. */

static int
quorem(Bigint *b, Bigint *S)
{}

/* 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)
{}

/* 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)
{}


double
_Py_dg_strtod(const char *s00, char **se)
{}

static char *
rv_alloc(int i)
{}

static char *
nrv_alloc(const char *s, char **rve, int n)
{}

/* freedtoa(s) must be used to free values s returned by dtoa
 * when MULTIPLE_THREADS is #defined.  It should be used in all cases,
 * but for consistency with earlier versions of dtoa, it is optional
 * when MULTIPLE_THREADS is not defined.
 */

void
_Py_dg_freedtoa(char *s)
{}

/* dtoa for IEEE arithmetic (dmg): convert double to ASCII string.
 *
 * Inspired by "How to Print Floating-Point Numbers Accurately" by
 * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 112-126].
 *
 * Modifications:
 *      1. Rather than iterating, we use a simple numeric overestimate
 *         to determine k = floor(log10(d)).  We scale relevant
 *         quantities using O(log2(k)) rather than O(k) multiplications.
 *      2. For some modes > 2 (corresponding to ecvt and fcvt), we don't
 *         try to generate digits strictly left to right.  Instead, we
 *         compute with fewer bits and propagate the carry if necessary
 *         when rounding the final digit up.  This is often faster.
 *      3. Under the assumption that input will be rounded nearest,
 *         mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22.
 *         That is, we allow equality in stopping tests when the
 *         round-nearest rule will give the same floating-point value
 *         as would satisfaction of the stopping test with strict
 *         inequality.
 *      4. We remove common factors of powers of 2 from relevant
 *         quantities.
 *      5. When converting floating-point integers less than 1e16,
 *         we use floating-point arithmetic rather than resorting
 *         to multiple-precision integers.
 *      6. When asked to produce fewer than 15 digits, we first try
 *         to get by with floating-point arithmetic; we resort to
 *         multiple-precision integer arithmetic only if we cannot
 *         guarantee that the floating-point calculation has given
 *         the correctly rounded result.  For k requested digits and
 *         "uniformly" distributed input, the probability is
 *         something like 10^(k-15) that we must resort to the Long
 *         calculation.
 */

/* Additional notes (METD): (1) returns NULL on failure.  (2) to avoid memory
   leakage, a successful call to _Py_dg_dtoa should always be matched by a
   call to _Py_dg_freedtoa. */

char *
_Py_dg_dtoa(double dd, int mode, int ndigits,
            int *decpt, int *sign, char **rve)
{}

#endif  // _PY_SHORT_FLOAT_REPR == 1

PyStatus
_PyDtoa_Init(PyInterpreterState *interp)
{}

void
_PyDtoa_Fini(PyInterpreterState *interp)
{}