1 /* $NetBSD: dtoa.c,v 1.10 2012/05/16 17:48:59 alnsn Exp $ */
3 /****************************************************************
5 The author of this software is David M. Gay.
7 Copyright (C) 1998, 1999 by Lucent Technologies
10 Permission to use, copy, modify, and distribute this software and
11 its documentation for any purpose and without fee is hereby
12 granted, provided that the above copyright notice appear in all
13 copies and that both that the copyright notice and this
14 permission notice and warranty disclaimer appear in supporting
15 documentation, and that the name of Lucent or any of its entities
16 not be used in advertising or publicity pertaining to
17 distribution of the software without specific, written prior
20 LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
21 INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
22 IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
23 SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
24 WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
25 IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
26 ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
29 ****************************************************************/
31 /* Please send bug reports to David M. Gay (dmg at acm dot org,
32 * with " at " changed at "@" and " dot " changed to "."). */
36 /* dtoa for IEEE arithmetic (dmg): convert double to ASCII string.
38 * Inspired by "How to Print Floating-Point Numbers Accurately" by
39 * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 112-126].
42 * 1. Rather than iterating, we use a simple numeric overestimate
43 * to determine k = floor(log10(d)). We scale relevant
44 * quantities using O(log2(k)) rather than O(k) multiplications.
45 * 2. For some modes > 2 (corresponding to ecvt and fcvt), we don't
46 * try to generate digits strictly left to right. Instead, we
47 * compute with fewer bits and propagate the carry if necessary
48 * when rounding the final digit up. This is often faster.
49 * 3. Under the assumption that input will be rounded nearest,
50 * mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22.
51 * That is, we allow equality in stopping tests when the
52 * round-nearest rule will give the same floating-point value
53 * as would satisfaction of the stopping test with strict
55 * 4. We remove common factors of powers of 2 from relevant
57 * 5. When converting floating-point integers less than 1e16,
58 * we use floating-point arithmetic rather than resorting
59 * to multiple-precision integers.
60 * 6. When asked to produce fewer than 15 digits, we first try
61 * to get by with floating-point arithmetic; we resort to
62 * multiple-precision integer arithmetic only if we cannot
63 * guarantee that the floating-point calculation has given
64 * the correctly rounded result. For k requested digits and
65 * "uniformly" distributed input, the probability is
66 * something like 10^(k-15) that we must resort to the Long
70 #ifdef Honor_FLT_ROUNDS
71 #undef Check_FLT_ROUNDS
72 #define Check_FLT_ROUNDS
74 #define Rounding Flt_Rounds
80 (d0
, mode
, ndigits
, decpt
, sign
, rve
)
81 double d0
; int mode
, ndigits
, *decpt
, *sign
; char **rve
;
83 (double d0
, int mode
, int ndigits
, int *decpt
, int *sign
, char **rve
)
86 /* Arguments ndigits, decpt, sign are similar to those
87 of ecvt and fcvt; trailing zeros are suppressed from
88 the returned string. If not null, *rve is set to point
89 to the end of the return value. If d is +-Infinity or NaN,
90 then *decpt is set to 9999.
93 0 ==> shortest string that yields d when read in
94 and rounded to nearest.
95 1 ==> like 0, but with Steele & White stopping rule;
96 e.g. with IEEE P754 arithmetic , mode 0 gives
97 1e23 whereas mode 1 gives 9.999999999999999e22.
98 2 ==> max(1,ndigits) significant digits. This gives a
99 return value similar to that of ecvt, except
100 that trailing zeros are suppressed.
101 3 ==> through ndigits past the decimal point. This
102 gives a return value similar to that from fcvt,
103 except that trailing zeros are suppressed, and
104 ndigits can be negative.
105 4,5 ==> similar to 2 and 3, respectively, but (in
106 round-nearest mode) with the tests of mode 0 to
107 possibly return a shorter string that rounds to d.
108 With IEEE arithmetic and compilation with
109 -DHonor_FLT_ROUNDS, modes 4 and 5 behave the same
110 as modes 2 and 3 when FLT_ROUNDS != 1.
111 6-9 ==> Debugging modes similar to mode - 4: don't try
112 fast floating-point estimate (if applicable).
114 Values of mode other than 0-9 are treated as mode 0.
116 Sufficient space is allocated to the return value
117 to hold the suppressed trailing zeros.
120 int bbits
, b2
, b5
, be
, dig
, i
, ieps
, ilim0
,
121 j
, jj1
, k
, k0
, k_check
, leftright
, m2
, m5
, s2
, s5
,
122 spec_case
, try_quick
;
123 int ilim
= 0, ilim1
= 0; /* pacify gcc */
125 #ifndef Sudden_Underflow
129 Bigint
*b
, *b1
, *delta
, *mhi
, *S
;
130 Bigint
*mlo
= NULL
; /* pacify gcc */
135 int inexact
, oldinexact
;
137 #ifdef Honor_FLT_ROUNDS /*{*/
139 #ifdef Trust_FLT_ROUNDS /*{{ only define this if FLT_ROUNDS really works! */
140 Rounding
= Flt_Rounds
;
143 switch(fegetround()) {
144 case FE_TOWARDZERO
: Rounding
= 0; break;
145 case FE_UPWARD
: Rounding
= 2; break;
146 case FE_DOWNWARD
: Rounding
= 3;
151 #ifndef MULTIPLE_THREADS
153 freedtoa(dtoa_result
);
158 if (word0(&d
) & Sign_bit
) {
159 /* set sign for everything, including 0's and NaNs */
161 word0(&d
) &= ~Sign_bit
; /* clear sign bit */
166 #if defined(IEEE_Arith) + defined(VAX)
168 if ((word0(&d
) & Exp_mask
) == Exp_mask
)
170 if (word0(&d
) == 0x8000)
173 /* Infinity or NaN */
176 if (!word1(&d
) && !(word0(&d
) & 0xfffff))
177 return nrv_alloc("Infinity", rve
, 8);
179 return nrv_alloc("NaN", rve
, 3);
183 dval(&d
) += 0; /* normalize */
187 return nrv_alloc("0", rve
, 1);
191 try_quick
= oldinexact
= get_inexact();
194 #ifdef Honor_FLT_ROUNDS
197 Rounding
= Rounding
== 2 ? 0 : 2;
204 b
= d2b(dval(&d
), &be
, &bbits
);
207 #ifdef Sudden_Underflow
208 i
= (int)(word0(&d
) >> Exp_shift1
& (Exp_mask
>>Exp_shift1
));
210 if (( i
= (int)(word0(&d
) >> Exp_shift1
& (Exp_mask
>>Exp_shift1
)) )!=0) {
212 dval(&d2
) = dval(&d
);
213 word0(&d2
) &= Frac_mask1
;
214 word0(&d2
) |= Exp_11
;
216 if (( j
= 11 - hi0bits(word0(&d2
) & Frac_mask
) )!=0)
220 /* log(x) ~=~ log(1.5) + (x-1.5)/1.5
221 * log10(x) = log(x) / log(10)
222 * ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10))
223 * log10(&d) = (i-Bias)*log(2)/log(10) + log10(&d2)
225 * This suggests computing an approximation k to log10(&d) by
227 * k = (i - Bias)*0.301029995663981
228 * + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 );
230 * We want k to be too large rather than too small.
231 * The error in the first-order Taylor series approximation
232 * is in our favor, so we just round up the constant enough
233 * to compensate for any error in the multiplication of
234 * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077,
235 * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14,
236 * adding 1e-13 to the constant term more than suffices.
237 * Hence we adjust the constant term to 0.1760912590558.
238 * (We could get a more accurate k by invoking log10,
239 * but this is probably not worthwhile.)
247 #ifndef Sudden_Underflow
251 /* d is denormalized */
253 i
= bbits
+ be
+ (Bias
+ (P
-1) - 1);
254 x
= i
> 32 ? word0(&d
) << (64 - i
) | word1(&d
) >> (i
- 32)
255 : word1(&d
) << (32 - i
);
257 word0(&d2
) -= 31*Exp_msk1
; /* adjust exponent */
258 i
-= (Bias
+ (P
-1) - 1) + 1;
262 ds
= (dval(&d2
)-1.5)*0.289529654602168 + 0.1760912590558 + i
*0.301029995663981;
264 if (ds
< 0. && ds
!= k
)
265 k
--; /* want k = floor(ds) */
267 if (k
>= 0 && k
<= Ten_pmax
) {
268 if (dval(&d
) < tens
[k
])
291 if (mode
< 0 || mode
> 9)
295 #ifdef Check_FLT_ROUNDS
296 try_quick
= Rounding
== 1;
300 #endif /*SET_INEXACT*/
307 ilim
= ilim1
= -1; /* Values for cases 0 and 1; done here to */
308 /* silence erroneous "gcc -Wall" warning. */
321 ilim
= ilim1
= i
= ndigits
;
333 s
= s0
= rv_alloc((size_t)i
);
337 #ifdef Honor_FLT_ROUNDS
338 if (mode
> 1 && Rounding
!= 1)
342 if (ilim
>= 0 && ilim
<= Quick_max
&& try_quick
) {
344 /* Try to get by with floating-point arithmetic. */
347 dval(&d2
) = dval(&d
);
350 ieps
= 2; /* conservative */
353 j
= (unsigned int)k
>> 4;
355 /* prevent overflows */
357 dval(&d
) /= bigtens
[n_bigtens
-1];
360 for(; j
; j
= (unsigned int)j
>> 1, i
++)
367 else if (( jj1
= -k
)!=0) {
368 dval(&d
) *= tens
[jj1
& 0xf];
369 for(j
= jj1
>> 4; j
; j
>>= 1, i
++)
372 dval(&d
) *= bigtens
[i
];
375 if (k_check
&& dval(&d
) < 1. && ilim
> 0) {
383 dval(&eps
) = ieps
*dval(&d
) + 7.;
384 word0(&eps
) -= (P
-1)*Exp_msk1
;
388 if (dval(&d
) > dval(&eps
))
390 if (dval(&d
) < -dval(&eps
))
396 /* Use Steele & White method of only
397 * generating digits needed.
399 dval(&eps
) = 0.5/tens
[ilim
-1] - dval(&eps
);
404 if (dval(&d
) < dval(&eps
))
406 if (1. - dval(&d
) < dval(&eps
))
416 /* Generate ilim digits, then fix them up. */
417 dval(&eps
) *= tens
[ilim
-1];
418 for(i
= 1;; i
++, dval(&d
) *= 10.) {
419 L
= (Long
)(dval(&d
));
420 if (!(dval(&d
) -= L
))
424 if (dval(&d
) > 0.5 + dval(&eps
))
426 else if (dval(&d
) < 0.5 - dval(&eps
)) {
439 dval(&d
) = dval(&d2
);
444 /* Do we have a "small" integer? */
446 if (be
>= 0 && k
<= Int_max
) {
449 if (ndigits
< 0 && ilim
<= 0) {
451 if (ilim
< 0 || dval(&d
) <= 5*ds
)
455 for(i
= 1;; i
++, dval(&d
) *= 10.) {
456 L
= (Long
)(dval(&d
) / ds
);
458 #ifdef Check_FLT_ROUNDS
459 /* If FLT_ROUNDS == 2, L will usually be high by 1 */
473 #ifdef Honor_FLT_ROUNDS
477 case 2: goto bump_up
;
480 dval(&d
) += dval(&d
);
484 if (dval(&d
) > ds
|| (dval(&d
) == ds
&& L
& 1))
507 #ifndef Sudden_Underflow
508 denorm
? be
+ (Bias
+ (P
-1) - 1 + 1) :
511 1 + 4*P
- 3 - bbits
+ ((bbits
+ be
- 1) & 3);
521 if (m2
> 0 && s2
> 0) {
522 i
= m2
< s2
? m2
: s2
;
530 mhi
= pow5mult(mhi
, m5
);
539 if (( j
= b5
- m5
)!=0) {
560 /* Check for special case that d is a normalized power of 2. */
563 if ((mode
< 2 || leftright
)
564 #ifdef Honor_FLT_ROUNDS
568 if (!word1(&d
) && !(word0(&d
) & Bndry_mask
)
569 #ifndef Sudden_Underflow
570 && word0(&d
) & (Exp_mask
& ~Exp_msk1
)
573 /* The special case */
580 /* Arrange for convenient computation of quotients:
581 * shift left if necessary so divisor has 4 leading 0 bits.
583 * Perhaps we should just compute leading 28 bits of S once
584 * and for all and pass them and a shift to quorem, so it
585 * can do shifts and ors to compute the numerator for q.
588 if (( i
= ((s5
? 32 - hi0bits(S
->x
[S
->wds
-1]) : 1) + s2
) & 0x1f )!=0)
591 if (( i
= ((s5
? 32 - hi0bits(S
->x
[S
->wds
-1]) : 1) + s2
) & 0xf )!=0)
619 b
= multadd(b
, 10, 0); /* we botched the k estimate */
623 mhi
= multadd(mhi
, 10, 0);
630 if (ilim
<= 0 && (mode
== 3 || mode
== 5)) {
631 if (ilim
< 0 || cmp(b
,S
= multadd(S
,5,0)) <= 0) {
632 /* no digits, fcvt style */
644 mhi
= lshift(mhi
, m2
);
649 /* Compute mlo -- check for special case
650 * that d is a normalized power of 2.
655 mhi
= Balloc(mhi
->k
);
659 mhi
= lshift(mhi
, Log2P
);
665 dig
= quorem(b
,S
) + '0';
666 /* Do we yet have the shortest decimal string
667 * that will round to d?
670 delta
= diff(S
, mhi
);
673 jj1
= delta
->sign
? 1 : cmp(b
, delta
);
676 if (jj1
== 0 && mode
!= 1 && !(word1(&d
) & 1)
677 #ifdef Honor_FLT_ROUNDS
686 else if (!b
->x
[0] && b
->wds
<= 1)
693 if (j
< 0 || (j
== 0 && mode
!= 1
698 if (!b
->x
[0] && b
->wds
<= 1) {
704 #ifdef Honor_FLT_ROUNDS
707 case 0: goto accept_dig
;
708 case 2: goto keep_dig
;
710 #endif /*Honor_FLT_ROUNDS*/
719 if ((jj1
> 0 || (jj1
== 0 && dig
& 1))
729 #ifdef Honor_FLT_ROUNDS
733 if (dig
== '9') { /* possible if i == 1 */
741 #ifdef Honor_FLT_ROUNDS
747 b
= multadd(b
, 10, 0);
751 mlo
= mhi
= multadd(mhi
, 10, 0);
756 mlo
= multadd(mlo
, 10, 0);
759 mhi
= multadd(mhi
, 10, 0);
767 *s
++ = dig
= quorem(b
,S
) + '0';
768 if (!b
->x
[0] && b
->wds
<= 1) {
776 b
= multadd(b
, 10, 0);
781 /* Round off last digit */
783 #ifdef Honor_FLT_ROUNDS
785 case 0: goto trimzeros
;
786 case 2: goto roundoff
;
794 if (j
> 0 || (j
== 0 && dig
& 1))
807 #ifdef Honor_FLT_ROUNDS
816 if (mlo
&& mlo
!= mhi
)
824 word0(&d
) = Exp_1
+ (70 << Exp_shift
);
829 else if (!oldinexact
)
833 if (s
== s0
) { /* don't return empty string */