3 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4 * 2000, 2001, 2002, 2003, by Larry Wall and others
6 * You may distribute under the terms of either the GNU General Public
7 * License or the Artistic License, as specified in the README file.
12 * "That only makes eleven (plus one mislaid) and not fourteen, unless
13 * wizards count differently to other people."
17 =head1 Numeric functions
21 #define PERL_IN_NUMERIC_C
25 Perl_cast_ulong(pTHX_ NV f)
28 return f < I32_MIN ? (U32) I32_MIN : (U32)(I32) f;
31 if (f < U32_MAX_P1_HALF)
34 return ((U32) f) | (1 + U32_MAX >> 1);
39 return f > 0 ? U32_MAX : 0 /* NaN */;
43 Perl_cast_i32(pTHX_ NV f)
46 return f < I32_MIN ? I32_MIN : (I32) f;
49 if (f < U32_MAX_P1_HALF)
52 return (I32)(((U32) f) | (1 + U32_MAX >> 1));
57 return f > 0 ? (I32)U32_MAX : 0 /* NaN */;
61 Perl_cast_iv(pTHX_ NV f)
64 return f < IV_MIN ? IV_MIN : (IV) f;
67 /* For future flexibility allowing for sizeof(UV) >= sizeof(IV) */
68 if (f < UV_MAX_P1_HALF)
71 return (IV)(((UV) f) | (1 + UV_MAX >> 1));
76 return f > 0 ? (IV)UV_MAX : 0 /* NaN */;
80 Perl_cast_uv(pTHX_ NV f)
83 return f < IV_MIN ? (UV) IV_MIN : (UV)(IV) f;
86 if (f < UV_MAX_P1_HALF)
89 return ((UV) f) | (1 + UV_MAX >> 1);
94 return f > 0 ? UV_MAX : 0 /* NaN */;
97 #if defined(HUGE_VAL) || (defined(USE_LONG_DOUBLE) && defined(HUGE_VALL))
99 * This hack is to force load of "huge" support from libm.a
100 * So it is in perl for (say) POSIX to use.
101 * Needed for SunOS with Sun's 'acc' for example.
106 # if defined(USE_LONG_DOUBLE) && defined(HUGE_VALL)
116 converts a string representing a binary number to numeric form.
118 On entry I<start> and I<*len> give the string to scan, I<*flags> gives
119 conversion flags, and I<result> should be NULL or a pointer to an NV.
120 The scan stops at the end of the string, or the first invalid character.
121 On return I<*len> is set to the length scanned string, and I<*flags> gives
124 If the value is <= UV_MAX it is returned as a UV, the output flags are clear,
125 and nothing is written to I<*result>. If the value is > UV_MAX C<grok_bin>
126 returns UV_MAX, sets C<PERL_SCAN_GREATER_THAN_UV_MAX> in the output flags,
127 and writes the value to I<*result> (or the value is discarded if I<result>
130 The hex number may optionally be prefixed with "0b" or "b" unless
131 C<PERL_SCAN_DISALLOW_PREFIX> is set in I<*flags> on entry. If
132 C<PERL_SCAN_ALLOW_UNDERSCORES> is set in I<*flags> then the binary
133 number may use '_' characters to separate digits.
139 Perl_grok_bin(pTHX_ char *start, STRLEN *len_p, I32 *flags, NV *result) {
140 const char *s = start;
145 const UV max_div_2 = UV_MAX / 2;
146 bool allow_underscores = *flags & PERL_SCAN_ALLOW_UNDERSCORES;
147 bool overflowed = FALSE;
149 if (!(*flags & PERL_SCAN_DISALLOW_PREFIX)) {
150 /* strip off leading b or 0b.
151 for compatibility silently suffer "b" and "0b" as valid binary
158 else if (len >= 2 && s[0] == '0' && s[1] == 'b') {
165 for (; len-- && *s; s++) {
167 if (bit == '0' || bit == '1') {
168 /* Write it in this wonky order with a goto to attempt to get the
169 compiler to make the common case integer-only loop pretty tight.
170 With gcc seems to be much straighter code than old scan_bin. */
173 if (value <= max_div_2) {
174 value = (value << 1) | (bit - '0');
177 /* Bah. We're just overflowed. */
178 if (ckWARN_d(WARN_OVERFLOW))
179 Perl_warner(aTHX_ packWARN(WARN_OVERFLOW),
180 "Integer overflow in binary number");
182 value_nv = (NV) value;
185 /* If an NV has not enough bits in its mantissa to
186 * represent a UV this summing of small low-order numbers
187 * is a waste of time (because the NV cannot preserve
188 * the low-order bits anyway): we could just remember when
189 * did we overflow and in the end just multiply value_nv by the
191 value_nv += (NV)(bit - '0');
194 if (bit == '_' && len && allow_underscores && (bit = s[1])
195 && (bit == '0' || bit == '1'))
201 if (!(*flags & PERL_SCAN_SILENT_ILLDIGIT) && ckWARN(WARN_DIGIT))
202 Perl_warner(aTHX_ packWARN(WARN_DIGIT),
203 "Illegal binary digit '%c' ignored", *s);
207 if ( ( overflowed && value_nv > 4294967295.0)
209 || (!overflowed && value > 0xffffffff )
212 if (ckWARN(WARN_PORTABLE))
213 Perl_warner(aTHX_ packWARN(WARN_PORTABLE),
214 "Binary number > 0b11111111111111111111111111111111 non-portable");
221 *flags = PERL_SCAN_GREATER_THAN_UV_MAX;
230 converts a string representing a hex number to numeric form.
232 On entry I<start> and I<*len> give the string to scan, I<*flags> gives
233 conversion flags, and I<result> should be NULL or a pointer to an NV.
234 The scan stops at the end of the string, or the first non-hex-digit character.
235 On return I<*len> is set to the length scanned string, and I<*flags> gives
238 If the value is <= UV_MAX it is returned as a UV, the output flags are clear,
239 and nothing is written to I<*result>. If the value is > UV_MAX C<grok_hex>
240 returns UV_MAX, sets C<PERL_SCAN_GREATER_THAN_UV_MAX> in the output flags,
241 and writes the value to I<*result> (or the value is discarded if I<result>
244 The hex number may optionally be prefixed with "0x" or "x" unless
245 C<PERL_SCAN_DISALLOW_PREFIX> is set in I<*flags> on entry. If
246 C<PERL_SCAN_ALLOW_UNDERSCORES> is set in I<*flags> then the hex
247 number may use '_' characters to separate digits.
253 Perl_grok_hex(pTHX_ char *start, STRLEN *len_p, I32 *flags, NV *result) {
254 const char *s = start;
259 const UV max_div_16 = UV_MAX / 16;
260 bool allow_underscores = *flags & PERL_SCAN_ALLOW_UNDERSCORES;
261 bool overflowed = FALSE;
262 const char *hexdigit;
264 if (!(*flags & PERL_SCAN_DISALLOW_PREFIX)) {
265 /* strip off leading x or 0x.
266 for compatibility silently suffer "x" and "0x" as valid hex numbers.
273 else if (len >= 2 && s[0] == '0' && s[1] == 'x') {
280 for (; len-- && *s; s++) {
281 hexdigit = strchr((char *) PL_hexdigit, *s);
283 /* Write it in this wonky order with a goto to attempt to get the
284 compiler to make the common case integer-only loop pretty tight.
285 With gcc seems to be much straighter code than old scan_hex. */
288 if (value <= max_div_16) {
289 value = (value << 4) | ((hexdigit - PL_hexdigit) & 15);
292 /* Bah. We're just overflowed. */
293 if (ckWARN_d(WARN_OVERFLOW))
294 Perl_warner(aTHX_ packWARN(WARN_OVERFLOW),
295 "Integer overflow in hexadecimal number");
297 value_nv = (NV) value;
300 /* If an NV has not enough bits in its mantissa to
301 * represent a UV this summing of small low-order numbers
302 * is a waste of time (because the NV cannot preserve
303 * the low-order bits anyway): we could just remember when
304 * did we overflow and in the end just multiply value_nv by the
305 * right amount of 16-tuples. */
306 value_nv += (NV)((hexdigit - PL_hexdigit) & 15);
309 if (*s == '_' && len && allow_underscores && s[1]
310 && (hexdigit = strchr((char *) PL_hexdigit, s[1])))
316 if (!(*flags & PERL_SCAN_SILENT_ILLDIGIT) && ckWARN(WARN_DIGIT))
317 Perl_warner(aTHX_ packWARN(WARN_DIGIT),
318 "Illegal hexadecimal digit '%c' ignored", *s);
322 if ( ( overflowed && value_nv > 4294967295.0)
324 || (!overflowed && value > 0xffffffff )
327 if (ckWARN(WARN_PORTABLE))
328 Perl_warner(aTHX_ packWARN(WARN_PORTABLE),
329 "Hexadecimal number > 0xffffffff non-portable");
336 *flags = PERL_SCAN_GREATER_THAN_UV_MAX;
350 Perl_grok_oct(pTHX_ char *start, STRLEN *len_p, I32 *flags, NV *result) {
351 const char *s = start;
356 const UV max_div_8 = UV_MAX / 8;
357 bool allow_underscores = *flags & PERL_SCAN_ALLOW_UNDERSCORES;
358 bool overflowed = FALSE;
360 for (; len-- && *s; s++) {
361 /* gcc 2.95 optimiser not smart enough to figure that this subtraction
362 out front allows slicker code. */
363 int digit = *s - '0';
364 if (digit >= 0 && digit <= 7) {
365 /* Write it in this wonky order with a goto to attempt to get the
366 compiler to make the common case integer-only loop pretty tight.
370 if (value <= max_div_8) {
371 value = (value << 3) | digit;
374 /* Bah. We're just overflowed. */
375 if (ckWARN_d(WARN_OVERFLOW))
376 Perl_warner(aTHX_ packWARN(WARN_OVERFLOW),
377 "Integer overflow in octal number");
379 value_nv = (NV) value;
382 /* If an NV has not enough bits in its mantissa to
383 * represent a UV this summing of small low-order numbers
384 * is a waste of time (because the NV cannot preserve
385 * the low-order bits anyway): we could just remember when
386 * did we overflow and in the end just multiply value_nv by the
387 * right amount of 8-tuples. */
388 value_nv += (NV)digit;
391 if (digit == ('_' - '0') && len && allow_underscores
392 && (digit = s[1] - '0') && (digit >= 0 && digit <= 7))
398 /* Allow \octal to work the DWIM way (that is, stop scanning
399 * as soon as non-octal characters are seen, complain only iff
400 * someone seems to want to use the digits eight and nine). */
401 if (digit == 8 || digit == 9) {
402 if (!(*flags & PERL_SCAN_SILENT_ILLDIGIT) && ckWARN(WARN_DIGIT))
403 Perl_warner(aTHX_ packWARN(WARN_DIGIT),
404 "Illegal octal digit '%c' ignored", *s);
409 if ( ( overflowed && value_nv > 4294967295.0)
411 || (!overflowed && value > 0xffffffff )
414 if (ckWARN(WARN_PORTABLE))
415 Perl_warner(aTHX_ packWARN(WARN_PORTABLE),
416 "Octal number > 037777777777 non-portable");
423 *flags = PERL_SCAN_GREATER_THAN_UV_MAX;
432 For backwards compatibility. Use C<grok_bin> instead.
436 For backwards compatibility. Use C<grok_hex> instead.
440 For backwards compatibility. Use C<grok_oct> instead.
446 Perl_scan_bin(pTHX_ char *start, STRLEN len, STRLEN *retlen)
449 I32 flags = *retlen ? PERL_SCAN_ALLOW_UNDERSCORES : 0;
450 UV ruv = grok_bin (start, &len, &flags, &rnv);
453 return (flags & PERL_SCAN_GREATER_THAN_UV_MAX) ? rnv : (NV)ruv;
457 Perl_scan_oct(pTHX_ char *start, STRLEN len, STRLEN *retlen)
460 I32 flags = *retlen ? PERL_SCAN_ALLOW_UNDERSCORES : 0;
461 UV ruv = grok_oct (start, &len, &flags, &rnv);
464 return (flags & PERL_SCAN_GREATER_THAN_UV_MAX) ? rnv : (NV)ruv;
468 Perl_scan_hex(pTHX_ char *start, STRLEN len, STRLEN *retlen)
471 I32 flags = *retlen ? PERL_SCAN_ALLOW_UNDERSCORES : 0;
472 UV ruv = grok_hex (start, &len, &flags, &rnv);
475 return (flags & PERL_SCAN_GREATER_THAN_UV_MAX) ? rnv : (NV)ruv;
479 =for apidoc grok_numeric_radix
481 Scan and skip for a numeric decimal separator (radix).
486 Perl_grok_numeric_radix(pTHX_ const char **sp, const char *send)
488 #ifdef USE_LOCALE_NUMERIC
489 if (PL_numeric_radix_sv && IN_LOCALE) {
491 char* radix = SvPV(PL_numeric_radix_sv, len);
492 if (*sp + len <= send && memEQ(*sp, radix, len)) {
497 /* always try "." if numeric radix didn't match because
498 * we may have data from different locales mixed */
500 if (*sp < send && **sp == '.') {
508 =for apidoc grok_number
510 Recognise (or not) a number. The type of the number is returned
511 (0 if unrecognised), otherwise it is a bit-ORed combination of
512 IS_NUMBER_IN_UV, IS_NUMBER_GREATER_THAN_UV_MAX, IS_NUMBER_NOT_INT,
513 IS_NUMBER_NEG, IS_NUMBER_INFINITY, IS_NUMBER_NAN (defined in perl.h).
515 If the value of the number can fit an in UV, it is returned in the *valuep
516 IS_NUMBER_IN_UV will be set to indicate that *valuep is valid, IS_NUMBER_IN_UV
517 will never be set unless *valuep is valid, but *valuep may have been assigned
518 to during processing even though IS_NUMBER_IN_UV is not set on return.
519 If valuep is NULL, IS_NUMBER_IN_UV will be set for the same cases as when
520 valuep is non-NULL, but no actual assignment (or SEGV) will occur.
522 IS_NUMBER_NOT_INT will be set with IS_NUMBER_IN_UV if trailing decimals were
523 seen (in which case *valuep gives the true value truncated to an integer), and
524 IS_NUMBER_NEG if the number is negative (in which case *valuep holds the
525 absolute value). IS_NUMBER_IN_UV is not set if e notation was used or the
526 number is larger than a UV.
531 Perl_grok_number(pTHX_ const char *pv, STRLEN len, UV *valuep)
534 const char *send = pv + len;
535 const UV max_div_10 = UV_MAX / 10;
536 const char max_mod_10 = UV_MAX % 10;
541 while (s < send && isSPACE(*s))
545 } else if (*s == '-') {
547 numtype = IS_NUMBER_NEG;
555 /* next must be digit or the radix separator or beginning of infinity */
557 /* UVs are at least 32 bits, so the first 9 decimal digits cannot
560 /* This construction seems to be more optimiser friendly.
561 (without it gcc does the isDIGIT test and the *s - '0' separately)
562 With it gcc on arm is managing 6 instructions (6 cycles) per digit.
563 In theory the optimiser could deduce how far to unroll the loop
564 before checking for overflow. */
566 int digit = *s - '0';
567 if (digit >= 0 && digit <= 9) {
568 value = value * 10 + digit;
571 if (digit >= 0 && digit <= 9) {
572 value = value * 10 + digit;
575 if (digit >= 0 && digit <= 9) {
576 value = value * 10 + digit;
579 if (digit >= 0 && digit <= 9) {
580 value = value * 10 + digit;
583 if (digit >= 0 && digit <= 9) {
584 value = value * 10 + digit;
587 if (digit >= 0 && digit <= 9) {
588 value = value * 10 + digit;
591 if (digit >= 0 && digit <= 9) {
592 value = value * 10 + digit;
595 if (digit >= 0 && digit <= 9) {
596 value = value * 10 + digit;
598 /* Now got 9 digits, so need to check
599 each time for overflow. */
601 while (digit >= 0 && digit <= 9
602 && (value < max_div_10
603 || (value == max_div_10
604 && digit <= max_mod_10))) {
605 value = value * 10 + digit;
611 if (digit >= 0 && digit <= 9
614 skip the remaining digits, don't
615 worry about setting *valuep. */
618 } while (s < send && isDIGIT(*s));
620 IS_NUMBER_GREATER_THAN_UV_MAX;
640 numtype |= IS_NUMBER_IN_UV;
645 if (GROK_NUMERIC_RADIX(&s, send)) {
646 numtype |= IS_NUMBER_NOT_INT;
647 while (s < send && isDIGIT(*s)) /* optional digits after the radix */
651 else if (GROK_NUMERIC_RADIX(&s, send)) {
652 numtype |= IS_NUMBER_NOT_INT | IS_NUMBER_IN_UV; /* valuep assigned below */
653 /* no digits before the radix means we need digits after it */
654 if (s < send && isDIGIT(*s)) {
657 } while (s < send && isDIGIT(*s));
659 /* integer approximation is valid - it's 0. */
665 } else if (*s == 'I' || *s == 'i') {
666 s++; if (s == send || (*s != 'N' && *s != 'n')) return 0;
667 s++; if (s == send || (*s != 'F' && *s != 'f')) return 0;
668 s++; if (s < send && (*s == 'I' || *s == 'i')) {
669 s++; if (s == send || (*s != 'N' && *s != 'n')) return 0;
670 s++; if (s == send || (*s != 'I' && *s != 'i')) return 0;
671 s++; if (s == send || (*s != 'T' && *s != 't')) return 0;
672 s++; if (s == send || (*s != 'Y' && *s != 'y')) return 0;
676 } else if (*s == 'N' || *s == 'n') {
677 /* XXX TODO: There are signaling NaNs and quiet NaNs. */
678 s++; if (s == send || (*s != 'A' && *s != 'a')) return 0;
679 s++; if (s == send || (*s != 'N' && *s != 'n')) return 0;
686 numtype &= IS_NUMBER_NEG; /* Keep track of sign */
687 numtype |= IS_NUMBER_INFINITY | IS_NUMBER_NOT_INT;
689 numtype &= IS_NUMBER_NEG; /* Keep track of sign */
690 numtype |= IS_NUMBER_NAN | IS_NUMBER_NOT_INT;
691 } else if (s < send) {
692 /* we can have an optional exponent part */
693 if (*s == 'e' || *s == 'E') {
694 /* The only flag we keep is sign. Blow away any "it's UV" */
695 numtype &= IS_NUMBER_NEG;
696 numtype |= IS_NUMBER_NOT_INT;
698 if (s < send && (*s == '-' || *s == '+'))
700 if (s < send && isDIGIT(*s)) {
703 } while (s < send && isDIGIT(*s));
709 while (s < send && isSPACE(*s))
713 if (len == 10 && memEQ(pv, "0 but true", 10)) {
716 return IS_NUMBER_IN_UV;
722 S_mulexp10(NV value, I32 exponent)
734 /* On OpenVMS VAX we by default use the D_FLOAT double format,
735 * and that format does not have *easy* capabilities [1] for
736 * overflowing doubles 'silently' as IEEE fp does. We also need
737 * to support G_FLOAT on both VAX and Alpha, and though the exponent
738 * range is much larger than D_FLOAT it still doesn't do silent
739 * overflow. Therefore we need to detect early whether we would
740 * overflow (this is the behaviour of the native string-to-float
741 * conversion routines, and therefore of native applications, too).
743 * [1] Trying to establish a condition handler to trap floating point
744 * exceptions is not a good idea. */
746 /* In UNICOS and in certain Cray models (such as T90) there is no
747 * IEEE fp, and no way at all from C to catch fp overflows gracefully.
748 * There is something you can do if you are willing to use some
749 * inline assembler: the instruction is called DFI-- but that will
750 * disable *all* floating point interrupts, a little bit too large
751 * a hammer. Therefore we need to catch potential overflows before
754 #if ((defined(VMS) && !defined(__IEEE_FP)) || defined(_UNICOS)) && defined(NV_MAX_10_EXP)
756 NV exp_v = log10(value);
757 if (exponent >= NV_MAX_10_EXP || exponent + exp_v >= NV_MAX_10_EXP)
760 if (-(exponent + exp_v) >= NV_MAX_10_EXP)
762 while (-exponent >= NV_MAX_10_EXP) {
763 /* combination does not overflow, but 10^(-exponent) does */
773 exponent = -exponent;
775 for (bit = 1; exponent; bit <<= 1) {
776 if (exponent & bit) {
779 /* Floating point exceptions are supposed to be turned off,
780 * but if we're obviously done, don't risk another iteration.
782 if (exponent == 0) break;
786 return negative ? value / result : value * result;
790 Perl_my_atof(pTHX_ const char* s)
793 #ifdef USE_LOCALE_NUMERIC
794 if (PL_numeric_local && IN_LOCALE) {
797 /* Scan the number twice; once using locale and once without;
798 * choose the larger result (in absolute value). */
800 SET_NUMERIC_STANDARD();
803 if ((y < 0.0 && y < x) || (y > 0.0 && y > x))
815 Perl_my_atof2(pTHX_ const char* orig, NV* value)
817 NV result[3] = {0.0, 0.0, 0.0};
818 char* s = (char*)orig;
820 UV accumulator[2] = {0,0}; /* before/after dp */
822 char* send = s + strlen(orig) - 1;
824 I32 exp_adjust[2] = {0,0};
825 I32 exp_acc[2] = {-1, -1};
826 /* the current exponent adjust for the accumulators */
831 I32 sig_digits = 0; /* noof significant digits seen so far */
833 /* There is no point in processing more significant digits
834 * than the NV can hold. Note that NV_DIG is a lower-bound value,
835 * while we need an upper-bound value. We add 2 to account for this;
836 * since it will have been conservative on both the first and last digit.
837 * For example a 32-bit mantissa with an exponent of 4 would have
838 * exact values in the set
846 * where for the purposes of calculating NV_DIG we would have to discount
847 * both the first and last digit, since neither can hold all values from
848 * 0..9; but for calculating the value we must examine those two digits.
850 #define MAX_SIG_DIGITS (NV_DIG+2)
852 /* the max number we can accumulate in a UV, and still safely do 10*N+9 */
853 #define MAX_ACCUMULATE ( (UV) ((UV_MAX - 9)/10))
855 /* leading whitespace */
868 /* we accumulate digits into an integer; when this becomes too
869 * large, we add the total to NV and start again */
879 /* don't start counting until we see the first significant
880 * digit, eg the 5 in 0.00005... */
881 if (!sig_digits && digit == 0)
884 if (++sig_digits > MAX_SIG_DIGITS) {
885 /* limits of precision reached */
887 ++accumulator[seen_dp];
888 } else if (digit == 5) {
889 if (old_digit % 2) { /* round to even - Allen */
890 ++accumulator[seen_dp];
898 /* skip remaining digits */
899 while (isDIGIT(*s)) {
905 /* warn of loss of precision? */
908 if (accumulator[seen_dp] > MAX_ACCUMULATE) {
909 /* add accumulator to result and start again */
910 result[seen_dp] = S_mulexp10(result[seen_dp],
912 + (NV)accumulator[seen_dp];
913 accumulator[seen_dp] = 0;
914 exp_acc[seen_dp] = 0;
916 accumulator[seen_dp] = accumulator[seen_dp] * 10 + digit;
920 else if (!seen_dp && GROK_NUMERIC_RADIX((const char **)&s, send)) {
922 if (sig_digits > MAX_SIG_DIGITS) {
924 while (isDIGIT(*s)) {
935 result[0] = S_mulexp10(result[0], exp_acc[0]) + (NV)accumulator[0];
937 result[1] = S_mulexp10(result[1], exp_acc[1]) + (NV)accumulator[1];
940 if (seen_digit && (*s == 'e' || *s == 'E')) {
941 bool expnegative = 0;
952 exponent = exponent * 10 + (*s++ - '0');
954 exponent = -exponent;
959 /* now apply the exponent */
962 result[2] = S_mulexp10(result[0],exponent+exp_adjust[0])
963 + S_mulexp10(result[1],exponent-exp_adjust[1]);
965 result[2] = S_mulexp10(result[0],exponent+exp_adjust[0]);
968 /* now apply the sign */
970 result[2] = -result[2];
971 #endif /* USE_PERL_ATOF */
976 #if ! defined(HAS_MODFL) && defined(HAS_AINTL) && defined(HAS_COPYSIGNL)
978 Perl_my_modfl(long double x, long double *ip)
981 return (x == *ip ? copysignl(0.0L, x) : x - *ip);
985 #if ! defined(HAS_FREXPL) && defined(HAS_ILOGBL) && defined(HAS_SCALBNL)
987 Perl_my_frexpl(long double x, int *e) {
988 *e = x == 0.0L ? 0 : ilogbl(x) + 1;
989 return (scalbnl(x, -*e));