1
/* Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
3
This library is free software; you can redistribute it and/or
4
modify it under the terms of the GNU Library General Public
5
License as published by the Free Software Foundation; version 2
8
This program is distributed in the hope that it will be useful,
9
but WITHOUT ANY WARRANTY; without even the implied warranty of
10
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
GNU General Public License for more details.
13
You should have received a copy of the GNU General Public License
14
along with this program; if not, write to the Free Software
15
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
17
/****************************************************************
19
This file incorporates work covered by the following copyright and
22
The author of this software is David M. Gay.
24
Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
26
Permission to use, copy, modify, and distribute this software for any
27
purpose without fee is hereby granted, provided that this entire notice
28
is included in all copies of any software which is or includes a copy
29
or modification of this software and in all copies of the supporting
30
documentation for such software.
32
THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
33
WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
34
REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
35
OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
37
***************************************************************/
39
#include <my_base.h> /* for EOVERFLOW on Windows */
40
#include <my_global.h>
41
#include <m_string.h> /* for memcpy and NOT_FIXED_DEC */
44
Appears to suffice to not call malloc() in most cases.
46
see if it is possible to get rid of malloc().
47
this constant is sufficient to avoid malloc() on all inputs I have tried.
49
#define DTOA_BUFF_SIZE (460 * sizeof(void *))
51
/* Magic value returned by dtoa() to indicate overflow */
52
#define DTOA_OVERFLOW 9999
54
static double my_strtod_int(const char *, char **, int *, char *, size_t);
55
static char *dtoa(double, int, int, int *, int *, char **, char *, size_t);
56
static void dtoa_free(char *, char *, size_t);
60
Converts a given floating point number to a zero-terminated string
61
representation using the 'f' format.
64
This function is a wrapper around dtoa() to do the same as
65
sprintf(to, "%-.*f", precision, x), though the conversion is usually more
66
precise. The only difference is in handling [-,+]infinity and nan values,
67
in which case we print '0\0' to the output string and indicate an overflow.
69
@param x the input floating point number.
70
@param precision the number of digits after the decimal point.
71
All properties of sprintf() apply:
72
- if the number of significant digits after the decimal
73
point is less than precision, the resulting string is
74
right-padded with zeros
75
- if the precision is 0, no decimal point appears
76
- if a decimal point appears, at least one digit appears
78
@param to pointer to the output buffer. The longest string which
79
my_fcvt() can return is FLOATING_POINT_BUFFER bytes
80
(including the terminating '\0').
81
@param error if not NULL, points to a location where the status of
82
conversion is stored upon return.
83
FALSE successful conversion
84
TRUE the input number is [-,+]infinity or nan.
85
The output string in this case is always '0'.
86
@return number of written characters (excluding terminating '\0')
89
size_t my_fcvt(double x, int precision, char *to, my_bool *error)
91
int decpt, sign, len, i;
92
char *res, *src, *end, *dst= to;
93
char buf[DTOA_BUFF_SIZE];
94
DBUG_ASSERT(precision >= 0 && precision < NOT_FIXED_DEC && to != NULL);
96
res= dtoa(x, 5, precision, &decpt, &sign, &end, buf, sizeof(buf));
98
if (decpt == DTOA_OVERFLOW)
100
dtoa_free(res, buf, sizeof(buf));
118
for (i= decpt; i < 0; i++)
122
for (i= 1; i <= len; i++)
125
if (i == decpt && i < len)
136
for (i= precision - MY_MAX(0, (len - decpt)); i > 0; i--)
144
dtoa_free(res, buf, sizeof(buf));
151
Converts a given floating point number to a zero-terminated string
152
representation with a given field width using the 'e' format
153
(aka scientific notation) or the 'f' one.
156
The format is chosen automatically to provide the most number of significant
157
digits (and thus, precision) with a given field width. In many cases, the
158
result is similar to that of sprintf(to, "%g", x) with a few notable
160
- the conversion is usually more precise than C library functions.
161
- there is no 'precision' argument. instead, we specify the number of
162
characters available for conversion (i.e. a field width).
163
- the result never exceeds the specified field width. If the field is too
164
short to contain even a rounded decimal representation, my_gcvt()
165
indicates overflow and truncates the output string to the specified width.
166
- float-type arguments are handled differently than double ones. For a
167
float input number (i.e. when the 'type' argument is MY_GCVT_ARG_FLOAT)
168
we deliberately limit the precision of conversion by FLT_DIG digits to
169
avoid garbage past the significant digits.
170
- unlike sprintf(), in cases where the 'e' format is preferred, we don't
171
zero-pad the exponent to save space for significant digits. The '+' sign
172
for a positive exponent does not appear for the same reason.
174
@param x the input floating point number.
175
@param type is either MY_GCVT_ARG_FLOAT or MY_GCVT_ARG_DOUBLE.
176
Specifies the type of the input number (see notes above).
177
@param width field width in characters. The minimal field width to
178
hold any number representation (albeit rounded) is 7
179
characters ("-Ne-NNN").
180
@param to pointer to the output buffer. The result is always
181
zero-terminated, and the longest returned string is thus
183
@param error if not NULL, points to a location where the status of
184
conversion is stored upon return.
185
FALSE successful conversion
186
TRUE the input number is [-,+]infinity or nan.
187
The output string in this case is always '0'.
188
@return number of written characters (excluding terminating '\0')
191
Check if it is possible and makes sense to do our own rounding on top of
192
dtoa() instead of calling dtoa() twice in (rare) cases when the resulting
193
string representation does not fit in the specified field width and we want
194
to re-round the input number with fewer significant digits. Examples:
196
my_gcvt(-9e-3, ..., 4, ...);
197
my_gcvt(-9e-3, ..., 2, ...);
198
my_gcvt(1.87e-3, ..., 4, ...);
199
my_gcvt(55, ..., 1, ...);
201
We do our best to minimize such cases by:
203
- passing to dtoa() the field width as the number of significant digits
205
- removing the sign of the number early (and decreasing the width before
206
passing it to dtoa())
208
- choosing the proper format to preserve the most number of significant
212
size_t my_gcvt(double x, my_gcvt_arg_type type, int width, char *to,
215
int decpt, sign, len, exp_len;
216
char *res, *src, *end, *dst= to, *dend= dst + width;
217
char buf[DTOA_BUFF_SIZE];
218
my_bool have_space, force_e_format;
219
DBUG_ASSERT(width > 0 && to != NULL);
221
/* We want to remove '-' from equations early */
225
res= dtoa(x, 4, type == MY_GCVT_ARG_DOUBLE ? width : MY_MIN(width, FLT_DIG),
226
&decpt, &sign, &end, buf, sizeof(buf));
227
if (decpt == DTOA_OVERFLOW)
229
dtoa_free(res, buf, sizeof(buf));
244
Number of digits in the exponent from the 'e' conversion.
245
The sign of the exponent is taken into account separetely, we don't need
248
exp_len= 1 + (decpt >= 101 || decpt <= -99) + (decpt >= 11 || decpt <= -9);
251
Do we have enough space for all digits in the 'f' format?
252
Let 'len' be the number of significant digits returned by dtoa,
253
and F be the length of the resulting decimal representation.
254
Consider the following cases:
255
1. decpt <= 0, i.e. we have "0.NNN" => F = len - decpt + 2
256
2. 0 < decpt < len, i.e. we have "NNN.NNN" => F = len + 1
257
3. len <= decpt, i.e. we have "NNN00" => F = decpt
259
have_space= (decpt <= 0 ? len - decpt + 2 :
260
decpt > 0 && decpt < len ? len + 1 :
263
The following is true when no significant digits can be placed with the
264
specified field width using the 'f' format, and the 'e' format
265
will not be truncated.
267
force_e_format= (decpt <= 0 && width <= 2 - decpt && width >= 3 + exp_len);
269
Assume that we don't have enough space to place all significant digits in
270
the 'f' format. We have to choose between the 'e' format and the 'f' one
271
to keep as many significant digits as possible.
272
Let E and F be the lengths of decimal representaion in the 'e' and 'f'
273
formats, respectively. We want to use the 'f' format if, and only if F <= E.
274
Consider the following cases:
276
F = len - decpt + 2 (see above)
277
E = len + (len > 1) + 1 + 1 (decpt <= -99) + (decpt <= -9) + 1
279
(F <= E) <=> (len == 1 && decpt >= -1) || (len > 1 && decpt >= -2)
280
We also need to ensure that if the 'f' format is chosen,
281
the field width allows us to place at least one significant digit
282
(i.e. width > 2 - decpt). If not, we prefer the 'e' format.
284
F = len + 1 (see above)
285
E = len + 1 + 1 + ... ("N.NNeMMM")
286
F is always less than E.
287
3. len <= decpt <= width
288
In this case we have enough space to represent the number in the 'f'
289
format, so we prefer it with some exceptions.
291
The number cannot be represented in the 'f' format at all, always use
296
Not enough space, let's see if the 'f' format provides the most number
297
of significant digits.
299
((decpt <= width && (decpt >= -1 || (decpt == -2 &&
300
(len > 1 || !force_e_format)))) &&
304
Use the 'e' format in some cases even if we have enough space for the
305
'f' one. See comment for MAX_DECPT_FOR_F_FORMAT.
307
(!have_space || (decpt >= -MAX_DECPT_FOR_F_FORMAT + 1 &&
308
(decpt <= MAX_DECPT_FOR_F_FORMAT || len > decpt))))
313
width-= (decpt < len) + (decpt <= 0 ? 1 - decpt : 0);
315
/* Do we have to truncate any digits? */
326
We want to truncate (len - width) least significant digits after the
327
decimal point. For this we are calling dtoa with mode=5, passing the
328
number of significant digits = (len-decpt) - (len-width) = width-decpt
330
dtoa_free(res, buf, sizeof(buf));
331
res= dtoa(x, 5, width - decpt, &decpt, &sign, &end, buf, sizeof(buf));
338
/* Underflow. Just print '0' and exit */
344
At this point we are sure we have enough space to put all digits
347
if (sign && dst < dend)
353
if (len > 0 && dst < dend)
355
for (; decpt < 0 && dst < dend; decpt++)
359
for (i= 1; i <= len && dst < dend; i++)
362
if (i == decpt && i < len && dst < dend)
365
while (i++ <= decpt && dst < dend)
379
width-= 1 + exp_len; /* eNNN */
392
/* Do we have to truncate any digits? */
395
/* Yes, re-convert with a smaller width */
396
dtoa_free(res, buf, sizeof(buf));
397
res= dtoa(x, 4, width, &decpt, &sign, &end, buf, sizeof(buf));
404
At this point we are sure we have enough space to put all digits
407
if (sign && dst < dend)
411
if (len > 1 && dst < dend)
414
while (src < end && dst < dend)
419
if (decpt_sign && dst < dend)
422
if (decpt >= 100 && dst < dend)
424
*dst++= decpt / 100 + '0';
427
*dst++= decpt / 10 + '0';
429
else if (decpt >= 10 && dst < dend)
430
*dst++= decpt / 10 + '0';
432
*dst++= decpt % 10 + '0';
437
dtoa_free(res, buf, sizeof(buf));
445
Converts string to double (string does not have to be zero-terminated)
448
This is a wrapper around dtoa's version of strtod().
450
@param str input string
451
@param end address of a pointer to the first character after the input
452
string. Upon return the pointer is set to point to the first
454
@param error Upon return is set to EOVERFLOW in case of underflow or
457
@return The resulting double value. In case of underflow, 0.0 is
458
returned. In case overflow, signed DBL_MAX is returned.
461
double my_strtod(const char *str, char **end, int *error)
463
char buf[DTOA_BUFF_SIZE];
465
DBUG_ASSERT(end != NULL && ((str != NULL && *end != NULL) ||
466
(str == NULL && *end == NULL)) &&
469
res= my_strtod_int(str, end, error, buf, sizeof(buf));
470
return (*error == 0) ? res : (res < 0 ? -DBL_MAX : DBL_MAX);
474
double my_atof(const char *nptr)
477
const char *end= nptr+65535; /* Should be enough */
478
return (my_strtod(nptr, (char**) &end, &error));
482
/****************************************************************
484
* The author of this software is David M. Gay.
486
* Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
488
* Permission to use, copy, modify, and distribute this software for any
489
* purpose without fee is hereby granted, provided that this entire notice
490
* is included in all copies of any software which is or includes a copy
491
* or modification of this software and in all copies of the supporting
492
* documentation for such software.
494
* THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
495
* WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
496
* REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
497
* OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
499
***************************************************************/
500
/* Please send bug reports to David M. Gay (dmg at acm dot org,
501
* with " at " changed at "@" and " dot " changed to "."). */
504
Original copy of the software is located at http://www.netlib.org/fp/dtoa.c
505
It was adjusted to serve MySQL server needs:
506
* strtod() was modified to not expect a zero-terminated string.
507
It now honors 'se' (end of string) argument as the input parameter,
508
not just as the output one.
509
* in dtoa(), in case of overflow/underflow/NaN result string now contains "0";
510
decpt is set to DTOA_OVERFLOW to indicate overflow.
511
* support for VAX, IBM mainframe and 16-bit hardware removed
512
* we always assume that 64-bit integer type is available
513
* support for Kernigan-Ritchie style headers (pre-ANSI compilers)
515
* all gcc warnings ironed out
516
* we always assume multithreaded environment, so we had to change
517
memory allocation procedures to use stack in most cases;
518
malloc is used as the last resort.
519
* pow5mult rewritten to use pre-calculated pow5 list instead of
520
the one generated on the fly.
525
On a machine with IEEE extended-precision registers, it is
526
necessary to specify double-precision (53-bit) rounding precision
527
before invoking strtod or dtoa. If the machine uses (the equivalent
528
of) Intel 80x87 arithmetic, the call
529
_control87(PC_53, MCW_PC);
530
does this with many compilers. Whether this or another call is
531
appropriate depends on the compiler; for this to work, it may be
532
necessary to #include "float.h" or another system-dependent header
537
#define Honor_FLT_ROUNDS if FLT_ROUNDS can assume the values 2 or 3
538
and dtoa should round accordingly.
539
#define Check_FLT_ROUNDS if FLT_ROUNDS can assume the values 2 or 3
540
and Honor_FLT_ROUNDS is not #defined.
542
TODO: check if we can get rid of the above two
546
typedef uint32 ULong;
548
typedef uint64 ULLong;
550
typedef union { double d; ULong L[2]; } U;
552
#if defined(WORDS_BIGENDIAN) || (defined(__FLOAT_WORD_ORDER) && \
553
(__FLOAT_WORD_ORDER == __BIG_ENDIAN))
554
#define word0(x) (x)->L[0]
555
#define word1(x) (x)->L[1]
557
#define word0(x) (x)->L[1]
558
#define word1(x) (x)->L[0]
561
#define dval(x) (x)->d
563
/* #define P DBL_MANT_DIG */
564
/* Ten_pmax= floor(P*log(2)/log(5)) */
565
/* Bletch= (highest power of 2 < DBL_MAX_10_EXP) / 16 */
566
/* Quick_max= floor((P-1)*log(FLT_RADIX)/log(10) - 1) */
567
/* Int_max= floor(P*log(FLT_RADIX)/log(10) - 1) */
570
#define Exp_shift1 20
571
#define Exp_msk1 0x100000
572
#define Exp_mask 0x7ff00000
576
#define Exp_1 0x3ff00000
577
#define Exp_11 0x3ff00000
579
#define Frac_mask 0xfffff
580
#define Frac_mask1 0xfffff
583
#define Bndry_mask 0xfffff
584
#define Bndry_mask1 0xfffff
586
#define Sign_bit 0x80000000
594
#define Flt_Rounds FLT_ROUNDS
598
#endif /*Flt_Rounds*/
600
#ifdef Honor_FLT_ROUNDS
601
#define Rounding rounding
602
#undef Check_FLT_ROUNDS
603
#define Check_FLT_ROUNDS
605
#define Rounding Flt_Rounds
608
#define rounded_product(a,b) a*= b
609
#define rounded_quotient(a,b) a/= b
611
#define Big0 (Frac_mask1 | Exp_msk1*(DBL_MAX_EXP+Bias-1))
612
#define Big1 0xffffffff
613
#define FFFFFFFF 0xffffffffUL
615
/* This is tested to be enough for dtoa */
619
#define Bcopy(x,y) memcpy((char *)&x->sign, (char *)&y->sign, \
620
2*sizeof(int) + y->wds*sizeof(ULong))
622
/* Arbitrary-length integer */
624
typedef struct Bigint
627
ULong *x; /* points right after this Bigint object */
628
struct Bigint *next; /* to maintain free lists */
630
int k; /* 2^k = maxwds */
631
int maxwds; /* maximum length in 32-bit words */
632
int sign; /* not zero if number is negative */
633
int wds; /* current length in 32-bit words */
637
/* A simple stack-memory based allocator for Bigints */
639
typedef struct Stack_alloc
645
Having list of free blocks lets us reduce maximum required amount
646
of memory from ~4000 bytes to < 1680 (tested on x86).
648
Bigint *freelist[Kmax+1];
653
Try to allocate object on stack, and resort to malloc if all
654
stack memory is used. Ensure allocated objects to be aligned by the pointer
655
size in order to not break the alignment rules when storing a pointer to a
659
static Bigint *Balloc(int k, Stack_alloc *alloc)
662
DBUG_ASSERT(k <= Kmax);
663
if (k <= Kmax && alloc->freelist[k])
665
rv= alloc->freelist[k];
666
alloc->freelist[k]= rv->p.next;
673
len= MY_ALIGN(sizeof(Bigint) + x * sizeof(ULong), SIZEOF_CHARP);
675
if (alloc->free + len <= alloc->end)
677
rv= (Bigint*) alloc->free;
681
rv= (Bigint*) malloc(len);
686
rv->sign= rv->wds= 0;
687
rv->p.x= (ULong*) (rv + 1);
693
If object was allocated on stack, try putting it to the free
694
list. Otherwise call free().
697
static void Bfree(Bigint *v, Stack_alloc *alloc)
699
char *gptr= (char*) v; /* generic pointer */
700
if (gptr < alloc->begin || gptr >= alloc->end)
702
else if (v->k <= Kmax)
705
Maintain free lists only for stack objects: this way we don't
706
have to bother with freeing lists in the end of dtoa;
707
heap should not be used normally anyway.
709
v->p.next= alloc->freelist[v->k];
710
alloc->freelist[v->k]= v;
716
This is to place return value of dtoa in: tries to use stack
717
as well, but passes by free lists management and just aligns len by
718
the pointer size in order to not break the alignment rules when storing a
722
static char *dtoa_alloc(int i, Stack_alloc *alloc)
725
int aligned_size= MY_ALIGN(i, SIZEOF_CHARP);
726
if (alloc->free + aligned_size <= alloc->end)
729
alloc->free+= aligned_size;
738
dtoa_free() must be used to free values s returned by dtoa()
739
This is the counterpart of dtoa_alloc()
742
static void dtoa_free(char *gptr, char *buf, size_t buf_size)
744
if (gptr < buf || gptr >= buf + buf_size)
749
/* Bigint arithmetic functions */
751
/* Multiply by m and add a */
753
static Bigint *multadd(Bigint *b, int m, int a, Stack_alloc *alloc)
766
y= *x * (ULLong)m + carry;
768
*x++= (ULong)(y & FFFFFFFF);
773
if (wds >= b->maxwds)
775
b1= Balloc(b->k+1, alloc);
780
b->p.x[wds++]= (ULong) carry;
787
Converts a string to Bigint.
789
Now we have nd0 digits, starting at s, followed by a
790
decimal point, followed by nd-nd0 digits.
791
Unless nd0 == nd, in which case we have a number of the form:
792
".xxxxxx" or "xxxxxx."
794
@param s Input string, already partially parsed by my_strtod_int().
795
@param nd0 Number of digits before decimal point.
796
@param nd Total number of digits.
797
@param y9 Pre-computed value of the first nine digits.
798
@param alloc Stack allocator for Bigints.
800
static Bigint *s2b(const char *s, int nd0, int nd, ULong y9, Stack_alloc *alloc)
807
for (k= 0, y= 1; x > y; y <<= 1, k++) ;
817
b= multadd(b, 10, *s++ - '0', alloc);
823
/* now do the fractional part */
825
b= multadd(b, 10, *s++ - '0', alloc);
830
static int hi0bits(register ULong x)
834
if (!(x & 0xffff0000))
839
if (!(x & 0xff000000))
844
if (!(x & 0xf0000000))
849
if (!(x & 0xc0000000))
854
if (!(x & 0x80000000))
857
if (!(x & 0x40000000))
864
static int lo0bits(ULong *y)
867
register ULong x= *y;
914
/* Convert integer to Bigint number */
916
static Bigint *i2b(int i, Stack_alloc *alloc)
927
/* Multiply two Bigint numbers */
929
static Bigint *mult(Bigint *a, Bigint *b, Stack_alloc *alloc)
933
ULong *x, *xa, *xae, *xb, *xbe, *xc, *xc0;
950
for (x= c->p.x, xa= x + wc; x < xa; x++)
957
for (; xb < xbe; xc0++)
966
z= *x++ * (ULLong)y + *xc + carry;
968
*xc++= (ULong) (z & FFFFFFFF);
974
for (xc0= c->p.x, xc= xc0 + wc; wc > 0 && !*--xc; --wc) ;
981
Precalculated array of powers of 5: tested to be enough for
982
vasting majority of dtoa_r cases.
985
static ULong powers5[]=
993
2242703233UL, 762134875UL, 1262UL,
995
3211403009UL, 1849224548UL, 3668416493UL, 3913284084UL, 1593091UL,
997
781532673UL, 64985353UL, 253049085UL, 594863151UL, 3553621484UL,
998
3288652808UL, 3167596762UL, 2788392729UL, 3911132675UL, 590UL,
1000
2553183233UL, 3201533787UL, 3638140786UL, 303378311UL, 1809731782UL,
1001
3477761648UL, 3583367183UL, 649228654UL, 2915460784UL, 487929380UL,
1002
1011012442UL, 1677677582UL, 3428152256UL, 1710878487UL, 1438394610UL,
1003
2161952759UL, 4100910556UL, 1608314830UL, 349175UL
1007
static Bigint p5_a[]=
1009
/* { x } - k - maxwds - sign - wds */
1010
{ { powers5 }, 1, 1, 0, 1 },
1011
{ { powers5 + 1 }, 1, 1, 0, 1 },
1012
{ { powers5 + 2 }, 1, 2, 0, 2 },
1013
{ { powers5 + 4 }, 2, 3, 0, 3 },
1014
{ { powers5 + 7 }, 3, 5, 0, 5 },
1015
{ { powers5 + 12 }, 4, 10, 0, 10 },
1016
{ { powers5 + 22 }, 5, 19, 0, 19 }
1019
#define P5A_MAX (sizeof(p5_a)/sizeof(*p5_a) - 1)
1021
static Bigint *pow5mult(Bigint *b, int k, Stack_alloc *alloc)
1023
Bigint *b1, *p5, *p51=NULL;
1025
static int p05[3]= { 5, 25, 125 };
1026
my_bool overflow= FALSE;
1029
b= multadd(b, p05[i-1], 0, alloc);
1038
b1= mult(b, p5, alloc);
1044
/* Calculate next power of 5 */
1047
p51= mult(p5, p5, alloc);
1051
else if (p5 < p5_a + P5A_MAX)
1053
else if (p5 == p5_a + P5A_MAX)
1055
p5= mult(p5, p5, alloc);
1065
static Bigint *lshift(Bigint *b, int k, Stack_alloc *alloc)
1069
ULong *x, *x1, *xe, z;
1074
for (i= b->maxwds; n1 > i; i<<= 1)
1076
b1= Balloc(k1, alloc);
1078
for (i= 0; i < n; i++)
1105
static int cmp(Bigint *a, Bigint *b)
1107
ULong *xa, *xa0, *xb, *xb0;
1121
return *xa < *xb ? -1 : 1;
1129
static Bigint *diff(Bigint *a, Bigint *b, Stack_alloc *alloc)
1133
ULong *xa, *xae, *xb, *xbe, *xc;
1139
c= Balloc(0, alloc);
1153
c= Balloc(a->k, alloc);
1165
y= (ULLong)*xa++ - *xb++ - borrow;
1166
borrow= y >> 32 & (ULong)1;
1167
*xc++= (ULong) (y & FFFFFFFF);
1173
borrow= y >> 32 & (ULong)1;
1174
*xc++= (ULong) (y & FFFFFFFF);
1183
static double ulp(U *x)
1188
L= (word0(x) & Exp_mask) - (P - 1)*Exp_msk1;
1195
static double b2d(Bigint *a, int *e)
1197
ULong *xa, *xa0, w, y, z;
1200
#define d0 word0(&d)
1201
#define d1 word1(&d)
1210
d0= Exp_1 | y >> (Ebits - k);
1211
w= xa > xa0 ? *--xa : 0;
1212
d1= y << ((32-Ebits) + k) | w >> (Ebits - k);
1215
z= xa > xa0 ? *--xa : 0;
1218
d0= Exp_1 | y << k | z >> (32 - k);
1219
y= xa > xa0 ? *--xa : 0;
1220
d1= z << k | y >> (32 - k);
1234
static Bigint *d2b(U *d, int *e, int *bits, Stack_alloc *alloc)
1243
b= Balloc(1, alloc);
1247
d0 &= 0x7fffffff; /* clear sign bit, which we ignore */
1248
if ((de= (int)(d0 >> Exp_shift)))
1252
if ((k= lo0bits(&y)))
1254
x[0]= y | z << (32 - k);
1259
i= b->wds= (x[1]= z) ? 2 : 1;
1270
*e= de - Bias - (P-1) + k;
1275
*e= de - Bias - (P-1) + 1 + k;
1276
*bits= 32*i - hi0bits(x[i-1]);
1284
static double ratio(Bigint *a, Bigint *b)
1289
dval(&da)= b2d(a, &ka);
1290
dval(&db)= b2d(b, &kb);
1291
k= ka - kb + 32*(a->wds - b->wds);
1293
word0(&da)+= k*Exp_msk1;
1297
word0(&db)+= k*Exp_msk1;
1299
return dval(&da) / dval(&db);
1302
static const double tens[] =
1304
1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
1305
1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
1309
static const double bigtens[]= { 1e16, 1e32, 1e64, 1e128, 1e256 };
1310
static const double tinytens[]=
1311
{ 1e-16, 1e-32, 1e-64, 1e-128,
1312
9007199254740992.*9007199254740992.e-256 /* = 2^106 * 1e-53 */
1315
The factor of 2^53 in tinytens[4] helps us avoid setting the underflow
1316
flag unnecessarily. It leads to a song and dance at the end of strtod.
1318
#define Scale_Bit 0x10
1322
strtod for IEEE--arithmetic machines.
1324
This strtod returns a nearest machine number to the input decimal
1325
string (or sets errno to EOVERFLOW). Ties are broken by the IEEE round-even
1328
Inspired loosely by William D. Clinger's paper "How to Read Floating
1329
Point Numbers Accurately" [Proc. ACM SIGPLAN '90, pp. 92-101].
1333
1. We only require IEEE (not IEEE double-extended).
1334
2. We get by with floating-point arithmetic in a case that
1335
Clinger missed -- when we're computing d * 10^n
1336
for a small integer d and the integer n is not too
1337
much larger than 22 (the maximum integer k for which
1338
we can represent 10^k exactly), we may be able to
1339
compute (d*10^k) * 10^(e-k) with just one roundoff.
1340
3. Rather than a bit-at-a-time adjustment of the binary
1341
result in the hard case, we use floating-point
1342
arithmetic to determine the adjustment to within
1343
one bit; only in really hard cases do we need to
1344
compute a second residual.
1345
4. Because of 3., we don't need a large table of powers of 10
1346
for ten-to-e (just some small tables, e.g. of 10^k
1350
static double my_strtod_int(const char *s00, char **se, int *error, char *buf, size_t buf_size)
1353
int bb2, bb5, bbe, bd2, bd5, bbbits, bs2, UNINIT_VAR(c), dsign,
1354
e, e1, esign, i, j, k, nd, nd0, nf, nz, nz0, sign;
1355
const char *s, *s0, *s1, *end = *se;
1357
U aadj2, adj, rv, rv0;
1360
Bigint *bb, *bb1, *bd, *bd0, *bs, *delta;
1362
int inexact, oldinexact;
1364
#ifdef Honor_FLT_ROUNDS
1371
alloc.begin= alloc.free= buf;
1372
alloc.end= buf + buf_size;
1373
memset(alloc.freelist, 0, sizeof(alloc.freelist));
1377
for (s= s00; s < end; s++)
1402
while (++s < end && *s == '0') ;
1408
for (nd= nf= 0; s < end && (c= *s) >= '0' && c <= '9'; nd++, s++)
1414
if (s < end && c == '.')
1419
for (; s < end; ++s)
1426
if (s < end && c > '0' && c <= '9')
1435
for (; s < end; ++s)
1438
if (c < '0' || c > '9')
1441
Here we are parsing the fractional part.
1442
We can stop counting digits after a while: the extra digits
1443
will not contribute to the actual result produced by s2b().
1444
We have to continue scanning, in case there is an exponent part.
1446
if (nd < 2 * DBL_DIG)
1452
for (i= 1; i < nz; i++)
1455
else if (nd <= DBL_DIG + 1)
1459
else if (nd <= DBL_DIG + 1)
1468
if (s < end && (c == 'e' || c == 'E'))
1470
if (!nd && !nz && !nz0)
1481
if (s < end && c >= '0' && c <= '9')
1483
while (s < end && c == '0')
1485
if (s < end && c > '0' && c <= '9') {
1488
while (++s < end && (c= *s) >= '0' && c <= '9')
1490
if (s - s1 > 8 || L > 19999)
1491
/* Avoid confusion from exponents
1492
* so large that e might overflow.
1494
e= 19999; /* safe for 16 bit ints */
1519
Now we have nd0 digits, starting at s0, followed by a
1520
decimal point, followed by nd-nd0 digits. The number we're
1521
after is the integer represented by those digits times
1527
k= nd < DBL_DIG + 1 ? nd : DBL_DIG + 1;
1533
oldinexact = get_inexact();
1535
dval(&rv)= tens[k - 9] * dval(&rv) + z;
1539
#ifndef Honor_FLT_ROUNDS
1550
#ifdef Honor_FLT_ROUNDS
1551
/* round correctly FLT_ROUNDS = 2 or 3 */
1558
/* rv = */ rounded_product(dval(&rv), tens[e]);
1562
if (e <= Ten_pmax + i)
1565
A fancier test would sometimes let us do
1566
this for larger i values.
1568
#ifdef Honor_FLT_ROUNDS
1569
/* round correctly FLT_ROUNDS = 2 or 3 */
1577
dval(&rv)*= tens[i];
1578
/* rv = */ rounded_product(dval(&rv), tens[e]);
1582
#ifndef Inaccurate_Divide
1583
else if (e >= -Ten_pmax)
1585
#ifdef Honor_FLT_ROUNDS
1586
/* round correctly FLT_ROUNDS = 2 or 3 */
1593
/* rv = */ rounded_quotient(dval(&rv), tens[-e]);
1603
oldinexact= get_inexact();
1606
#ifdef Honor_FLT_ROUNDS
1607
if ((rounding= Flt_Rounds) >= 2)
1610
rounding= rounding == 2 ? 0 : 2;
1617
/* Get starting approximation = rv * 10**e1 */
1622
dval(&rv)*= tens[i];
1625
if (e1 > DBL_MAX_10_EXP)
1629
/* Can't trust HUGE_VAL */
1630
#ifdef Honor_FLT_ROUNDS
1633
case 0: /* toward 0 */
1634
case 3: /* toward -infinity */
1639
word0(&rv)= Exp_mask;
1642
#else /*Honor_FLT_ROUNDS*/
1643
word0(&rv)= Exp_mask;
1645
#endif /*Honor_FLT_ROUNDS*/
1647
/* set overflow bit */
1649
dval(&rv0)*= dval(&rv0);
1656
for(j= 0; e1 > 1; j++, e1>>= 1)
1658
dval(&rv)*= bigtens[j];
1659
/* The last multiplication could overflow. */
1660
word0(&rv)-= P*Exp_msk1;
1661
dval(&rv)*= bigtens[j];
1662
if ((z= word0(&rv) & Exp_mask) > Exp_msk1 * (DBL_MAX_EXP + Bias - P))
1664
if (z > Exp_msk1 * (DBL_MAX_EXP + Bias - 1 - P))
1666
/* set to largest number (Can't trust DBL_MAX) */
1671
word0(&rv)+= P*Exp_msk1;
1678
dval(&rv)/= tens[i];
1681
if (e1 >= 1 << n_bigtens)
1685
for(j= 0; e1 > 0; j++, e1>>= 1)
1687
dval(&rv)*= tinytens[j];
1688
if (scale && (j = 2 * P + 1 - ((word0(&rv) & Exp_mask) >> Exp_shift)) > 0)
1690
/* scaled rv is denormal; zap j low bits */
1695
word0(&rv)= (P + 2) * Exp_msk1;
1697
word0(&rv)&= 0xffffffff << (j - 32);
1700
word1(&rv)&= 0xffffffff << j;
1713
/* Now the hard part -- adjusting rv to the correct value.*/
1715
/* Put digits into bd: true value = bd * 10^e */
1717
bd0= s2b(s0, nd0, nd, y, &alloc);
1721
bd= Balloc(bd0->k, &alloc);
1723
bb= d2b(&rv, &bbe, &bbbits, &alloc); /* rv = bb * 2^bbe */
1741
#ifdef Honor_FLT_ROUNDS
1746
i= j + bbbits - 1; /* logb(rv) */
1747
if (i < Emin) /* denormal */
1754
i= bb2 < bd2 ? bb2 : bd2;
1765
bs= pow5mult(bs, bb5, &alloc);
1766
bb1= mult(bs, bb, &alloc);
1771
bb= lshift(bb, bb2, &alloc);
1773
bd= pow5mult(bd, bd5, &alloc);
1775
bd= lshift(bd, bd2, &alloc);
1777
bs= lshift(bs, bs2, &alloc);
1778
delta= diff(bb, bd, &alloc);
1782
#ifdef Honor_FLT_ROUNDS
1787
/* Error is less than an ulp */
1788
if (!delta->p.x[0] && delta->wds <= 1)
1807
if (!word1(&rv) && !(word0(&rv) & Frac_mask))
1809
y= word0(&rv) & Exp_mask;
1810
if (!scale || y > 2*P*Exp_msk1)
1812
delta= lshift(delta, Log2P, &alloc);
1813
if (cmp(delta, bs) <= 0)
1818
if (scale && (y= word0(&rv) & Exp_mask) <= 2 * P * Exp_msk1)
1819
word0(&adj)+= (2 * P + 1) * Exp_msk1 - y;
1820
dval(&rv)+= adj.d * ulp(&rv);
1824
adj.d= ratio(delta, bs);
1827
if (adj.d <= 0x7ffffffe)
1829
/* adj = rounding ? ceil(adj) : floor(adj); */
1833
if (!((rounding >> 1) ^ dsign))
1838
if (scale && (y= word0(&rv) & Exp_mask) <= 2 * P * Exp_msk1)
1839
word0(&adj)+= (2 * P + 1) * Exp_msk1 - y;
1847
#endif /*Honor_FLT_ROUNDS*/
1852
Error is less than half an ulp -- check for special case of mantissa
1855
if (dsign || word1(&rv) || word0(&rv) & Bndry_mask ||
1856
(word0(&rv) & Exp_mask) <= (2 * P + 1) * Exp_msk1)
1859
if (!delta->x[0] && delta->wds <= 1)
1864
if (!delta->p.x[0] && delta->wds <= 1)
1872
delta= lshift(delta, Log2P, &alloc);
1873
if (cmp(delta, bs) > 0)
1879
/* exactly half-way between */
1882
if ((word0(&rv) & Bndry_mask1) == Bndry_mask1 &&
1884
((scale && (y = word0(&rv) & Exp_mask) <= 2 * P * Exp_msk1) ?
1885
(0xffffffff & (0xffffffff << (2*P+1-(y>>Exp_shift)))) :
1888
/*boundary case -- increment exponent*/
1889
word0(&rv)= (word0(&rv) & Exp_mask) + Exp_msk1;
1895
else if (!(word0(&rv) & Bndry_mask) && !word1(&rv))
1898
/* boundary case -- decrement exponent */
1901
L= word0(&rv) & Exp_mask;
1902
if (L <= (2 *P + 1) * Exp_msk1)
1904
if (L > (P + 2) * Exp_msk1)
1905
/* round even ==> accept rv */
1907
/* rv = smallest denormal */
1911
L= (word0(&rv) & Exp_mask) - Exp_msk1;
1912
word0(&rv)= L | Bndry_mask1;
1913
word1(&rv)= 0xffffffff;
1916
if (!(word1(&rv) & LSB))
1919
dval(&rv)+= ulp(&rv);
1922
dval(&rv)-= ulp(&rv);
1929
if ((aadj= ratio(delta, bs)) <= 2.)
1933
else if (word1(&rv) || word0(&rv) & Bndry_mask)
1935
if (word1(&rv) == Tiny1 && !word0(&rv))
1942
/* special case -- power of FLT_RADIX to be rounded down... */
1943
if (aadj < 2. / FLT_RADIX)
1944
aadj= 1. / FLT_RADIX;
1953
aadj1= dsign ? aadj : -aadj;
1954
#ifdef Check_FLT_ROUNDS
1957
case 2: /* towards +infinity */
1960
case 0: /* towards 0 */
1961
case 3: /* towards -infinity */
1965
if (Flt_Rounds == 0)
1967
#endif /*Check_FLT_ROUNDS*/
1969
y= word0(&rv) & Exp_mask;
1971
/* Check for overflow */
1973
if (y == Exp_msk1 * (DBL_MAX_EXP + Bias - 1))
1975
dval(&rv0)= dval(&rv);
1976
word0(&rv)-= P * Exp_msk1;
1977
adj.d= aadj1 * ulp(&rv);
1979
if ((word0(&rv) & Exp_mask) >= Exp_msk1 * (DBL_MAX_EXP + Bias - P))
1981
if (word0(&rv0) == Big0 && word1(&rv0) == Big1)
1988
word0(&rv)+= P * Exp_msk1;
1992
if (scale && y <= 2 * P * Exp_msk1)
1994
if (aadj <= 0x7fffffff)
1996
if ((z= (ULong) aadj) <= 0)
1999
aadj1= dsign ? aadj : -aadj;
2001
dval(&aadj2) = aadj1;
2002
word0(&aadj2)+= (2 * P + 1) * Exp_msk1 - y;
2003
aadj1= dval(&aadj2);
2004
adj.d= aadj1 * ulp(&rv);
2011
adj.d= aadj1 * ulp(&rv);
2015
z= word0(&rv) & Exp_mask;
2020
/* Can we stop now? */
2023
/* The tolerances below are conservative. */
2024
if (dsign || word1(&rv) || word0(&rv) & Bndry_mask)
2026
if (aadj < .4999999 || aadj > .5000001)
2029
else if (aadj < .4999999 / FLT_RADIX)
2037
Bfree(delta, &alloc);
2044
word0(&rv0)= Exp_1 + (70 << Exp_shift);
2049
else if (!oldinexact)
2054
word0(&rv0)= Exp_1 - 2 * P * Exp_msk1;
2056
dval(&rv)*= dval(&rv0);
2059
if (inexact && !(word0(&rv) & Exp_mask))
2061
/* set underflow bit */
2063
dval(&rv0)*= dval(&rv0);
2071
Bfree(delta, &alloc);
2074
return sign ? -dval(&rv) : dval(&rv);
2078
static int quorem(Bigint *b, Bigint *S)
2081
ULong *bx, *bxe, q, *sx, *sxe;
2082
ULLong borrow, carry, y, ys;
2091
q= *bxe / (*sxe + 1); /* ensure q <= true quotient */
2098
ys= *sx++ * (ULLong)q + carry;
2100
y= *bx - (ys & FFFFFFFF) - borrow;
2101
borrow= y >> 32 & (ULong)1;
2102
*bx++= (ULong) (y & FFFFFFFF);
2108
while (--bxe > bx && !*bxe)
2124
y= *bx - (ys & FFFFFFFF) - borrow;
2125
borrow= y >> 32 & (ULong)1;
2126
*bx++= (ULong) (y & FFFFFFFF);
2133
while (--bxe > bx && !*bxe)
2143
dtoa for IEEE arithmetic (dmg): convert double to ASCII string.
2145
Inspired by "How to Print Floating-Point Numbers Accurately" by
2146
Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 112-126].
2149
1. Rather than iterating, we use a simple numeric overestimate
2150
to determine k= floor(log10(d)). We scale relevant
2151
quantities using O(log2(k)) rather than O(k) multiplications.
2152
2. For some modes > 2 (corresponding to ecvt and fcvt), we don't
2153
try to generate digits strictly left to right. Instead, we
2154
compute with fewer bits and propagate the carry if necessary
2155
when rounding the final digit up. This is often faster.
2156
3. Under the assumption that input will be rounded nearest,
2157
mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22.
2158
That is, we allow equality in stopping tests when the
2159
round-nearest rule will give the same floating-point value
2160
as would satisfaction of the stopping test with strict
2162
4. We remove common factors of powers of 2 from relevant
2164
5. When converting floating-point integers less than 1e16,
2165
we use floating-point arithmetic rather than resorting
2166
to multiple-precision integers.
2167
6. When asked to produce fewer than 15 digits, we first try
2168
to get by with floating-point arithmetic; we resort to
2169
multiple-precision integer arithmetic only if we cannot
2170
guarantee that the floating-point calculation has given
2171
the correctly rounded result. For k requested digits and
2172
"uniformly" distributed input, the probability is
2173
something like 10^(k-15) that we must resort to the Long
2177
static char *dtoa(double dd, int mode, int ndigits, int *decpt, int *sign,
2178
char **rve, char *buf, size_t buf_size)
2181
Arguments ndigits, decpt, sign are similar to those
2182
of ecvt and fcvt; trailing zeros are suppressed from
2183
the returned string. If not null, *rve is set to point
2184
to the end of the return value. If d is +-Infinity or NaN,
2185
then *decpt is set to DTOA_OVERFLOW.
2188
0 ==> shortest string that yields d when read in
2189
and rounded to nearest.
2190
1 ==> like 0, but with Steele & White stopping rule;
2191
e.g. with IEEE P754 arithmetic , mode 0 gives
2192
1e23 whereas mode 1 gives 9.999999999999999e22.
2193
2 ==> max(1,ndigits) significant digits. This gives a
2194
return value similar to that of ecvt, except
2195
that trailing zeros are suppressed.
2196
3 ==> through ndigits past the decimal point. This
2197
gives a return value similar to that from fcvt,
2198
except that trailing zeros are suppressed, and
2199
ndigits can be negative.
2200
4,5 ==> similar to 2 and 3, respectively, but (in
2201
round-nearest mode) with the tests of mode 0 to
2202
possibly return a shorter string that rounds to d.
2203
With IEEE arithmetic and compilation with
2204
-DHonor_FLT_ROUNDS, modes 4 and 5 behave the same
2205
as modes 2 and 3 when FLT_ROUNDS != 1.
2206
6-9 ==> Debugging modes similar to mode - 4: don't try
2207
fast floating-point estimate (if applicable).
2209
Values of mode other than 0-9 are treated as mode 0.
2211
Sufficient space is allocated to the return value
2212
to hold the suppressed trailing zeros.
2215
int bbits, b2, b5, be, dig, i, ieps, UNINIT_VAR(ilim), ilim0,
2216
UNINIT_VAR(ilim1), j, j1, k, k0, k_check, leftright, m2, m5, s2, s5,
2217
spec_case, try_quick;
2221
Bigint *b, *b1, *delta, *mlo, *mhi, *S;
2225
#ifdef Honor_FLT_ROUNDS
2230
alloc.begin= alloc.free= buf;
2231
alloc.end= buf + buf_size;
2232
memset(alloc.freelist, 0, sizeof(alloc.freelist));
2235
if (word0(&u) & Sign_bit)
2237
/* set sign for everything, including 0's and NaNs */
2239
word0(&u) &= ~Sign_bit; /* clear sign bit */
2244
/* If infinity, set decpt to DTOA_OVERFLOW, if 0 set it to 1 */
2245
if (((word0(&u) & Exp_mask) == Exp_mask && (*decpt= DTOA_OVERFLOW)) ||
2246
(!dval(&u) && (*decpt= 1)))
2248
/* Infinity, NaN, 0 */
2249
char *res= (char*) dtoa_alloc(2, &alloc);
2257
#ifdef Honor_FLT_ROUNDS
2258
if ((rounding= Flt_Rounds) >= 2)
2261
rounding= rounding == 2 ? 0 : 2;
2268
b= d2b(&u, &be, &bbits, &alloc);
2269
if ((i= (int)(word0(&u) >> Exp_shift1 & (Exp_mask>>Exp_shift1))))
2271
dval(&d2)= dval(&u);
2272
word0(&d2) &= Frac_mask1;
2273
word0(&d2) |= Exp_11;
2276
log(x) ~=~ log(1.5) + (x-1.5)/1.5
2277
log10(x) = log(x) / log(10)
2278
~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10))
2279
log10(d)= (i-Bias)*log(2)/log(10) + log10(d2)
2281
This suggests computing an approximation k to log10(d) by
2283
k= (i - Bias)*0.301029995663981
2284
+ ( (d2-1.5)*0.289529654602168 + 0.176091259055681 );
2286
We want k to be too large rather than too small.
2287
The error in the first-order Taylor series approximation
2288
is in our favor, so we just round up the constant enough
2289
to compensate for any error in the multiplication of
2290
(i - Bias) by 0.301029995663981; since |i - Bias| <= 1077,
2291
and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14,
2292
adding 1e-13 to the constant term more than suffices.
2293
Hence we adjust the constant term to 0.1760912590558.
2294
(We could get a more accurate k by invoking log10,
2295
but this is probably not worthwhile.)
2303
/* d is denormalized */
2305
i= bbits + be + (Bias + (P-1) - 1);
2306
x= i > 32 ? word0(&u) << (64 - i) | word1(&u) >> (i - 32)
2307
: word1(&u) << (32 - i);
2309
word0(&d2)-= 31*Exp_msk1; /* adjust exponent */
2310
i-= (Bias + (P-1) - 1) + 1;
2313
ds= (dval(&d2)-1.5)*0.289529654602168 + 0.1760912590558 + i*0.301029995663981;
2315
if (ds < 0. && ds != k)
2316
k--; /* want k= floor(ds) */
2318
if (k >= 0 && k <= Ten_pmax)
2320
if (dval(&u) < tens[k])
2347
if (mode < 0 || mode > 9)
2350
#ifdef Check_FLT_ROUNDS
2351
try_quick= Rounding == 1;
2375
ilim= ilim1= i= ndigits;
2387
s= s0= dtoa_alloc(i, &alloc);
2389
#ifdef Honor_FLT_ROUNDS
2390
if (mode > 1 && rounding != 1)
2394
if (ilim >= 0 && ilim <= Quick_max && try_quick)
2396
/* Try to get by with floating-point arithmetic. */
2398
dval(&d2)= dval(&u);
2401
ieps= 2; /* conservative */
2408
/* prevent overflows */
2410
dval(&u)/= bigtens[n_bigtens-1];
2413
for (; j; j>>= 1, i++)
2425
dval(&u)*= tens[j1 & 0xf];
2426
for (j= j1 >> 4; j; j>>= 1, i++)
2431
dval(&u)*= bigtens[i];
2435
if (k_check && dval(&u) < 1. && ilim > 0)
2444
dval(&eps)= ieps*dval(&u) + 7.;
2445
word0(&eps)-= (P-1)*Exp_msk1;
2450
if (dval(&u) > dval(&eps))
2452
if (dval(&u) < -dval(&eps))
2458
/* Use Steele & White method of only generating digits needed. */
2459
dval(&eps)= 0.5/tens[ilim-1] - dval(&eps);
2465
if (dval(&u) < dval(&eps))
2467
if (1. - dval(&u) < dval(&eps))
2477
/* Generate ilim digits, then fix them up. */
2478
dval(&eps)*= tens[ilim-1];
2479
for (i= 1;; i++, dval(&u)*= 10.)
2481
L= (Long)(dval(&u));
2482
if (!(dval(&u)-= L))
2487
if (dval(&u) > 0.5 + dval(&eps))
2489
else if (dval(&u) < 0.5 - dval(&eps))
2491
while (*--s == '0');
2501
dval(&u)= dval(&d2);
2506
/* Do we have a "small" integer? */
2508
if (be >= 0 && k <= Int_max)
2512
if (ndigits < 0 && ilim <= 0)
2515
if (ilim < 0 || dval(&u) <= 5*ds)
2519
for (i= 1;; i++, dval(&u)*= 10.)
2521
L= (Long)(dval(&u) / ds);
2523
#ifdef Check_FLT_ROUNDS
2524
/* If FLT_ROUNDS == 2, L will usually be high by 1 */
2538
#ifdef Honor_FLT_ROUNDS
2543
case 2: goto bump_up;
2547
dval(&u)+= dval(&u);
2548
if (dval(&u) > ds || (dval(&u) == ds && L & 1))
2571
i = denorm ? be + (Bias + (P-1) - 1 + 1) : 1 + P - bbits;
2574
mhi= i2b(1, &alloc);
2576
if (m2 > 0 && s2 > 0)
2578
i= m2 < s2 ? m2 : s2;
2589
mhi= pow5mult(mhi, m5, &alloc);
2590
b1= mult(mhi, b, &alloc);
2595
b= pow5mult(b, j, &alloc);
2598
b= pow5mult(b, b5, &alloc);
2602
S= pow5mult(S, s5, &alloc);
2604
/* Check for special case that d is a normalized power of 2. */
2607
if ((mode < 2 || leftright)
2608
#ifdef Honor_FLT_ROUNDS
2613
if (!word1(&u) && !(word0(&u) & Bndry_mask) &&
2614
word0(&u) & (Exp_mask & ~Exp_msk1)
2617
/* The special case */
2625
Arrange for convenient computation of quotients:
2626
shift left if necessary so divisor has 4 leading 0 bits.
2628
Perhaps we should just compute leading 28 bits of S once
2629
a nd for all and pass them and a shift to quorem, so it
2630
can do shifts and ors to compute the numerator for q.
2632
if ((i= ((s5 ? 32 - hi0bits(S->p.x[S->wds-1]) : 1) + s2) & 0x1f))
2649
b= lshift(b, b2, &alloc);
2651
S= lshift(S, s2, &alloc);
2657
/* we botched the k estimate */
2658
b= multadd(b, 10, 0, &alloc);
2660
mhi= multadd(mhi, 10, 0, &alloc);
2664
if (ilim <= 0 && (mode == 3 || mode == 5))
2666
if (ilim < 0 || cmp(b,S= multadd(S,5,0, &alloc)) <= 0)
2668
/* no digits, fcvt style */
2681
mhi= lshift(mhi, m2, &alloc);
2684
Compute mlo -- check for special case that d is a normalized power of 2.
2690
mhi= Balloc(mhi->k, &alloc);
2692
mhi= lshift(mhi, Log2P, &alloc);
2697
dig= quorem(b,S) + '0';
2698
/* Do we yet have the shortest decimal string that will round to d? */
2700
delta= diff(S, mhi, &alloc);
2701
j1= delta->sign ? 1 : cmp(b, delta);
2702
Bfree(delta, &alloc);
2703
if (j1 == 0 && mode != 1 && !(word1(&u) & 1)
2704
#ifdef Honor_FLT_ROUNDS
2716
if (j < 0 || (j == 0 && mode != 1 && !(word1(&u) & 1)))
2718
if (!b->p.x[0] && b->wds <= 1)
2722
#ifdef Honor_FLT_ROUNDS
2725
case 0: goto accept_dig;
2726
case 2: goto keep_dig;
2728
#endif /*Honor_FLT_ROUNDS*/
2731
b= lshift(b, 1, &alloc);
2733
if ((j1 > 0 || (j1 == 0 && dig & 1))
2743
#ifdef Honor_FLT_ROUNDS
2748
{ /* possible if i == 1 */
2756
#ifdef Honor_FLT_ROUNDS
2762
b= multadd(b, 10, 0, &alloc);
2764
mlo= mhi= multadd(mhi, 10, 0, &alloc);
2767
mlo= multadd(mlo, 10, 0, &alloc);
2768
mhi= multadd(mhi, 10, 0, &alloc);
2775
*s++= dig= quorem(b,S) + '0';
2776
if (!b->p.x[0] && b->wds <= 1)
2782
b= multadd(b, 10, 0, &alloc);
2785
/* Round off last digit */
2787
#ifdef Honor_FLT_ROUNDS
2789
case 0: goto trimzeros;
2790
case 2: goto roundoff;
2793
b= lshift(b, 1, &alloc);
2795
if (j > 0 || (j == 0 && dig & 1))
2809
#ifdef Honor_FLT_ROUNDS
2812
while (*--s == '0');
2819
if (mlo && mlo != mhi)