1
/* Copyright (C) 2007 MySQL AB
2
This program is free software; you can redistribute it and/or modify
3
it under the terms of the GNU General Public License as published by
4
the Free Software Foundation; either version 2 of the License, or
5
(at your option) any later version.
7
This program is distributed in the hope that it will be useful,
8
but WITHOUT ANY WARRANTY; without even the implied warranty of
9
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10
GNU General Public License for more details.
12
You should have received a copy of the GNU General Public License
13
along with this program; if not, write to the Free Software
14
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
16
/****************************************************************
18
This file incorporates work covered by the following copyright and
21
The author of this software is David M. Gay.
23
Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
25
Permission to use, copy, modify, and distribute this software for any
26
purpose without fee is hereby granted, provided that this entire notice
27
is included in all copies of any software which is or includes a copy
28
or modification of this software and in all copies of the supporting
29
documentation for such software.
31
THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
32
WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
33
REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
34
OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
36
***************************************************************/
38
#include <m_string.h> /* for memcpy and NOT_FIXED_DEC */
41
Appears to suffice to not call malloc() in most cases.
43
see if it is possible to get rid of malloc().
44
this constant is sufficient to avoid malloc() on all inputs I have tried.
46
#define DTOA_BUFF_SIZE (420 * sizeof(void *))
48
/* Magic value returned by dtoa() to indicate overflow */
49
#define DTOA_OVERFLOW 9999
51
static double my_strtod_int(const char *, char **, int *, char *, size_t);
52
static char *dtoa(double, int, int, int *, int *, char **, char *, size_t);
53
static void dtoa_free(char *, char *, size_t);
57
Converts a given floating point number to a zero-terminated string
58
representation using the 'f' format.
61
This function is a wrapper around dtoa() to do the same as
62
sprintf(to, "%-.*f", precision, x), though the conversion is usually more
63
precise. The only difference is in handling [-,+]infinity and nan values,
64
in which case we print '0\0' to the output string and indicate an overflow.
66
@param x the input floating point number.
67
@param precision the number of digits after the decimal point.
68
All properties of sprintf() apply:
69
- if the number of significant digits after the decimal
70
point is less than precision, the resulting string is
71
right-padded with zeros
72
- if the precision is 0, no decimal point appears
73
- if a decimal point appears, at least one digit appears
75
@param to pointer to the output buffer. The longest string which
76
my_fcvt() can return is FLOATING_POINT_BUFFER bytes
77
(including the terminating '\0').
78
@param error if not NULL, points to a location where the status of
79
conversion is stored upon return.
80
false successful conversion
81
true the input number is [-,+]infinity or nan.
82
The output string in this case is always '0'.
83
@return number of written characters (excluding terminating '\0')
86
size_t my_fcvt(double x, int precision, char *to, bool *error)
88
int decpt, sign, len, i;
89
char *res, *src, *end, *dst= to;
90
char buf[DTOA_BUFF_SIZE];
91
assert(precision >= 0 && precision < NOT_FIXED_DEC && to != NULL);
93
res= dtoa(x, 5, precision, &decpt, &sign, &end, buf, sizeof(buf));
95
if (decpt == DTOA_OVERFLOW)
97
dtoa_free(res, buf, sizeof(buf));
115
for (i= decpt; i < 0; i++)
119
for (i= 1; i <= len; i++)
122
if (i == decpt && i < len)
133
for (i= precision - cmax(0, (len - decpt)); i > 0; i--)
141
dtoa_free(res, buf, sizeof(buf));
148
Converts a given floating point number to a zero-terminated string
149
representation with a given field width using the 'e' format
150
(aka scientific notation) or the 'f' one.
153
The format is chosen automatically to provide the most number of significant
154
digits (and thus, precision) with a given field width. In many cases, the
155
result is similar to that of sprintf(to, "%g", x) with a few notable
157
- the conversion is usually more precise than C library functions.
158
- there is no 'precision' argument. instead, we specify the number of
159
characters available for conversion (i.e. a field width).
160
- the result never exceeds the specified field width. If the field is too
161
short to contain even a rounded decimal representation, my_gcvt()
162
indicates overflow and truncates the output string to the specified width.
163
- float-type arguments are handled differently than double ones. For a
164
float input number (i.e. when the 'type' argument is MY_GCVT_ARG_FLOAT)
165
we deliberately limit the precision of conversion by FLT_DIG digits to
166
avoid garbage past the significant digits.
167
- unlike sprintf(), in cases where the 'e' format is preferred, we don't
168
zero-pad the exponent to save space for significant digits. The '+' sign
169
for a positive exponent does not appear for the same reason.
171
@param x the input floating point number.
172
@param type is either MY_GCVT_ARG_FLOAT or MY_GCVT_ARG_DOUBLE.
173
Specifies the type of the input number (see notes above).
174
@param width field width in characters. The minimal field width to
175
hold any number representation (albeit rounded) is 7
176
characters ("-Ne-NNN").
177
@param to pointer to the output buffer. The result is always
178
zero-terminated, and the longest returned string is thus
180
@param error if not NULL, points to a location where the status of
181
conversion is stored upon return.
182
false successful conversion
183
true the input number is [-,+]infinity or nan.
184
The output string in this case is always '0'.
185
@return number of written characters (excluding terminating '\0')
188
Check if it is possible and makes sense to do our own rounding on top of
189
dtoa() instead of calling dtoa() twice in (rare) cases when the resulting
190
string representation does not fit in the specified field width and we want
191
to re-round the input number with fewer significant digits. Examples:
193
my_gcvt(-9e-3, ..., 4, ...);
194
my_gcvt(-9e-3, ..., 2, ...);
195
my_gcvt(1.87e-3, ..., 4, ...);
196
my_gcvt(55, ..., 1, ...);
198
We do our best to minimize such cases by:
200
- passing to dtoa() the field width as the number of significant digits
202
- removing the sign of the number early (and decreasing the width before
203
passing it to dtoa())
205
- choosing the proper format to preserve the most number of significant
209
size_t my_gcvt(double x, my_gcvt_arg_type type, int width, char *to,
212
int decpt, sign, len, exp_len;
213
char *res, *src, *end, *dst= to, *dend= dst + width;
214
char buf[DTOA_BUFF_SIZE];
215
bool have_space, force_e_format;
216
assert(width > 0 && to != NULL);
218
/* We want to remove '-' from equations early */
222
res= dtoa(x, 4, type == MY_GCVT_ARG_DOUBLE ? width : cmin(width, FLT_DIG),
223
&decpt, &sign, &end, buf, sizeof(buf));
224
if (decpt == DTOA_OVERFLOW)
226
dtoa_free(res, buf, sizeof(buf));
241
Number of digits in the exponent from the 'e' conversion.
242
The sign of the exponent is taken into account separetely, we don't need
245
exp_len= 1 + (decpt >= 101 || decpt <= -99) + (decpt >= 11 || decpt <= -9);
248
Do we have enough space for all digits in the 'f' format?
249
Let 'len' be the number of significant digits returned by dtoa,
250
and F be the length of the resulting decimal representation.
251
Consider the following cases:
252
1. decpt <= 0, i.e. we have "0.NNN" => F = len - decpt + 2
253
2. 0 < decpt < len, i.e. we have "NNN.NNN" => F = len + 1
254
3. len <= decpt, i.e. we have "NNN00" => F = decpt
256
have_space= (decpt <= 0 ? len - decpt + 2 :
257
decpt > 0 && decpt < len ? len + 1 :
260
The following is true when no significant digits can be placed with the
261
specified field width using the 'f' format, and the 'e' format
262
will not be truncated.
264
force_e_format= (decpt <= 0 && width <= 2 - decpt && width >= 3 + exp_len);
266
Assume that we don't have enough space to place all significant digits in
267
the 'f' format. We have to choose between the 'e' format and the 'f' one
268
to keep as many significant digits as possible.
269
Let E and F be the lengths of decimal representaion in the 'e' and 'f'
270
formats, respectively. We want to use the 'f' format if, and only if F <= E.
271
Consider the following cases:
273
F = len - decpt + 2 (see above)
274
E = len + (len > 1) + 1 + 1 (decpt <= -99) + (decpt <= -9) + 1
276
(F <= E) <=> (len == 1 && decpt >= -1) || (len > 1 && decpt >= -2)
277
We also need to ensure that if the 'f' format is chosen,
278
the field width allows us to place at least one significant digit
279
(i.e. width > 2 - decpt). If not, we prefer the 'e' format.
281
F = len + 1 (see above)
282
E = len + 1 + 1 + ... ("N.NNeMMM")
283
F is always less than E.
284
3. len <= decpt <= width
285
In this case we have enough space to represent the number in the 'f'
286
format, so we prefer it with some exceptions.
288
The number cannot be represented in the 'f' format at all, always use
293
Not enough space, let's see if the 'f' format provides the most number
294
of significant digits.
296
((decpt <= width && (decpt >= -1 || (decpt == -2 &&
297
(len > 1 || !force_e_format)))) &&
301
Use the 'e' format in some cases even if we have enough space for the
302
'f' one. See comment for MAX_DECPT_FOR_F_FORMAT.
304
(!have_space || (decpt >= -MAX_DECPT_FOR_F_FORMAT + 1 &&
305
(decpt <= MAX_DECPT_FOR_F_FORMAT || len > decpt))))
310
width-= (decpt < len) + (decpt <= 0 ? 1 - decpt : 0);
312
/* Do we have to truncate any digits? */
323
We want to truncate (len - width) least significant digits after the
324
decimal point. For this we are calling dtoa with mode=5, passing the
325
number of significant digits = (len-decpt) - (len-width) = width-decpt
327
dtoa_free(res, buf, sizeof(buf));
328
res= dtoa(x, 5, width - decpt, &decpt, &sign, &end, buf, sizeof(buf));
335
/* Underflow. Just print '0' and exit */
341
At this point we are sure we have enough space to put all digits
344
if (sign && dst < dend)
350
if (len > 0 && dst < dend)
352
for (; decpt < 0 && dst < dend; decpt++)
356
for (i= 1; i <= len && dst < dend; i++)
359
if (i == decpt && i < len && dst < dend)
362
while (i++ <= decpt && dst < dend)
376
width-= 1 + exp_len; /* eNNN */
389
/* Do we have to truncate any digits? */
392
/* Yes, re-convert with a smaller width */
393
dtoa_free(res, buf, sizeof(buf));
394
res= dtoa(x, 4, width, &decpt, &sign, &end, buf, sizeof(buf));
401
At this point we are sure we have enough space to put all digits
404
if (sign && dst < dend)
408
if (len > 1 && dst < dend)
411
while (src < end && dst < dend)
416
if (decpt_sign && dst < dend)
419
if (decpt >= 100 && dst < dend)
421
*dst++= decpt / 100 + '0';
424
*dst++= decpt / 10 + '0';
426
else if (decpt >= 10 && dst < dend)
427
*dst++= decpt / 10 + '0';
429
*dst++= decpt % 10 + '0';
434
dtoa_free(res, buf, sizeof(buf));
442
Converts string to double (string does not have to be zero-terminated)
445
This is a wrapper around dtoa's version of strtod().
447
@param str input string
448
@param end address of a pointer to the first character after the input
449
string. Upon return the pointer is set to point to the first
451
@param error Upon return is set to EOVERFLOW in case of underflow or
454
@return The resulting double value. In case of underflow, 0.0 is
455
returned. In case overflow, signed DBL_MAX is returned.
458
double my_strtod(const char *str, char **end, int *error)
460
char buf[DTOA_BUFF_SIZE];
462
assert(str != NULL && end != NULL && *end != NULL && error != NULL);
464
res= my_strtod_int(str, end, error, buf, sizeof(buf));
465
return (*error == 0) ? res : (res < 0 ? -DBL_MAX : DBL_MAX);
469
double my_atof(const char *nptr)
472
const char *end= nptr+65535; /* Should be enough */
473
return (my_strtod(nptr, (char**) &end, &error));
477
/****************************************************************
479
* The author of this software is David M. Gay.
481
* Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
483
* Permission to use, copy, modify, and distribute this software for any
484
* purpose without fee is hereby granted, provided that this entire notice
485
* is included in all copies of any software which is or includes a copy
486
* or modification of this software and in all copies of the supporting
487
* documentation for such software.
489
* THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
490
* WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
491
* REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
492
* OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
494
***************************************************************/
495
/* Please send bug reports to David M. Gay (dmg at acm dot org,
496
* with " at " changed at "@" and " dot " changed to "."). */
499
Original copy of the software is located at http://www.netlib.org/fp/dtoa.c
500
It was adjusted to serve MySQL server needs:
501
* strtod() was modified to not expect a zero-terminated string.
502
It now honors 'se' (end of string) argument as the input parameter,
503
not just as the output one.
504
* in dtoa(), in case of overflow/underflow/NaN result string now contains "0";
505
decpt is set to DTOA_OVERFLOW to indicate overflow.
506
* support for VAX, IBM mainframe and 16-bit hardware removed
507
* we always assume that 64-bit integer type is available
508
* support for Kernigan-Ritchie style headers (pre-ANSI compilers)
510
* all gcc warnings ironed out
511
* we always assume multithreaded environment, so we had to change
512
memory allocation procedures to use stack in most cases;
513
malloc is used as the last resort.
514
* pow5mult rewritten to use pre-calculated pow5 list instead of
515
the one generated on the fly.
520
On a machine with IEEE extended-precision registers, it is
521
necessary to specify double-precision (53-bit) rounding precision
522
before invoking strtod or dtoa. If the machine uses (the equivalent
523
of) Intel 80x87 arithmetic, the call
524
_control87(PC_53, MCW_PC);
525
does this with many compilers. Whether this or another call is
526
appropriate depends on the compiler; for this to work, it may be
527
necessary to #include "float.h" or another system-dependent header
531
typedef int32_t Long;
532
typedef uint32_t ULong;
533
typedef int64_t LLong;
534
typedef uint64_t ULLong;
536
typedef union { double d; ULong L[2]; } U;
538
#if defined(WORDS_BIGENDIAN) || (defined(__FLOAT_WORD_ORDER) && \
539
(__FLOAT_WORD_ORDER == __BIG_ENDIAN))
540
#define word0(x) ((U*)&x)->L[0]
541
#define word1(x) ((U*)&x)->L[1]
543
#define word0(x) ((U*)&x)->L[1]
544
#define word1(x) ((U*)&x)->L[0]
547
#define dval(x) ((U*)&x)->d
549
/* #define P DBL_MANT_DIG */
550
/* Ten_pmax= floor(P*log(2)/log(5)) */
551
/* Bletch= (highest power of 2 < DBL_MAX_10_EXP) / 16 */
552
/* Quick_max= floor((P-1)*log(FLT_RADIX)/log(10) - 1) */
553
/* Int_max= floor(P*log(FLT_RADIX)/log(10) - 1) */
556
#define Exp_shift1 20
557
#define Exp_msk1 0x100000
558
#define Exp_mask 0x7ff00000
562
#define Exp_1 0x3ff00000
563
#define Exp_11 0x3ff00000
565
#define Frac_mask 0xfffff
566
#define Frac_mask1 0xfffff
569
#define Bndry_mask 0xfffff
570
#define Bndry_mask1 0xfffff
572
#define Sign_bit 0x80000000
580
#define Flt_Rounds FLT_ROUNDS
584
#endif /*Flt_Rounds*/
586
#define rounded_product(a,b) a*= b
587
#define rounded_quotient(a,b) a/= b
589
#define Big0 (Frac_mask1 | Exp_msk1*(DBL_MAX_EXP+Bias-1))
590
#define Big1 0xffffffff
591
#define FFFFFFFF 0xffffffffUL
593
/* This is tested to be enough for dtoa */
597
#define Bcopy(x,y) memcpy(&x->sign, &y->sign, \
598
2*sizeof(int) + y->wds*sizeof(ULong))
600
/* Arbitrary-length integer */
602
typedef struct Bigint
605
ULong *x; /* points right after this Bigint object */
606
struct Bigint *next; /* to maintain free lists */
608
int k; /* 2^k = maxwds */
609
int maxwds; /* maximum length in 32-bit words */
610
int sign; /* not zero if number is negative */
611
int wds; /* current length in 32-bit words */
615
/* A simple stack-memory based allocator for Bigints */
617
typedef struct Stack_alloc
623
Having list of free blocks lets us reduce maximum required amount
624
of memory from ~4000 bytes to < 1680 (tested on x86).
626
Bigint *freelist[Kmax+1];
631
Try to allocate object on stack, and resort to malloc if all
632
stack memory is used.
635
static Bigint *Balloc(int k, Stack_alloc *alloc)
638
if (k <= Kmax && alloc->freelist[k])
640
rv= alloc->freelist[k];
641
alloc->freelist[k]= rv->p.next;
648
len= sizeof(Bigint) + x * sizeof(ULong);
650
if (alloc->free + len <= alloc->end)
652
rv= (Bigint*) alloc->free;
656
rv= (Bigint*) malloc(len);
661
rv->sign= rv->wds= 0;
662
rv->p.x= (ULong*) (rv + 1);
668
If object was allocated on stack, try putting it to the free
669
list. Otherwise call free().
672
static void Bfree(Bigint *v, Stack_alloc *alloc)
674
char *gptr= (char*) v; /* generic pointer */
675
if (gptr < alloc->begin || gptr >= alloc->end)
677
else if (v->k <= Kmax)
680
Maintain free lists only for stack objects: this way we don't
681
have to bother with freeing lists in the end of dtoa;
682
heap should not be used normally anyway.
684
v->p.next= alloc->freelist[v->k];
685
alloc->freelist[v->k]= v;
691
This is to place return value of dtoa in: tries to use stack
692
as well, but passes by free lists management and just aligns len by
696
static char *dtoa_alloc(int i, Stack_alloc *alloc)
699
int aligned_size= (i + sizeof(ULong) - 1) / sizeof(ULong) * sizeof(ULong);
700
if (alloc->free + aligned_size <= alloc->end)
703
alloc->free+= aligned_size;
712
dtoa_free() must be used to free values s returned by dtoa()
713
This is the counterpart of dtoa_alloc()
716
static void dtoa_free(char *gptr, char *buf, size_t buf_size)
718
if (gptr < buf || gptr >= buf + buf_size)
723
/* Bigint arithmetic functions */
725
/* Multiply by m and add a */
727
static Bigint *multadd(Bigint *b, int m, int a, Stack_alloc *alloc)
740
y= *x * (ULLong)m + carry;
742
*x++= (ULong)(y & FFFFFFFF);
747
if (wds >= b->maxwds)
749
b1= Balloc(b->k+1, alloc);
754
b->p.x[wds++]= (ULong) carry;
761
static Bigint *s2b(const char *s, int nd0, int nd, ULong y9, Stack_alloc *alloc)
768
for (k= 0, y= 1; x > y; y <<= 1, k++) ;
778
b= multadd(b, 10, *s++ - '0', alloc);
785
b= multadd(b, 10, *s++ - '0', alloc);
790
static int hi0bits(register ULong x)
794
if (!(x & 0xffff0000))
799
if (!(x & 0xff000000))
804
if (!(x & 0xf0000000))
809
if (!(x & 0xc0000000))
814
if (!(x & 0x80000000))
817
if (!(x & 0x40000000))
824
static int lo0bits(ULong *y)
827
register ULong x= *y;
874
/* Convert integer to Bigint number */
876
static Bigint *i2b(int i, Stack_alloc *alloc)
887
/* Multiply two Bigint numbers */
889
static Bigint *mult(Bigint *a, Bigint *b, Stack_alloc *alloc)
893
ULong *x, *xa, *xae, *xb, *xbe, *xc, *xc0;
910
for (x= c->p.x, xa= x + wc; x < xa; x++)
917
for (; xb < xbe; xc0++)
926
z= *x++ * (ULLong)y + *xc + carry;
928
*xc++= (ULong) (z & FFFFFFFF);
934
for (xc0= c->p.x, xc= xc0 + wc; wc > 0 && !*--xc; --wc) ;
941
Precalculated array of powers of 5: tested to be enough for
942
vasting majority of dtoa_r cases.
945
static ULong powers5[]=
953
2242703233UL, 762134875UL, 1262UL,
955
3211403009UL, 1849224548UL, 3668416493UL, 3913284084UL, 1593091UL,
957
781532673UL, 64985353UL, 253049085UL, 594863151UL, 3553621484UL,
958
3288652808UL, 3167596762UL, 2788392729UL, 3911132675UL, 590UL,
960
2553183233UL, 3201533787UL, 3638140786UL, 303378311UL, 1809731782UL,
961
3477761648UL, 3583367183UL, 649228654UL, 2915460784UL, 487929380UL,
962
1011012442UL, 1677677582UL, 3428152256UL, 1710878487UL, 1438394610UL,
963
2161952759UL, 4100910556UL, 1608314830UL, 349175UL
967
static Bigint p5_a[]=
969
/* { x } - k - maxwds - sign - wds */
970
{ { powers5 }, 1, 1, 0, 1 },
971
{ { powers5 + 1 }, 1, 1, 0, 1 },
972
{ { powers5 + 2 }, 1, 2, 0, 2 },
973
{ { powers5 + 4 }, 2, 3, 0, 3 },
974
{ { powers5 + 7 }, 3, 5, 0, 5 },
975
{ { powers5 + 12 }, 4, 10, 0, 10 },
976
{ { powers5 + 22 }, 5, 19, 0, 19 }
979
#define P5A_MAX (sizeof(p5_a)/sizeof(*p5_a) - 1)
981
static Bigint *pow5mult(Bigint *b, int k, Stack_alloc *alloc)
983
Bigint *b1, *p5, *p51;
985
static int p05[3]= { 5, 25, 125 };
988
b= multadd(b, p05[i-1], 0, alloc);
997
b1= mult(b, p5, alloc);
1003
/* Calculate next power of 5 */
1004
if (p5 < p5_a + P5A_MAX)
1006
else if (p5 == p5_a + P5A_MAX)
1007
p5= mult(p5, p5, alloc);
1010
p51= mult(p5, p5, alloc);
1019
static Bigint *lshift(Bigint *b, int k, Stack_alloc *alloc)
1023
ULong *x, *x1, *xe, z;
1028
for (i= b->maxwds; n1 > i; i<<= 1)
1030
b1= Balloc(k1, alloc);
1032
for (i= 0; i < n; i++)
1059
static int cmp(Bigint *a, Bigint *b)
1061
ULong *xa, *xa0, *xb, *xb0;
1075
return *xa < *xb ? -1 : 1;
1083
static Bigint *diff(Bigint *a, Bigint *b, Stack_alloc *alloc)
1087
ULong *xa, *xae, *xb, *xbe, *xc;
1093
c= Balloc(0, alloc);
1107
c= Balloc(a->k, alloc);
1119
y= (ULLong)*xa++ - *xb++ - borrow;
1120
borrow= y >> 32 & (ULong)1;
1121
*xc++= (ULong) (y & FFFFFFFF);
1127
borrow= y >> 32 & (ULong)1;
1128
*xc++= (ULong) (y & FFFFFFFF);
1137
static double ulp(double x)
1142
L= (word0(x) & Exp_mask) - (P - 1)*Exp_msk1;
1149
static double b2d(Bigint *a, int *e)
1151
ULong *xa, *xa0, w, y, z;
1164
d0= Exp_1 | y >> (Ebits - k);
1165
w= xa > xa0 ? *--xa : 0;
1166
d1= y << ((32-Ebits) + k) | w >> (Ebits - k);
1169
z= xa > xa0 ? *--xa : 0;
1172
d0= Exp_1 | y << k | z >> (32 - k);
1173
y= xa > xa0 ? *--xa : 0;
1174
d1= z << k | y >> (32 - k);
1188
static Bigint *d2b(double d, int *e, int *bits, Stack_alloc *alloc)
1197
b= Balloc(1, alloc);
1201
d0 &= 0x7fffffff; /* clear sign bit, which we ignore */
1202
if ((de= (int)(d0 >> Exp_shift)))
1206
if ((k= lo0bits(&y)))
1208
x[0]= y | z << (32 - k);
1213
i= b->wds= (x[1]= z) ? 2 : 1;
1224
*e= de - Bias - (P-1) + k;
1229
*e= de - Bias - (P-1) + 1 + k;
1230
*bits= 32*i - hi0bits(x[i-1]);
1238
static double ratio(Bigint *a, Bigint *b)
1243
dval(da)= b2d(a, &ka);
1244
dval(db)= b2d(b, &kb);
1245
k= ka - kb + 32*(a->wds - b->wds);
1247
word0(da)+= k*Exp_msk1;
1251
word0(db)+= k*Exp_msk1;
1253
return dval(da) / dval(db);
1256
static const double tens[] =
1258
1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
1259
1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
1263
static const double bigtens[]= { 1e16, 1e32, 1e64, 1e128, 1e256 };
1264
static const double tinytens[]=
1265
{ 1e-16, 1e-32, 1e-64, 1e-128,
1266
9007199254740992.*9007199254740992.e-256 /* = 2^106 * 1e-53 */
1269
The factor of 2^53 in tinytens[4] helps us avoid setting the underflow
1270
flag unnecessarily. It leads to a song and dance at the end of strtod.
1272
#define Scale_Bit 0x10
1276
strtod for IEEE--arithmetic machines.
1278
This strtod returns a nearest machine number to the input decimal
1279
string (or sets errno to EOVERFLOW). Ties are broken by the IEEE round-even
1282
Inspired loosely by William D. Clinger's paper "How to Read Floating
1283
Point Numbers Accurately" [Proc. ACM SIGPLAN '90, pp. 92-101].
1287
1. We only require IEEE (not IEEE double-extended).
1288
2. We get by with floating-point arithmetic in a case that
1289
Clinger missed -- when we're computing d * 10^n
1290
for a small integer d and the integer n is not too
1291
much larger than 22 (the maximum integer k for which
1292
we can represent 10^k exactly), we may be able to
1293
compute (d*10^k) * 10^(e-k) with just one roundoff.
1294
3. Rather than a bit-at-a-time adjustment of the binary
1295
result in the hard case, we use floating-point
1296
arithmetic to determine the adjustment to within
1297
one bit; only in really hard cases do we need to
1298
compute a second residual.
1299
4. Because of 3., we don't need a large table of powers of 10
1300
for ten-to-e (just some small tables, e.g. of 10^k
1304
static double my_strtod_int(const char *s00, char **se, int *error, char *buf, size_t buf_size)
1307
int bb2, bb5, bbe, bd2, bd5, bbbits, bs2, c, dsign,
1308
e, e1, esign, i, j, k, nd, nd0, nf, nz, nz0, sign;
1309
const char *s, *s0, *s1, *end = *se;
1310
double aadj, aadj1, adj, rv, rv0;
1313
Bigint *bb= NULL, *bb1= NULL, *bd= NULL, *bd0= NULL, *bs= NULL, *delta= NULL;
1315
int inexact, oldinexact;
1322
alloc.begin= alloc.free= buf;
1323
alloc.end= buf + buf_size;
1324
memset(alloc.freelist, 0, sizeof(alloc.freelist));
1328
for (s= s00; s < end; s++)
1353
while (++s < end && *s == '0') ;
1359
for (nd= nf= 0; s < end && (c= *s) >= '0' && c <= '9'; nd++, s++)
1365
if (s < end - 1 && c == '.')
1370
for (; s < end && c == '0'; c= *++s)
1372
if (s < end && c > '0' && c <= '9')
1381
for (; s < end && c >= '0' && c <= '9'; c = *++s)
1388
for (i= 1; i < nz; i++)
1391
else if (nd <= DBL_DIG + 1)
1395
else if (nd <= DBL_DIG + 1)
1403
if (s < end && (c == 'e' || c == 'E'))
1405
if (!nd && !nz && !nz0)
1416
if (s < end && c >= '0' && c <= '9')
1418
while (s < end && c == '0')
1420
if (s < end && c > '0' && c <= '9') {
1423
while (++s < end && (c= *s) >= '0' && c <= '9')
1425
if (s - s1 > 8 || L > 19999)
1426
/* Avoid confusion from exponents
1427
* so large that e might overflow.
1429
e= 19999; /* safe for 16 bit ints */
1454
Now we have nd0 digits, starting at s0, followed by a
1455
decimal point, followed by nd-nd0 digits. The number we're
1456
after is the integer represented by those digits times
1462
k= nd < DBL_DIG + 1 ? nd : DBL_DIG + 1;
1468
oldinexact = get_inexact();
1470
dval(rv)= tens[k - 9] * dval(rv) + z;
1482
/* rv = */ rounded_product(dval(rv), tens[e]);
1486
if (e <= Ten_pmax + i)
1489
A fancier test would sometimes let us do
1490
this for larger i values.
1494
/* rv = */ rounded_product(dval(rv), tens[e]);
1498
#ifndef Inaccurate_Divide
1499
else if (e >= -Ten_pmax)
1501
/* rv = */ rounded_quotient(dval(rv), tens[-e]);
1511
oldinexact= get_inexact();
1515
/* Get starting approximation = rv * 10**e1 */
1523
if (e1 > DBL_MAX_10_EXP)
1527
/* Can't trust HUGE_VAL */
1528
word0(rv)= Exp_mask;
1531
/* set overflow bit */
1533
dval(rv0)*= dval(rv0);
1540
for(j= 0; e1 > 1; j++, e1>>= 1)
1542
dval(rv)*= bigtens[j];
1543
/* The last multiplication could overflow. */
1544
word0(rv)-= P*Exp_msk1;
1545
dval(rv)*= bigtens[j];
1546
if ((z= word0(rv) & Exp_mask) > Exp_msk1 * (DBL_MAX_EXP + Bias - P))
1548
if (z > Exp_msk1 * (DBL_MAX_EXP + Bias - 1 - P))
1550
/* set to largest number (Can't trust DBL_MAX) */
1555
word0(rv)+= P*Exp_msk1;
1565
if (e1 >= 1 << n_bigtens)
1569
for(j= 0; e1 > 0; j++, e1>>= 1)
1571
dval(rv)*= tinytens[j];
1572
if (scale && (j = 2 * P + 1 - ((word0(rv) & Exp_mask) >> Exp_shift)) > 0)
1574
/* scaled rv is denormal; zap j low bits */
1579
word0(rv)= (P + 2) * Exp_msk1;
1581
word0(rv)&= 0xffffffff << (j - 32);
1584
word1(rv)&= 0xffffffff << j;
1597
/* Now the hard part -- adjusting rv to the correct value.*/
1599
/* Put digits into bd: true value = bd * 10^e */
1601
bd0= s2b(s0, nd0, nd, y, &alloc);
1605
bd= Balloc(bd0->k, &alloc);
1607
bb= d2b(dval(rv), &bbe, &bbbits, &alloc); /* rv = bb * 2^bbe */
1626
i= j + bbbits - 1; /* logb(rv) */
1627
if (i < Emin) /* denormal */
1634
i= bb2 < bd2 ? bb2 : bd2;
1645
bs= pow5mult(bs, bb5, &alloc);
1646
bb1= mult(bs, bb, &alloc);
1651
bb= lshift(bb, bb2, &alloc);
1653
bd= pow5mult(bd, bd5, &alloc);
1655
bd= lshift(bd, bd2, &alloc);
1657
bs= lshift(bs, bs2, &alloc);
1658
delta= diff(bb, bd, &alloc);
1666
Error is less than half an ulp -- check for special case of mantissa
1669
if (dsign || word1(rv) || word0(rv) & Bndry_mask ||
1670
(word0(rv) & Exp_mask) <= (2 * P + 1) * Exp_msk1)
1673
if (!delta->x[0] && delta->wds <= 1)
1678
if (!delta->p.x[0] && delta->wds <= 1)
1686
delta= lshift(delta, Log2P, &alloc);
1687
if (cmp(delta, bs) > 0)
1693
/* exactly half-way between */
1696
if ((word0(rv) & Bndry_mask1) == Bndry_mask1 &&
1698
((scale && (y = word0(rv) & Exp_mask) <= 2 * P * Exp_msk1) ?
1699
(0xffffffff & (0xffffffff << (2*P+1-(y>>Exp_shift)))) :
1702
/*boundary case -- increment exponent*/
1703
word0(rv)= (word0(rv) & Exp_mask) + Exp_msk1;
1709
else if (!(word0(rv) & Bndry_mask) && !word1(rv))
1712
/* boundary case -- decrement exponent */
1715
L= word0(rv) & Exp_mask;
1716
if (L <= (2 *P + 1) * Exp_msk1)
1718
if (L > (P + 2) * Exp_msk1)
1719
/* round even ==> accept rv */
1721
/* rv = smallest denormal */
1725
L= (word0(rv) & Exp_mask) - Exp_msk1;
1726
word0(rv)= L | Bndry_mask1;
1727
word1(rv)= 0xffffffff;
1730
if (!(word1(rv) & LSB))
1733
dval(rv)+= ulp(dval(rv));
1736
dval(rv)-= ulp(dval(rv));
1743
if ((aadj= ratio(delta, bs)) <= 2.)
1747
else if (word1(rv) || word0(rv) & Bndry_mask)
1749
if (word1(rv) == Tiny1 && !word0(rv))
1756
/* special case -- power of FLT_RADIX to be rounded down... */
1757
if (aadj < 2. / FLT_RADIX)
1758
aadj= 1. / FLT_RADIX;
1767
aadj1= dsign ? aadj : -aadj;
1768
if (Flt_Rounds == 0)
1771
y= word0(rv) & Exp_mask;
1773
/* Check for overflow */
1775
if (y == Exp_msk1 * (DBL_MAX_EXP + Bias - 1))
1777
dval(rv0)= dval(rv);
1778
word0(rv)-= P * Exp_msk1;
1779
adj= aadj1 * ulp(dval(rv));
1781
if ((word0(rv) & Exp_mask) >= Exp_msk1 * (DBL_MAX_EXP + Bias - P))
1783
if (word0(rv0) == Big0 && word1(rv0) == Big1)
1790
word0(rv)+= P * Exp_msk1;
1794
if (scale && y <= 2 * P * Exp_msk1)
1796
if (aadj <= 0x7fffffff)
1798
if ((z= (ULong) aadj) <= 0)
1801
aadj1= dsign ? aadj : -aadj;
1803
word0(aadj1)+= (2 * P + 1) * Exp_msk1 - y;
1805
adj = aadj1 * ulp(dval(rv));
1808
z= word0(rv) & Exp_mask;
1813
/* Can we stop now? */
1816
/* The tolerances below are conservative. */
1817
if (dsign || word1(rv) || word0(rv) & Bndry_mask)
1819
if (aadj < .4999999 || aadj > .5000001)
1822
else if (aadj < .4999999 / FLT_RADIX)
1830
Bfree(delta, &alloc);
1837
word0(rv0)= Exp_1 + (70 << Exp_shift);
1842
else if (!oldinexact)
1847
word0(rv0)= Exp_1 - 2 * P * Exp_msk1;
1849
dval(rv)*= dval(rv0);
1852
if (inexact && !(word0(rv) & Exp_mask))
1854
/* set underflow bit */
1856
dval(rv0)*= dval(rv0);
1864
Bfree(delta, &alloc);
1867
return sign ? -dval(rv) : dval(rv);
1871
static int quorem(Bigint *b, Bigint *S)
1874
ULong *bx, *bxe, q, *sx, *sxe;
1875
ULLong borrow, carry, y, ys;
1884
q= *bxe / (*sxe + 1); /* ensure q <= true quotient */
1891
ys= *sx++ * (ULLong)q + carry;
1893
y= *bx - (ys & FFFFFFFF) - borrow;
1894
borrow= y >> 32 & (ULong)1;
1895
*bx++= (ULong) (y & FFFFFFFF);
1901
while (--bxe > bx && !*bxe)
1917
y= *bx - (ys & FFFFFFFF) - borrow;
1918
borrow= y >> 32 & (ULong)1;
1919
*bx++= (ULong) (y & FFFFFFFF);
1926
while (--bxe > bx && !*bxe)
1936
dtoa for IEEE arithmetic (dmg): convert double to ASCII string.
1938
Inspired by "How to Print Floating-Point Numbers Accurately" by
1939
Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 112-126].
1942
1. Rather than iterating, we use a simple numeric overestimate
1943
to determine k= floor(log10(d)). We scale relevant
1944
quantities using O(log2(k)) rather than O(k) multiplications.
1945
2. For some modes > 2 (corresponding to ecvt and fcvt), we don't
1946
try to generate digits strictly left to right. Instead, we
1947
compute with fewer bits and propagate the carry if necessary
1948
when rounding the final digit up. This is often faster.
1949
3. Under the assumption that input will be rounded nearest,
1950
mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22.
1951
That is, we allow equality in stopping tests when the
1952
round-nearest rule will give the same floating-point value
1953
as would satisfaction of the stopping test with strict
1955
4. We remove common factors of powers of 2 from relevant
1957
5. When converting floating-point integers less than 1e16,
1958
we use floating-point arithmetic rather than resorting
1959
to multiple-precision integers.
1960
6. When asked to produce fewer than 15 digits, we first try
1961
to get by with floating-point arithmetic; we resort to
1962
multiple-precision integer arithmetic only if we cannot
1963
guarantee that the floating-point calculation has given
1964
the correctly rounded result. For k requested digits and
1965
"uniformly" distributed input, the probability is
1966
something like 10^(k-15) that we must resort to the Long
1970
static char *dtoa(double d, int mode, int ndigits, int *decpt, int *sign,
1971
char **rve, char *buf, size_t buf_size)
1974
Arguments ndigits, decpt, sign are similar to those
1975
of ecvt and fcvt; trailing zeros are suppressed from
1976
the returned string. If not null, *rve is set to point
1977
to the end of the return value. If d is +-Infinity or NaN,
1978
then *decpt is set to DTOA_OVERFLOW.
1981
0 ==> shortest string that yields d when read in
1982
and rounded to nearest.
1983
1 ==> like 0, but with Steele & White stopping rule;
1984
e.g. with IEEE P754 arithmetic , mode 0 gives
1985
1e23 whereas mode 1 gives 9.999999999999999e22.
1986
2 ==> cmax(1,ndigits) significant digits. This gives a
1987
return value similar to that of ecvt, except
1988
that trailing zeros are suppressed.
1989
3 ==> through ndigits past the decimal point. This
1990
gives a return value similar to that from fcvt,
1991
except that trailing zeros are suppressed, and
1992
ndigits can be negative.
1993
4,5 ==> similar to 2 and 3, respectively, but (in
1994
round-nearest mode) with the tests of mode 0 to
1995
possibly return a shorter string that rounds to d.
1996
6-9 ==> Debugging modes similar to mode - 4: don't try
1997
fast floating-point estimate (if applicable).
1999
Values of mode other than 0-9 are treated as mode 0.
2001
Sufficient space is allocated to the return value
2002
to hold the suppressed trailing zeros.
2005
int bbits, b2, b5, be, dig, i, ieps, ilim=0, ilim0, ilim1= 0,
2006
j, j1, k, k0, k_check, leftright, m2, m5, s2, s5,
2007
spec_case, try_quick;
2011
Bigint *b, *b1, *delta, *mlo = NULL, *mhi, *S;
2016
alloc.begin= alloc.free= buf;
2017
alloc.end= buf + buf_size;
2018
memset(alloc.freelist, 0, sizeof(alloc.freelist));
2020
if (word0(d) & Sign_bit)
2022
/* set sign for everything, including 0's and NaNs */
2024
word0(d) &= ~Sign_bit; /* clear sign bit */
2029
/* If infinity, set decpt to DTOA_OVERFLOW, if 0 set it to 1 */
2030
if (((word0(d) & Exp_mask) == Exp_mask && (*decpt= DTOA_OVERFLOW)) ||
2031
(!dval(d) && (*decpt= 1)))
2033
/* Infinity, NaN, 0 */
2034
char *res= (char*) dtoa_alloc(2, &alloc);
2043
b= d2b(dval(d), &be, &bbits, &alloc);
2044
if ((i= (int)(word0(d) >> Exp_shift1 & (Exp_mask>>Exp_shift1))))
2047
word0(d2) &= Frac_mask1;
2048
word0(d2) |= Exp_11;
2051
log(x) ~=~ log(1.5) + (x-1.5)/1.5
2052
log10(x) = log(x) / log(10)
2053
~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10))
2054
log10(d)= (i-Bias)*log(2)/log(10) + log10(d2)
2056
This suggests computing an approximation k to log10(d) by
2058
k= (i - Bias)*0.301029995663981
2059
+ ( (d2-1.5)*0.289529654602168 + 0.176091259055681 );
2061
We want k to be too large rather than too small.
2062
The error in the first-order Taylor series approximation
2063
is in our favor, so we just round up the constant enough
2064
to compensate for any error in the multiplication of
2065
(i - Bias) by 0.301029995663981; since |i - Bias| <= 1077,
2066
and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14,
2067
adding 1e-13 to the constant term more than suffices.
2068
Hence we adjust the constant term to 0.1760912590558.
2069
(We could get a more accurate k by invoking log10,
2070
but this is probably not worthwhile.)
2078
/* d is denormalized */
2080
i= bbits + be + (Bias + (P-1) - 1);
2081
x= i > 32 ? word0(d) << (64 - i) | word1(d) >> (i - 32)
2082
: word1(d) << (32 - i);
2084
word0(d2)-= 31*Exp_msk1; /* adjust exponent */
2085
i-= (Bias + (P-1) - 1) + 1;
2088
ds= (dval(d2)-1.5)*0.289529654602168 + 0.1760912590558 + i*0.301029995663981;
2090
if (ds < 0. && ds != k)
2091
k--; /* want k= floor(ds) */
2093
if (k >= 0 && k <= Ten_pmax)
2095
if (dval(d) < tens[k])
2122
if (mode < 0 || mode > 9)
2146
ilim= ilim1= i= ndigits;
2158
s= s0= dtoa_alloc(i, &alloc);
2160
if (ilim >= 0 && ilim <= Quick_max && try_quick)
2162
/* Try to get by with floating-point arithmetic. */
2167
ieps= 2; /* conservative */
2174
/* prevent overflows */
2176
dval(d)/= bigtens[n_bigtens-1];
2179
for (; j; j>>= 1, i++)
2191
dval(d)*= tens[j1 & 0xf];
2192
for (j= j1 >> 4; j; j>>= 1, i++)
2197
dval(d)*= bigtens[i];
2201
if (k_check && dval(d) < 1. && ilim > 0)
2210
dval(eps)= ieps*dval(d) + 7.;
2211
word0(eps)-= (P-1)*Exp_msk1;
2216
if (dval(d) > dval(eps))
2218
if (dval(d) < -dval(eps))
2224
/* Use Steele & White method of only generating digits needed. */
2225
dval(eps)= 0.5/tens[ilim-1] - dval(eps);
2231
if (dval(d) < dval(eps))
2233
if (1. - dval(d) < dval(eps))
2243
/* Generate ilim digits, then fix them up. */
2244
dval(eps)*= tens[ilim-1];
2245
for (i= 1;; i++, dval(d)*= 10.)
2253
if (dval(d) > 0.5 + dval(eps))
2255
else if (dval(d) < 0.5 - dval(eps))
2257
while (*--s == '0');
2272
/* Do we have a "small" integer? */
2274
if (be >= 0 && k <= Int_max)
2278
if (ndigits < 0 && ilim <= 0)
2281
if (ilim < 0 || dval(d) <= 5*ds)
2285
for (i= 1;; i++, dval(d)*= 10.)
2287
L= (Long)(dval(d) / ds);
2297
if (dval(d) > ds || (dval(d) == ds && L & 1))
2320
i = denorm ? be + (Bias + (P-1) - 1 + 1) : 1 + P - bbits;
2323
mhi= i2b(1, &alloc);
2325
if (m2 > 0 && s2 > 0)
2327
i= m2 < s2 ? m2 : s2;
2338
mhi= pow5mult(mhi, m5, &alloc);
2339
b1= mult(mhi, b, &alloc);
2344
b= pow5mult(b, j, &alloc);
2347
b= pow5mult(b, b5, &alloc);
2351
S= pow5mult(S, s5, &alloc);
2353
/* Check for special case that d is a normalized power of 2. */
2356
if ((mode < 2 || leftright)
2359
if (!word1(d) && !(word0(d) & Bndry_mask) &&
2360
word0(d) & (Exp_mask & ~Exp_msk1)
2363
/* The special case */
2371
Arrange for convenient computation of quotients:
2372
shift left if necessary so divisor has 4 leading 0 bits.
2374
Perhaps we should just compute leading 28 bits of S once
2375
a nd for all and pass them and a shift to quorem, so it
2376
can do shifts and ors to compute the numerator for q.
2378
if ((i= ((s5 ? 32 - hi0bits(S->p.x[S->wds-1]) : 1) + s2) & 0x1f))
2395
b= lshift(b, b2, &alloc);
2397
S= lshift(S, s2, &alloc);
2403
/* we botched the k estimate */
2404
b= multadd(b, 10, 0, &alloc);
2406
mhi= multadd(mhi, 10, 0, &alloc);
2410
if (ilim <= 0 && (mode == 3 || mode == 5))
2412
if (ilim < 0 || cmp(b,S= multadd(S,5,0, &alloc)) <= 0)
2414
/* no digits, fcvt style */
2427
mhi= lshift(mhi, m2, &alloc);
2430
Compute mlo -- check for special case that d is a normalized power of 2.
2436
mhi= Balloc(mhi->k, &alloc);
2438
mhi= lshift(mhi, Log2P, &alloc);
2443
dig= quorem(b,S) + '0';
2444
/* Do we yet have the shortest decimal string that will round to d? */
2446
delta= diff(S, mhi, &alloc);
2447
j1= delta->sign ? 1 : cmp(b, delta);
2448
Bfree(delta, &alloc);
2449
if (j1 == 0 && mode != 1 && !(word1(d) & 1)
2459
if (j < 0 || (j == 0 && mode != 1 && !(word1(d) & 1)))
2461
if (!b->p.x[0] && b->wds <= 1)
2467
b= lshift(b, 1, &alloc);
2469
if ((j1 > 0 || (j1 == 0 && dig & 1))
2480
{ /* possible if i == 1 */
2491
b= multadd(b, 10, 0, &alloc);
2493
mlo= mhi= multadd(mhi, 10, 0, &alloc);
2496
mlo= multadd(mlo, 10, 0, &alloc);
2497
mhi= multadd(mhi, 10, 0, &alloc);
2504
*s++= dig= quorem(b,S) + '0';
2505
if (!b->p.x[0] && b->wds <= 1)
2511
b= multadd(b, 10, 0, &alloc);
2514
/* Round off last digit */
2516
b= lshift(b, 1, &alloc);
2518
if (j > 0 || (j == 0 && dig & 1))
2532
while (*--s == '0');
2539
if (mlo && mlo != mhi)