Update.
[glibc.git] / stdlib / strtod.c
blob9aa120c87a7aa4ff3f57cccba571041aebee1a3f
1 /* Read decimal floating point numbers.
2 This file is part of the GNU C Library.
3 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc.
4 Contributed by Ulrich Drepper <drepper@gnu.ai.mit.edu>, 1995.
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Library General Public License as
8 published by the Free Software Foundation; either version 2 of the
9 License, or (at your option) any later version.
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Library General Public License for more details.
16 You should have received a copy of the GNU Library General Public
17 License along with the GNU C Library; see the file COPYING.LIB. If not,
18 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
21 /* Configuration part. These macros are defined by `strtold.c',
22 `strtof.c', `wcstod.c', `wcstold.c', and `wcstof.c' to produce the
23 `long double' and `float' versions of the reader. */
24 #ifndef FLOAT
25 # define FLOAT double
26 # define FLT DBL
27 # ifdef USE_WIDE_CHAR
28 # define STRTOF wcstod
29 # else
30 # define STRTOF strtod
31 # endif
32 # define MPN2FLOAT __mpn_construct_double
33 # define FLOAT_HUGE_VAL HUGE_VAL
34 #endif
36 #ifdef USE_WIDE_CHAR
37 # include <wctype.h>
38 # include <wchar.h>
39 # define STRING_TYPE wchar_t
40 # define CHAR_TYPE wint_t
41 # define L_(Ch) L##Ch
42 # define ISSPACE(Ch) iswspace (Ch)
43 # define TOLOWER(Ch) towlower (Ch)
44 #else
45 # define STRING_TYPE char
46 # define CHAR_TYPE char
47 # define L_(Ch) Ch
48 # define ISSPACE(Ch) isspace (Ch)
49 # define TOLOWER(Ch) tolower (Ch)
50 #endif
51 /* End of configuration part. */
53 #include <ctype.h>
54 #include <errno.h>
55 #include <float.h>
56 #include "../locale/localeinfo.h"
57 #include <math.h>
58 #include <stdlib.h>
59 #include <string.h>
61 /* The gmp headers need some configuration frobs. */
62 #define HAVE_ALLOCA 1
64 #include "gmp.h"
65 #include "gmp-impl.h"
66 #include <gmp-mparam.h>
67 #include "longlong.h"
68 #include "fpioconst.h"
70 #define NDEBUG 1
71 #include <assert.h>
74 /* Constants we need from float.h; select the set for the FLOAT precision. */
75 #define MANT_DIG PASTE(FLT,_MANT_DIG)
76 #define DIG PASTE(FLT,_DIG)
77 #define MAX_EXP PASTE(FLT,_MAX_EXP)
78 #define MIN_EXP PASTE(FLT,_MIN_EXP)
79 #define MAX_10_EXP PASTE(FLT,_MAX_10_EXP)
80 #define MIN_10_EXP PASTE(FLT,_MIN_10_EXP)
82 /* Extra macros required to get FLT expanded before the pasting. */
83 #define PASTE(a,b) PASTE1(a,b)
84 #define PASTE1(a,b) a##b
86 /* Function to construct a floating point number from an MP integer
87 containing the fraction bits, a base 2 exponent, and a sign flag. */
88 extern FLOAT MPN2FLOAT (mp_srcptr mpn, int exponent, int negative);
90 /* Definitions according to limb size used. */
91 #if BITS_PER_MP_LIMB == 32
92 # define MAX_DIG_PER_LIMB 9
93 # define MAX_FAC_PER_LIMB 1000000000UL
94 #elif BITS_PER_MP_LIMB == 64
95 # define MAX_DIG_PER_LIMB 19
96 # define MAX_FAC_PER_LIMB 10000000000000000000UL
97 #else
98 # error "mp_limb_t size " BITS_PER_MP_LIMB "not accounted for"
99 #endif
102 /* Local data structure. */
103 static const mp_limb_t _tens_in_limb[MAX_DIG_PER_LIMB + 1] =
104 { 0, 10, 100,
105 1000, 10000, 100000,
106 1000000, 10000000, 100000000,
107 1000000000
108 #if BITS_PER_MP_LIMB > 32
109 , 10000000000U, 100000000000U,
110 1000000000000U, 10000000000000U, 100000000000000U,
111 1000000000000000U, 10000000000000000U, 100000000000000000U,
112 1000000000000000000U, 10000000000000000000U
113 #endif
114 #if BITS_PER_MP_LIMB > 64
115 #error "Need to expand tens_in_limb table to" MAX_DIG_PER_LIMB
116 #endif
119 #ifndef howmany
120 #define howmany(x,y) (((x)+((y)-1))/(y))
121 #endif
122 #define SWAP(x, y) ({ typeof(x) _tmp = x; x = y; y = _tmp; })
124 #define NDIG (MAX_10_EXP - MIN_10_EXP + 2 * MANT_DIG)
125 #define RETURN_LIMB_SIZE howmany (MANT_DIG, BITS_PER_MP_LIMB)
127 #define RETURN(val,end) \
128 do { if (endptr != NULL) *endptr = (STRING_TYPE *) (end); \
129 return val; } while (0)
131 /* Maximum size necessary for mpn integers to hold floating point numbers. */
132 #define MPNSIZE (howmany (MAX_EXP + 2 * MANT_DIG, BITS_PER_MP_LIMB) \
133 + 2)
134 /* Declare an mpn integer variable that big. */
135 #define MPN_VAR(name) mp_limb_t name[MPNSIZE]; mp_size_t name##size
136 /* Copy an mpn integer value. */
137 #define MPN_ASSIGN(dst, src) \
138 memcpy (dst, src, (dst##size = src##size) * sizeof (mp_limb_t))
141 /* Return a floating point number of the needed type according to the given
142 multi-precision number after possible rounding. */
143 static inline FLOAT
144 round_and_return (mp_limb_t *retval, int exponent, int negative,
145 mp_limb_t round_limb, mp_size_t round_bit, int more_bits)
147 if (exponent < MIN_EXP - 1)
149 mp_size_t shift = MIN_EXP - 1 - exponent;
151 if (shift > MANT_DIG)
153 __set_errno (EDOM);
154 return 0.0;
157 more_bits |= (round_limb & ((((mp_limb_t) 1) << round_bit) - 1)) != 0;
158 if (shift == MANT_DIG)
159 /* This is a special case to handle the very seldom case where
160 the mantissa will be empty after the shift. */
162 int i;
164 round_limb = retval[RETURN_LIMB_SIZE - 1];
165 round_bit = BITS_PER_MP_LIMB - 1;
166 for (i = 0; i < RETURN_LIMB_SIZE; ++i)
167 more_bits |= retval[i] != 0;
168 MPN_ZERO (retval, RETURN_LIMB_SIZE);
170 else if (shift >= BITS_PER_MP_LIMB)
172 int i;
174 round_limb = retval[(shift - 1) / BITS_PER_MP_LIMB];
175 round_bit = (shift - 1) % BITS_PER_MP_LIMB;
176 for (i = 0; i < (shift - 1) / BITS_PER_MP_LIMB; ++i)
177 more_bits |= retval[i] != 0;
178 more_bits |= ((round_limb & ((((mp_limb_t) 1) << round_bit) - 1))
179 != 0);
181 (void) __mpn_rshift (retval, &retval[shift / BITS_PER_MP_LIMB],
182 RETURN_LIMB_SIZE - (shift / BITS_PER_MP_LIMB),
183 shift % BITS_PER_MP_LIMB);
184 MPN_ZERO (&retval[RETURN_LIMB_SIZE - (shift / BITS_PER_MP_LIMB)],
185 shift / BITS_PER_MP_LIMB);
187 else if (shift > 0)
189 round_limb = retval[0];
190 round_bit = shift - 1;
191 (void) __mpn_rshift (retval, retval, RETURN_LIMB_SIZE, shift);
193 exponent = MIN_EXP - 2;
196 if ((round_limb & (((mp_limb_t) 1) << round_bit)) != 0
197 && (more_bits || (retval[0] & 1) != 0
198 || (round_limb & ((((mp_limb_t) 1) << round_bit) - 1)) != 0))
200 mp_limb_t cy = __mpn_add_1 (retval, retval, RETURN_LIMB_SIZE, 1);
202 if (((MANT_DIG % BITS_PER_MP_LIMB) == 0 && cy) ||
203 ((MANT_DIG % BITS_PER_MP_LIMB) != 0 &&
204 (retval[RETURN_LIMB_SIZE - 1]
205 & (((mp_limb_t) 1) << (MANT_DIG % BITS_PER_MP_LIMB))) != 0))
207 ++exponent;
208 (void) __mpn_rshift (retval, retval, RETURN_LIMB_SIZE, 1);
209 retval[RETURN_LIMB_SIZE - 1]
210 |= ((mp_limb_t) 1) << ((MANT_DIG - 1) % BITS_PER_MP_LIMB);
212 else if (exponent == MIN_EXP - 2
213 && (retval[RETURN_LIMB_SIZE - 1]
214 & (((mp_limb_t) 1) << ((MANT_DIG - 1) % BITS_PER_MP_LIMB)))
215 != 0)
216 /* The number was denormalized but now normalized. */
217 exponent = MIN_EXP - 1;
220 if (exponent > MAX_EXP)
221 return negative ? -FLOAT_HUGE_VAL : FLOAT_HUGE_VAL;
223 return MPN2FLOAT (retval, exponent, negative);
227 /* Read a multi-precision integer starting at STR with exactly DIGCNT digits
228 into N. Return the size of the number limbs in NSIZE at the first
229 character od the string that is not part of the integer as the function
230 value. If the EXPONENT is small enough to be taken as an additional
231 factor for the resulting number (see code) multiply by it. */
232 static inline const STRING_TYPE *
233 str_to_mpn (const STRING_TYPE *str, int digcnt, mp_limb_t *n, mp_size_t *nsize,
234 int *exponent)
236 /* Number of digits for actual limb. */
237 int cnt = 0;
238 mp_limb_t low = 0;
239 mp_limb_t base;
241 *nsize = 0;
242 assert (digcnt > 0);
245 if (cnt == MAX_DIG_PER_LIMB)
247 if (*nsize == 0)
248 n[0] = low;
249 else
251 mp_limb_t cy;
252 cy = __mpn_mul_1 (n, n, *nsize, MAX_FAC_PER_LIMB);
253 cy += __mpn_add_1 (n, n, *nsize, low);
254 if (cy != 0)
255 n[*nsize] = cy;
257 ++(*nsize);
258 cnt = 0;
259 low = 0;
262 /* There might be thousands separators or radix characters in the string.
263 But these all can be ignored because we know the format of the number
264 is correct and we have an exact number of characters to read. */
265 while (*str < L_('0') || *str > L_('9'))
266 ++str;
267 low = low * 10 + *str++ - L_('0');
268 ++cnt;
270 while (--digcnt > 0);
272 if (*exponent > 0 && cnt + *exponent <= MAX_DIG_PER_LIMB)
274 low *= _tens_in_limb[*exponent];
275 base = _tens_in_limb[cnt + *exponent];
276 *exponent = 0;
278 else
279 base = _tens_in_limb[cnt];
281 if (*nsize == 0)
283 n[0] = low;
284 *nsize = 1;
286 else
288 mp_limb_t cy;
289 cy = __mpn_mul_1 (n, n, *nsize, base);
290 cy += __mpn_add_1 (n, n, *nsize, low);
291 if (cy != 0)
292 n[(*nsize)++] = cy;
294 return str;
298 /* Shift {PTR, SIZE} COUNT bits to the left, and fill the vacated bits
299 with the COUNT most significant bits of LIMB.
301 Tege doesn't like this function so I have to write it here myself. :)
302 --drepper */
303 static inline void
304 __mpn_lshift_1 (mp_limb_t *ptr, mp_size_t size, unsigned int count,
305 mp_limb_t limb)
307 if (count == BITS_PER_MP_LIMB)
309 /* Optimize the case of shifting by exactly a word:
310 just copy words, with no actual bit-shifting. */
311 mp_size_t i;
312 for (i = size - 1; i > 0; --i)
313 ptr[i] = ptr[i - 1];
314 ptr[0] = limb;
316 else
318 (void) __mpn_lshift (ptr, ptr, size, count);
319 ptr[0] |= limb >> (BITS_PER_MP_LIMB - count);
324 #define INTERNAL(x) INTERNAL1(x)
325 #define INTERNAL1(x) __##x##_internal
327 /* This file defines a function to check for correct grouping. */
328 #include "grouping.h"
331 /* Return a floating point number with the value of the given string NPTR.
332 Set *ENDPTR to the character after the last used one. If the number is
333 smaller than the smallest representable number, set `errno' to ERANGE and
334 return 0.0. If the number is too big to be represented, set `errno' to
335 ERANGE and return HUGE_VAL with the appropriate sign. */
336 FLOAT
337 INTERNAL (STRTOF) (nptr, endptr, group)
338 const STRING_TYPE *nptr;
339 STRING_TYPE **endptr;
340 int group;
342 int negative; /* The sign of the number. */
343 MPN_VAR (num); /* MP representation of the number. */
344 int exponent; /* Exponent of the number. */
346 /* When we have to compute fractional digits we form a fraction with a
347 second multi-precision number (and we sometimes need a second for
348 temporary results). */
349 MPN_VAR (den);
351 /* Representation for the return value. */
352 mp_limb_t retval[RETURN_LIMB_SIZE];
353 /* Number of bits currently in result value. */
354 int bits;
356 /* Running pointer after the last character processed in the string. */
357 const STRING_TYPE *cp, *tp;
358 /* Start of significant part of the number. */
359 const STRING_TYPE *startp, *start_of_digits;
360 /* Points at the character following the integer and fractional digits. */
361 const STRING_TYPE *expp;
362 /* Total number of digit and number of digits in integer part. */
363 int dig_no, int_no, lead_zero;
364 /* Contains the last character read. */
365 CHAR_TYPE c;
367 /* We should get wint_t from <stddef.h>, but not all GCC versions define it
368 there. So define it ourselves if it remains undefined. */
369 #ifndef _WINT_T
370 typedef unsigned int wint_t;
371 #endif
372 /* The radix character of the current locale. */
373 wint_t decimal;
374 /* The thousands character of the current locale. */
375 wint_t thousands;
376 /* The numeric grouping specification of the current locale,
377 in the format described in <locale.h>. */
378 const char *grouping;
380 assert (sizeof (wchar_t) == sizeof (wint_t));
382 if (group)
384 grouping = _NL_CURRENT (LC_NUMERIC, GROUPING);
385 if (*grouping <= 0 || *grouping == CHAR_MAX)
386 grouping = NULL;
387 else
389 /* Figure out the thousands separator character. */
390 if (mbtowc ((wchar_t *) &thousands,
391 _NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP),
392 strlen (_NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP))) <= 0)
393 thousands = (wint_t) *_NL_CURRENT (LC_NUMERIC, THOUSANDS_SEP);
394 if (thousands == L'\0')
395 grouping = NULL;
398 else
400 grouping = NULL;
401 thousands = L'\0';
404 /* Find the locale's decimal point character. */
405 if (mbtowc ((wchar_t *) &decimal, _NL_CURRENT (LC_NUMERIC, DECIMAL_POINT),
406 strlen (_NL_CURRENT (LC_NUMERIC, DECIMAL_POINT))) <= 0)
407 decimal = (wint_t) *_NL_CURRENT (LC_NUMERIC, DECIMAL_POINT);
408 assert (decimal != L'\0');
410 /* Prepare number representation. */
411 exponent = 0;
412 negative = 0;
413 bits = 0;
415 /* Parse string to get maximal legal prefix. We need the number of
416 characters of the integer part, the fractional part and the exponent. */
417 cp = nptr - 1;
418 /* Ignore leading white space. */
420 c = *++cp;
421 while (ISSPACE (c));
423 /* Get sign of the result. */
424 if (c == L_('-'))
426 negative = 1;
427 c = *++cp;
429 else if (c == L_('+'))
430 c = *++cp;
432 /* Return 0.0 if no legal string is found.
433 No character is used even if a sign was found. */
434 if ((c < L_('0') || c > L_('9'))
435 && ((wint_t) c != decimal || cp[1] < L_('0') || cp[1] > L_('9')))
436 RETURN (0.0, nptr);
438 /* Record the start of the digits, in case we will check their grouping. */
439 start_of_digits = startp = cp;
441 /* Ignore leading zeroes. This helps us to avoid useless computations. */
442 while (c == L_('0') || (thousands != L'\0' && (wint_t) c == thousands))
443 c = *++cp;
445 /* If no other digit but a '0' is found the result is 0.0.
446 Return current read pointer. */
447 if ((c < L_('0') || c > L_('9')) && (wint_t) c != decimal
448 && TOLOWER (c) != L_('e'))
450 tp = correctly_grouped_prefix (start_of_digits, cp, thousands, grouping);
451 /* If TP is at the start of the digits, there was no correctly
452 grouped prefix of the string; so no number found. */
453 RETURN (0.0, tp == start_of_digits ? nptr : tp);
456 /* Remember first significant digit and read following characters until the
457 decimal point, exponent character or any non-FP number character. */
458 startp = cp;
459 dig_no = 0;
460 while (dig_no < NDIG ||
461 /* If parsing grouping info, keep going past useful digits
462 so we can check all the grouping separators. */
463 grouping)
465 if (c >= L_('0') && c <= L_('9'))
466 ++dig_no;
467 else if (thousands == L'\0' || (wint_t) c != thousands)
468 /* Not a digit or separator: end of the integer part. */
469 break;
470 c = *++cp;
473 if (grouping && dig_no > 0)
475 /* Check the grouping of the digits. */
476 tp = correctly_grouped_prefix (start_of_digits, cp, thousands, grouping);
477 if (cp != tp)
479 /* Less than the entire string was correctly grouped. */
481 if (tp == start_of_digits)
482 /* No valid group of numbers at all: no valid number. */
483 RETURN (0.0, nptr);
485 if (tp < startp)
486 /* The number is validly grouped, but consists
487 only of zeroes. The whole value is zero. */
488 RETURN (0.0, tp);
490 /* Recompute DIG_NO so we won't read more digits than
491 are properly grouped. */
492 cp = tp;
493 dig_no = 0;
494 for (tp = startp; tp < cp; ++tp)
495 if (*tp >= L_('0') && *tp <= L_('9'))
496 ++dig_no;
498 int_no = dig_no;
499 lead_zero = 0;
501 goto number_parsed;
505 if (dig_no >= NDIG)
506 /* Too many digits to be representable. Assigning this to EXPONENT
507 allows us to read the full number but return HUGE_VAL after parsing. */
508 exponent = MAX_10_EXP;
510 /* We have the number digits in the integer part. Whether these are all or
511 any is really a fractional digit will be decided later. */
512 int_no = dig_no;
513 lead_zero = int_no == 0 ? -1 : 0;
515 /* Read the fractional digits. A special case are the 'american style'
516 numbers like `16.' i.e. with decimal but without trailing digits. */
517 if ((wint_t) c == decimal)
519 c = *++cp;
520 while (c >= L_('0') && c <= L_('9'))
522 if (c != L_('0') && lead_zero == -1)
523 lead_zero = dig_no - int_no;
524 ++dig_no;
525 c = *++cp;
529 /* Remember start of exponent (if any). */
530 expp = cp;
532 /* Read exponent. */
533 if (TOLOWER (c) == L_('e'))
535 int exp_negative = 0;
537 c = *++cp;
538 if (c == L_('-'))
540 exp_negative = 1;
541 c = *++cp;
543 else if (c == L_('+'))
544 c = *++cp;
546 if (c >= L_('0') && c <= L_('9'))
548 int exp_limit;
550 /* Get the exponent limit. */
551 exp_limit = exp_negative ?
552 -MIN_10_EXP + MANT_DIG - int_no :
553 MAX_10_EXP - int_no + lead_zero;
557 exponent *= 10;
559 if (exponent > exp_limit)
560 /* The exponent is too large/small to represent a valid
561 number. */
563 FLOAT retval;
565 /* We have to take care for special situation: a joker
566 might have written "0.0e100000" which is in fact
567 zero. */
568 if (lead_zero == -1)
569 retval = !negative ? 0.0 : -0.0;
570 else
572 /* Overflow or underflow. */
573 __set_errno (ERANGE);
574 retval = (exp_negative ? 0.0 :
575 negative ? -FLOAT_HUGE_VAL : FLOAT_HUGE_VAL);
578 /* Accept all following digits as part of the exponent. */
580 ++cp;
581 while (*cp >= L_('0') && *cp <= L_('9'));
583 RETURN (retval, cp);
584 /* NOTREACHED */
587 exponent += c - L_('0');
588 c = *++cp;
590 while (c >= L_('0') && c <= L_('9'));
592 if (exp_negative)
593 exponent = -exponent;
595 else
596 cp = expp;
599 /* We don't want to have to work with trailing zeroes after the radix. */
600 if (dig_no > int_no)
602 while (expp[-1] == L_('0'))
604 --expp;
605 --dig_no;
607 assert (dig_no >= int_no);
610 number_parsed:
612 /* The whole string is parsed. Store the address of the next character. */
613 if (endptr)
614 *endptr = (STRING_TYPE *) cp;
616 if (dig_no == 0)
617 return !negative ? 0.0 : -0.0;
619 if (lead_zero)
621 /* Find the decimal point */
622 while ((wint_t) *startp != decimal)
623 ++startp;
624 startp += lead_zero + 1;
625 exponent -= lead_zero;
626 dig_no -= lead_zero;
629 /* Now we have the number of digits in total and the integer digits as well
630 as the exponent and its sign. We can decide whether the read digits are
631 really integer digits or belong to the fractional part; i.e. we normalize
632 123e-2 to 1.23. */
634 register int incr = exponent < 0 ? MAX (-int_no, exponent)
635 : MIN (dig_no - int_no, exponent);
636 int_no += incr;
637 exponent -= incr;
640 if (int_no + exponent > MAX_10_EXP + 1)
642 __set_errno (ERANGE);
643 return negative ? -FLOAT_HUGE_VAL : FLOAT_HUGE_VAL;
646 if (exponent < MIN_10_EXP - (DIG + 1))
648 __set_errno (ERANGE);
649 return 0.0;
652 if (int_no > 0)
654 /* Read the integer part as a multi-precision number to NUM. */
655 startp = str_to_mpn (startp, int_no, num, &numsize, &exponent);
657 if (exponent > 0)
659 /* We now multiply the gained number by the given power of ten. */
660 mp_limb_t *psrc = num;
661 mp_limb_t *pdest = den;
662 int expbit = 1;
663 const struct mp_power *ttab = &_fpioconst_pow10[0];
667 if ((exponent & expbit) != 0)
669 mp_limb_t cy;
670 exponent ^= expbit;
672 /* FIXME: not the whole multiplication has to be done.
673 If we have the needed number of bits we only need the
674 information whether more non-zero bits follow. */
675 if (numsize >= ttab->arraysize - _FPIO_CONST_OFFSET)
676 cy = __mpn_mul (pdest, psrc, numsize,
677 &ttab->array[_FPIO_CONST_OFFSET],
678 ttab->arraysize - _FPIO_CONST_OFFSET);
679 else
680 cy = __mpn_mul (pdest, &ttab->array[_FPIO_CONST_OFFSET],
681 ttab->arraysize - _FPIO_CONST_OFFSET,
682 psrc, numsize);
683 numsize += ttab->arraysize - _FPIO_CONST_OFFSET;
684 if (cy == 0)
685 --numsize;
686 SWAP (psrc, pdest);
688 expbit <<= 1;
689 ++ttab;
691 while (exponent != 0);
693 if (psrc == den)
694 memcpy (num, den, numsize * sizeof (mp_limb_t));
697 /* Determine how many bits of the result we already have. */
698 count_leading_zeros (bits, num[numsize - 1]);
699 bits = numsize * BITS_PER_MP_LIMB - bits;
701 /* Now we know the exponent of the number in base two.
702 Check it against the maximum possible exponent. */
703 if (bits > MAX_EXP)
705 __set_errno (ERANGE);
706 return negative ? -FLOAT_HUGE_VAL : FLOAT_HUGE_VAL;
709 /* We have already the first BITS bits of the result. Together with
710 the information whether more non-zero bits follow this is enough
711 to determine the result. */
712 if (bits > MANT_DIG)
714 int i;
715 const mp_size_t least_idx = (bits - MANT_DIG) / BITS_PER_MP_LIMB;
716 const mp_size_t least_bit = (bits - MANT_DIG) % BITS_PER_MP_LIMB;
717 const mp_size_t round_idx = least_bit == 0 ? least_idx - 1
718 : least_idx;
719 const mp_size_t round_bit = least_bit == 0 ? BITS_PER_MP_LIMB - 1
720 : least_bit - 1;
722 if (least_bit == 0)
723 memcpy (retval, &num[least_idx],
724 RETURN_LIMB_SIZE * sizeof (mp_limb_t));
725 else
727 for (i = least_idx; i < numsize - 1; ++i)
728 retval[i - least_idx] = (num[i] >> least_bit)
729 | (num[i + 1]
730 << (BITS_PER_MP_LIMB - least_bit));
731 if (i - least_idx < RETURN_LIMB_SIZE)
732 retval[RETURN_LIMB_SIZE - 1] = num[i] >> least_bit;
735 /* Check whether any limb beside the ones in RETVAL are non-zero. */
736 for (i = 0; num[i] == 0; ++i)
739 return round_and_return (retval, bits - 1, negative,
740 num[round_idx], round_bit,
741 int_no < dig_no || i < round_idx);
742 /* NOTREACHED */
744 else if (dig_no == int_no)
746 const mp_size_t target_bit = (MANT_DIG - 1) % BITS_PER_MP_LIMB;
747 const mp_size_t is_bit = (bits - 1) % BITS_PER_MP_LIMB;
749 if (target_bit == is_bit)
751 memcpy (&retval[RETURN_LIMB_SIZE - numsize], num,
752 numsize * sizeof (mp_limb_t));
753 /* FIXME: the following loop can be avoided if we assume a
754 maximal MANT_DIG value. */
755 MPN_ZERO (retval, RETURN_LIMB_SIZE - numsize);
757 else if (target_bit > is_bit)
759 (void) __mpn_lshift (&retval[RETURN_LIMB_SIZE - numsize],
760 num, numsize, target_bit - is_bit);
761 /* FIXME: the following loop can be avoided if we assume a
762 maximal MANT_DIG value. */
763 MPN_ZERO (retval, RETURN_LIMB_SIZE - numsize);
765 else
767 mp_limb_t cy;
768 assert (numsize < RETURN_LIMB_SIZE);
770 cy = __mpn_rshift (&retval[RETURN_LIMB_SIZE - numsize],
771 num, numsize, is_bit - target_bit);
772 retval[RETURN_LIMB_SIZE - numsize - 1] = cy;
773 /* FIXME: the following loop can be avoided if we assume a
774 maximal MANT_DIG value. */
775 MPN_ZERO (retval, RETURN_LIMB_SIZE - numsize - 1);
778 return round_and_return (retval, bits - 1, negative, 0, 0, 0);
779 /* NOTREACHED */
782 /* Store the bits we already have. */
783 memcpy (retval, num, numsize * sizeof (mp_limb_t));
784 #if RETURN_LIMB_SIZE > 1
785 if (numsize < RETURN_LIMB_SIZE)
786 retval[numsize] = 0;
787 #endif
790 /* We have to compute at least some of the fractional digits. */
792 /* We construct a fraction and the result of the division gives us
793 the needed digits. The denominator is 1.0 multiplied by the
794 exponent of the lowest digit; i.e. 0.123 gives 123 / 1000 and
795 123e-6 gives 123 / 1000000. */
797 int expbit;
798 int cnt;
799 int neg_exp;
800 int more_bits;
801 mp_limb_t cy;
802 mp_limb_t *psrc = den;
803 mp_limb_t *pdest = num;
804 const struct mp_power *ttab = &_fpioconst_pow10[0];
806 assert (dig_no > int_no && exponent <= 0);
809 /* For the fractional part we need not process too much digits. One
810 decimal digits gives us log_2(10) ~ 3.32 bits. If we now compute
811 ceil(BITS / 3) =: N
812 digits we should have enough bits for the result. The remaining
813 decimal digits give us the information that more bits are following.
814 This can be used while rounding. (One added as a safety margin.) */
815 if (dig_no - int_no > (MANT_DIG - bits + 2) / 3 + 1)
817 dig_no = int_no + (MANT_DIG - bits + 2) / 3 + 1;
818 more_bits = 1;
820 else
821 more_bits = 0;
823 neg_exp = dig_no - int_no - exponent;
825 /* Construct the denominator. */
826 densize = 0;
827 expbit = 1;
830 if ((neg_exp & expbit) != 0)
832 mp_limb_t cy;
833 neg_exp ^= expbit;
835 if (densize == 0)
837 densize = ttab->arraysize - _FPIO_CONST_OFFSET;
838 memcpy (psrc, &ttab->array[_FPIO_CONST_OFFSET],
839 densize * sizeof (mp_limb_t));
841 else
843 cy = __mpn_mul (pdest, &ttab->array[_FPIO_CONST_OFFSET],
844 ttab->arraysize - _FPIO_CONST_OFFSET,
845 psrc, densize);
846 densize += ttab->arraysize - _FPIO_CONST_OFFSET;
847 if (cy == 0)
848 --densize;
849 SWAP (psrc, pdest);
852 expbit <<= 1;
853 ++ttab;
855 while (neg_exp != 0);
857 if (psrc == num)
858 memcpy (den, num, densize * sizeof (mp_limb_t));
860 /* Read the fractional digits from the string. */
861 (void) str_to_mpn (startp, dig_no - int_no, num, &numsize, &exponent);
864 /* We now have to shift both numbers so that the highest bit in the
865 denominator is set. In the same process we copy the numerator to
866 a high place in the array so that the division constructs the wanted
867 digits. This is done by a "quasi fix point" number representation.
869 num: ddddddddddd . 0000000000000000000000
870 |--- m ---|
871 den: ddddddddddd n >= m
872 |--- n ---|
875 count_leading_zeros (cnt, den[densize - 1]);
877 if (cnt > 0)
879 (void) __mpn_lshift (den, den, densize, cnt);
880 cy = __mpn_lshift (num, num, numsize, cnt);
881 if (cy != 0)
882 num[numsize++] = cy;
885 /* Now we are ready for the division. But it is not necessary to
886 do a full multi-precision division because we only need a small
887 number of bits for the result. So we do not use __mpn_divmod
888 here but instead do the division here by hand and stop whenever
889 the needed number of bits is reached. The code itself comes
890 from the GNU MP Library by Torbj\"orn Granlund. */
892 exponent = bits;
894 switch (densize)
896 case 1:
898 mp_limb_t d, n, quot;
899 int used = 0;
901 n = num[0];
902 d = den[0];
903 assert (numsize == 1 && n < d);
907 udiv_qrnnd (quot, n, n, 0, d);
909 #define got_limb \
910 if (bits == 0) \
912 register int cnt; \
913 if (quot == 0) \
914 cnt = BITS_PER_MP_LIMB; \
915 else \
916 count_leading_zeros (cnt, quot); \
917 exponent -= cnt; \
918 if (BITS_PER_MP_LIMB - cnt > MANT_DIG) \
920 used = MANT_DIG + cnt; \
921 retval[0] = quot >> (BITS_PER_MP_LIMB - used); \
922 bits = MANT_DIG + 1; \
924 else \
926 /* Note that we only clear the second element. */ \
927 /* The conditional is determined at compile time. */ \
928 if (RETURN_LIMB_SIZE > 1) \
929 retval[1] = 0; \
930 retval[0] = quot; \
931 bits = -cnt; \
934 else if (bits + BITS_PER_MP_LIMB <= MANT_DIG) \
935 __mpn_lshift_1 (retval, RETURN_LIMB_SIZE, BITS_PER_MP_LIMB, \
936 quot); \
937 else \
939 used = MANT_DIG - bits; \
940 if (used > 0) \
941 __mpn_lshift_1 (retval, RETURN_LIMB_SIZE, used, quot); \
943 bits += BITS_PER_MP_LIMB
945 got_limb;
947 while (bits <= MANT_DIG);
949 return round_and_return (retval, exponent - 1, negative,
950 quot, BITS_PER_MP_LIMB - 1 - used,
951 more_bits || n != 0);
953 case 2:
955 mp_limb_t d0, d1, n0, n1;
956 mp_limb_t quot = 0;
957 int used = 0;
959 d0 = den[0];
960 d1 = den[1];
962 if (numsize < densize)
964 if (num[0] >= d1)
966 /* The numerator of the number occupies fewer bits than
967 the denominator but the one limb is bigger than the
968 high limb of the numerator. */
969 n1 = 0;
970 n0 = num[0];
972 else
974 if (bits <= 0)
975 exponent -= BITS_PER_MP_LIMB;
976 else
978 if (bits + BITS_PER_MP_LIMB <= MANT_DIG)
979 __mpn_lshift_1 (retval, RETURN_LIMB_SIZE,
980 BITS_PER_MP_LIMB, 0);
981 else
983 used = MANT_DIG - bits;
984 if (used > 0)
985 __mpn_lshift_1 (retval, RETURN_LIMB_SIZE, used, 0);
987 bits += BITS_PER_MP_LIMB;
989 n1 = num[0];
990 n0 = 0;
993 else
995 n1 = num[1];
996 n0 = num[0];
999 while (bits <= MANT_DIG)
1001 mp_limb_t r;
1003 if (n1 == d1)
1005 /* QUOT should be either 111..111 or 111..110. We need
1006 special treatment of this rare case as normal division
1007 would give overflow. */
1008 quot = ~(mp_limb_t) 0;
1010 r = n0 + d1;
1011 if (r < d1) /* Carry in the addition? */
1013 add_ssaaaa (n1, n0, r - d0, 0, 0, d0);
1014 goto have_quot;
1016 n1 = d0 - (d0 != 0);
1017 n0 = -d0;
1019 else
1021 udiv_qrnnd (quot, r, n1, n0, d1);
1022 umul_ppmm (n1, n0, d0, quot);
1025 q_test:
1026 if (n1 > r || (n1 == r && n0 > 0))
1028 /* The estimated QUOT was too large. */
1029 --quot;
1031 sub_ddmmss (n1, n0, n1, n0, 0, d0);
1032 r += d1;
1033 if (r >= d1) /* If not carry, test QUOT again. */
1034 goto q_test;
1036 sub_ddmmss (n1, n0, r, 0, n1, n0);
1038 have_quot:
1039 got_limb;
1042 return round_and_return (retval, exponent - 1, negative,
1043 quot, BITS_PER_MP_LIMB - 1 - used,
1044 more_bits || n1 != 0 || n0 != 0);
1046 default:
1048 int i;
1049 mp_limb_t cy, dX, d1, n0, n1;
1050 mp_limb_t quot = 0;
1051 int used = 0;
1053 dX = den[densize - 1];
1054 d1 = den[densize - 2];
1056 /* The division does not work if the upper limb of the two-limb
1057 numerator is greater than the denominator. */
1058 if (__mpn_cmp (num, &den[densize - numsize], numsize) > 0)
1059 num[numsize++] = 0;
1061 if (numsize < densize)
1063 mp_size_t empty = densize - numsize;
1065 if (bits <= 0)
1067 register int i;
1068 for (i = numsize; i > 0; --i)
1069 num[i + empty] = num[i - 1];
1070 MPN_ZERO (num, empty + 1);
1071 exponent -= empty * BITS_PER_MP_LIMB;
1073 else
1075 if (bits + empty * BITS_PER_MP_LIMB <= MANT_DIG)
1077 /* We make a difference here because the compiler
1078 cannot optimize the `else' case that good and
1079 this reflects all currently used FLOAT types
1080 and GMP implementations. */
1081 register int i;
1082 #if RETURN_LIMB_SIZE <= 2
1083 assert (empty == 1);
1084 __mpn_lshift_1 (retval, RETURN_LIMB_SIZE,
1085 BITS_PER_MP_LIMB, 0);
1086 #else
1087 for (i = RETURN_LIMB_SIZE; i > empty; --i)
1088 retval[i] = retval[i - empty];
1089 #endif
1090 #if RETURN_LIMB_SIZE > 1
1091 retval[1] = 0;
1092 #endif
1093 for (i = numsize; i > 0; --i)
1094 num[i + empty] = num[i - 1];
1095 MPN_ZERO (num, empty + 1);
1097 else
1099 used = MANT_DIG - bits;
1100 if (used >= BITS_PER_MP_LIMB)
1102 register int i;
1103 (void) __mpn_lshift (&retval[used
1104 / BITS_PER_MP_LIMB],
1105 retval, RETURN_LIMB_SIZE,
1106 used % BITS_PER_MP_LIMB);
1107 for (i = used / BITS_PER_MP_LIMB; i >= 0; --i)
1108 retval[i] = 0;
1110 else if (used > 0)
1111 __mpn_lshift_1 (retval, RETURN_LIMB_SIZE, used, 0);
1113 bits += empty * BITS_PER_MP_LIMB;
1116 else
1118 int i;
1119 assert (numsize == densize);
1120 for (i = numsize; i > 0; --i)
1121 num[i] = num[i - 1];
1124 den[densize] = 0;
1125 n0 = num[densize];
1127 while (bits <= MANT_DIG)
1129 if (n0 == dX)
1130 /* This might over-estimate QUOT, but it's probably not
1131 worth the extra code here to find out. */
1132 quot = ~(mp_limb_t) 0;
1133 else
1135 mp_limb_t r;
1137 udiv_qrnnd (quot, r, n0, num[densize - 1], dX);
1138 umul_ppmm (n1, n0, d1, quot);
1140 while (n1 > r || (n1 == r && n0 > num[densize - 2]))
1142 --quot;
1143 r += dX;
1144 if (r < dX) /* I.e. "carry in previous addition?" */
1145 break;
1146 n1 -= n0 < d1;
1147 n0 -= d1;
1151 /* Possible optimization: We already have (q * n0) and (1 * n1)
1152 after the calculation of QUOT. Taking advantage of this, we
1153 could make this loop make two iterations less. */
1155 cy = __mpn_submul_1 (num, den, densize + 1, quot);
1157 if (num[densize] != cy)
1159 cy = __mpn_add_n (num, num, den, densize);
1160 assert (cy != 0);
1161 --quot;
1163 n0 = num[densize] = num[densize - 1];
1164 for (i = densize - 1; i > 0; --i)
1165 num[i] = num[i - 1];
1167 got_limb;
1170 for (i = densize; num[i] == 0 && i >= 0; --i)
1172 return round_and_return (retval, exponent - 1, negative,
1173 quot, BITS_PER_MP_LIMB - 1 - used,
1174 more_bits || i >= 0);
1179 /* NOTREACHED */
1182 /* External user entry point. */
1184 FLOAT
1185 #ifdef weak_function
1186 weak_function
1187 #endif
1188 STRTOF (nptr, endptr)
1189 const STRING_TYPE *nptr;
1190 STRING_TYPE **endptr;
1192 return INTERNAL (STRTOF) (nptr, endptr, 0);