1 /* Decimal Number module for the decNumber C Library
2 Copyright (C) 2005 Free Software Foundation, Inc.
3 Contributed by IBM Corporation. Author Mike Cowlishaw.
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING. If not, write to the Free
19 Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
22 /* ------------------------------------------------------------------ */
23 /* This module comprises the routines for Standard Decimal Arithmetic */
24 /* as defined in the specification which may be found on the */
25 /* http://www2.hursley.ibm.com/decimal web pages. It implements both */
26 /* the full ('extended') arithmetic and the simpler ('subset') */
31 /* 1. This code is ANSI C89 except: */
33 /* a) Line comments (double forward slash) are used. (Most C */
34 /* compilers accept these. If yours does not, a simple script */
35 /* can be used to convert them to ANSI C comments.) */
37 /* b) Types from C99 stdint.h are used. If you do not have this */
38 /* header file, see the User's Guide section of the decNumber */
39 /* documentation; this lists the necessary definitions. */
41 /* c) If DECDPUN>4, non-ANSI 64-bit 'long long' types are used. */
42 /* To avoid these, set DECDPUN <= 4 (see documentation). */
44 /* 2. The decNumber format which this library uses is optimized for */
45 /* efficient processing of relatively short numbers; in particular */
46 /* it allows the use of fixed sized structures and minimizes copy */
47 /* and move operations. It does, however, support arbitrary */
48 /* precision (up to 999,999,999 digits) and arbitrary exponent */
49 /* range (Emax in the range 0 through 999,999,999 and Emin in the */
50 /* range -999,999,999 through 0). */
52 /* 3. Operands to operator functions are never modified unless they */
53 /* are also specified to be the result number (which is always */
54 /* permitted). Other than that case, operands may not overlap. */
56 /* 4. Error handling: the type of the error is ORed into the status */
57 /* flags in the current context (decContext structure). The */
58 /* SIGFPE signal is then raised if the corresponding trap-enabler */
59 /* flag in the decContext is set (is 1). */
61 /* It is the responsibility of the caller to clear the status */
62 /* flags as required. */
64 /* The result of any routine which returns a number will always */
65 /* be a valid number (which may be a special value, such as an */
66 /* Infinity or NaN). */
68 /* 5. The decNumber format is not an exchangeable concrete */
69 /* representation as it comprises fields which may be machine- */
70 /* dependent (big-endian or little-endian, for example). */
71 /* Canonical conversions to and from strings are provided; other */
72 /* conversions are available in separate modules. */
74 /* 6. Normally, input operands are assumed to be valid. Set DECCHECK */
75 /* to 1 for extended operand checking (including NULL operands). */
76 /* Results are undefined if a badly-formed structure (or a NULL */
77 /* NULL pointer to a structure) is provided, though with DECCHECK */
78 /* enabled the operator routines are protected against exceptions. */
79 /* (Except if the result pointer is NULL, which is unrecoverable.) */
81 /* However, the routines will never cause exceptions if they are */
82 /* given well-formed operands, even if the value of the operands */
83 /* is inappropriate for the operation and DECCHECK is not set. */
85 /* 7. Subset arithmetic is available only if DECSUBSET is set to 1. */
86 /* ------------------------------------------------------------------ */
87 /* Implementation notes for maintenance of this module: */
89 /* 1. Storage leak protection: Routines which use malloc are not */
90 /* permitted to use return for fastpath or error exits (i.e., */
91 /* they follow strict structured programming conventions). */
92 /* Instead they have a do{}while(0); construct surrounding the */
93 /* code which is protected -- break may be used from this. */
94 /* Other routines are allowed to use the return statement inline. */
96 /* Storage leak accounting can be enabled using DECALLOC. */
98 /* 2. All loops use the for(;;) construct. Any do construct is for */
99 /* protection as just described. */
101 /* 3. Setting status in the context must always be the very last */
102 /* action in a routine, as non-0 status may raise a trap and hence */
103 /* the call to set status may not return (if the handler uses long */
104 /* jump). Therefore all cleanup must be done first. In general, */
105 /* to achieve this we accumulate status and only finally apply it */
106 /* by calling decContextSetStatus (via decStatus). */
108 /* Routines which allocate storage cannot, therefore, use the */
109 /* 'top level' routines which could cause a non-returning */
110 /* transfer of control. The decXxxxOp routines are safe (do not */
111 /* call decStatus even if traps are set in the context) and should */
112 /* be used instead (they are also a little faster). */
114 /* 4. Exponent checking is minimized by allowing the exponent to */
115 /* grow outside its limits during calculations, provided that */
116 /* the decFinalize function is called later. Multiplication and */
117 /* division, and intermediate calculations in exponentiation, */
118 /* require more careful checks because of the risk of 31-bit */
119 /* overflow (the most negative valid exponent is -1999999997, for */
120 /* a 999999999-digit number with adjusted exponent of -999999999). */
122 /* 5. Rounding is deferred until finalization of results, with any */
123 /* 'off to the right' data being represented as a single digit */
124 /* residue (in the range -1 through 9). This avoids any double- */
125 /* rounding when more than one shortening takes place (for */
126 /* example, when a result is subnormal). */
128 /* 6. The digits count is allowed to rise to a multiple of DECDPUN */
129 /* during many operations, so whole Units are handled and exact */
130 /* accounting of digits is not needed. The correct digits value */
131 /* is found by decGetDigits, which accounts for leading zeros. */
132 /* This must be called before any rounding if the number of digits */
133 /* is not known exactly. */
135 /* 7. We use the multiply-by-reciprocal 'trick' for partitioning */
136 /* numbers up to four digits, using appropriate constants. This */
137 /* is not useful for longer numbers because overflow of 32 bits */
138 /* would lead to 4 multiplies, which is almost as expensive as */
139 /* a divide (unless we assumed floating-point multiply available). */
141 /* 8. Unusual abbreviations possibly used in the commentary: */
142 /* lhs -- left hand side (operand, of an operation) */
143 /* lsd -- least significant digit (of coefficient) */
144 /* lsu -- least significant Unit (of coefficient) */
145 /* msd -- most significant digit (of coefficient) */
146 /* msu -- most significant Unit (of coefficient) */
147 /* rhs -- right hand side (operand, of an operation) */
148 /* +ve -- positive */
149 /* -ve -- negative */
150 /* ------------------------------------------------------------------ */
152 /* Some of glibc's string inlines cause warnings. Plus we'd rather
153 rely on (and therefore test) GCC's string builtins. */
154 #define __NO_STRING_INLINES
156 #include <stdlib.h> /* for malloc, free, etc. */
157 #include <stdio.h> /* for printf [if needed] */
158 #include <string.h> /* for strcpy */
159 #include <ctype.h> /* for lower */
161 #include "decNumber.h" /* base number library */
162 #include "decNumberLocal.h" /* decNumber local types, etc. */
165 /* Public constant array: powers of ten (powers[n]==10**n) */
166 const uInt powers[] = { 1, 10, 100, 1000, 10000, 100000, 1000000,
167 10000000, 100000000, 1000000000
170 /* Local constants */
171 #define DIVIDE 0x80 /* Divide operators */
172 #define REMAINDER 0x40 /* .. */
173 #define DIVIDEINT 0x20 /* .. */
174 #define REMNEAR 0x10 /* .. */
175 #define COMPARE 0x01 /* Compare operators */
176 #define COMPMAX 0x02 /* .. */
177 #define COMPMIN 0x03 /* .. */
178 #define COMPNAN 0x04 /* .. [NaN processing] */
180 #define DEC_sNaN 0x40000000 /* local status: sNaN signal */
181 #define BADINT (Int)0x80000000 /* most-negative Int; error indicator */
183 static Unit one[] = { 1 }; /* Unit array of 1, used for incrementing */
185 /* Granularity-dependent code */
187 #define eInt Int /* extended integer */
188 #define ueInt uInt /* unsigned extended integer */
189 /* Constant multipliers for divide-by-power-of five using reciprocal */
190 /* multiply, after removing powers of 2 by shifting, and final shift */
191 /* of 17 [we only need up to **4] */
192 static const uInt multies[] = { 131073, 26215, 5243, 1049, 210 };
194 /* QUOT10 -- macro to return the quotient of unit u divided by 10**n */
195 #define QUOT10(u, n) ((((uInt)(u)>>(n))*multies[n])>>17)
197 /* For DECDPUN>4 we currently use non-ANSI 64-bit types. These could */
198 /* be replaced by subroutine calls later. */
202 typedef signed long long Long;
203 typedef unsigned long long uLong;
204 #define eInt Long /* extended integer */
205 #define ueInt uLong /* unsigned extended integer */
209 static decNumber *decAddOp (decNumber *, const decNumber *,
210 const decNumber *, decContext *,
212 static void decApplyRound (decNumber *, decContext *, Int, uInt *);
213 static Int decCompare (const decNumber * lhs, const decNumber * rhs);
214 static decNumber *decCompareOp (decNumber *, const decNumber *, const decNumber *,
215 decContext *, Flag, uInt *);
216 static void decCopyFit (decNumber *, const decNumber *, decContext *,
218 static decNumber *decDivideOp (decNumber *, const decNumber *, const decNumber *,
219 decContext *, Flag, uInt *);
220 static void decFinalize (decNumber *, decContext *, Int *, uInt *);
221 static Int decGetDigits (const Unit *, Int);
223 static Int decGetInt (const decNumber *, decContext *);
225 static Int decGetInt (const decNumber *);
227 static decNumber *decMultiplyOp (decNumber *, const decNumber *,
228 const decNumber *, decContext *, uInt *);
229 static decNumber *decNaNs (decNumber *, const decNumber *, const decNumber *, uInt *);
230 static decNumber *decQuantizeOp (decNumber *, const decNumber *,
231 const decNumber *, decContext *, Flag, uInt *);
232 static void decSetCoeff (decNumber *, decContext *, const Unit *,
234 static void decSetOverflow (decNumber *, decContext *, uInt *);
235 static void decSetSubnormal (decNumber *, decContext *, Int *, uInt *);
236 static Int decShiftToLeast (Unit *, Int, Int);
237 static Int decShiftToMost (Unit *, Int, Int);
238 static void decStatus (decNumber *, uInt, decContext *);
239 static Flag decStrEq (const char *, const char *);
240 static void decToString (const decNumber *, char[], Flag);
241 static decNumber *decTrim (decNumber *, Flag, Int *);
242 static Int decUnitAddSub (const Unit *, Int, const Unit *, Int, Int, Unit *, Int);
243 static Int decUnitCompare (const Unit *, Int, const Unit *, Int, Int);
246 /* decFinish == decFinalize when no subset arithmetic needed */
247 #define decFinish(a,b,c,d) decFinalize(a,b,c,d)
249 static void decFinish (decNumber *, decContext *, Int *, uInt *);
250 static decNumber *decRoundOperand (const decNumber *, decContext *, uInt *);
253 /* Diagnostic macros, etc. */
255 /* Handle malloc/free accounting. If enabled, our accountable routines */
256 /* are used; otherwise the code just goes straight to the system malloc */
257 /* and free routines. */
258 #define malloc(a) decMalloc(a)
259 #define free(a) decFree(a)
260 #define DECFENCE 0x5a /* corruption detector */
261 /* 'Our' malloc and free: */
262 static void *decMalloc (size_t);
263 static void decFree (void *);
264 uInt decAllocBytes = 0; /* count of bytes allocated */
265 /* Note that DECALLOC code only checks for storage buffer overflow. */
266 /* To check for memory leaks, the decAllocBytes variable should be */
267 /* checked to be 0 at appropriate times (e.g., after the test */
268 /* harness completes a set of tests). This checking may be unreliable */
269 /* if the testing is done in a multi-thread environment. */
273 /* Optional operand checking routines. Enabling these means that */
274 /* decNumber and decContext operands to operator routines are checked */
275 /* for correctness. This roughly doubles the execution time of the */
276 /* fastest routines (and adds 600+ bytes), so should not normally be */
277 /* used in 'production'. */
278 #define DECUNUSED (void *)(0xffffffff)
279 static Flag decCheckOperands (decNumber *, const decNumber *,
280 const decNumber *, decContext *);
281 static Flag decCheckNumber (const decNumber *, decContext *);
284 #if DECTRACE || DECCHECK
285 /* Optional trace/debugging routines. */
286 void decNumberShow (const decNumber *); /* displays the components of a number */
287 static void decDumpAr (char, const Unit *, Int);
290 /* ================================================================== */
292 /* ================================================================== */
294 /* ------------------------------------------------------------------ */
295 /* to-scientific-string -- conversion to numeric string */
296 /* to-engineering-string -- conversion to numeric string */
298 /* decNumberToString(dn, string); */
299 /* decNumberToEngString(dn, string); */
301 /* dn is the decNumber to convert */
302 /* string is the string where the result will be laid out */
304 /* string must be at least dn->digits+14 characters long */
306 /* No error is possible, and no status can be set. */
307 /* ------------------------------------------------------------------ */
309 decNumberToString (const decNumber * dn, char *string)
311 decToString (dn, string, 0);
316 decNumberToEngString (const decNumber * dn, char *string)
318 decToString (dn, string, 1);
322 /* ------------------------------------------------------------------ */
323 /* to-number -- conversion from numeric string */
325 /* decNumberFromString -- convert string to decNumber */
326 /* dn -- the number structure to fill */
327 /* chars[] -- the string to convert ('\0' terminated) */
328 /* set -- the context used for processing any error, */
329 /* determining the maximum precision available */
330 /* (set.digits), determining the maximum and minimum */
331 /* exponent (set.emax and set.emin), determining if */
332 /* extended values are allowed, and checking the */
333 /* rounding mode if overflow occurs or rounding is */
336 /* The length of the coefficient and the size of the exponent are */
337 /* checked by this routine, so the correct error (Underflow or */
338 /* Overflow) can be reported or rounding applied, as necessary. */
340 /* If bad syntax is detected, the result will be a quiet NaN. */
341 /* ------------------------------------------------------------------ */
343 decNumberFromString (decNumber * dn, const char chars[], decContext * set)
345 Int exponent = 0; /* working exponent [assume 0] */
346 uByte bits = 0; /* working flags [assume +ve] */
347 Unit *res; /* where result will be built */
348 Unit resbuff[D2U (DECBUFFER + 1)]; /* local buffer in case need temporary */
349 Unit *allocres = NULL; /* -> allocated result, iff allocated */
350 Int need; /* units needed for result */
351 Int d = 0; /* count of digits found in decimal part */
352 const char *dotchar = NULL; /* where dot was found */
353 const char *cfirst; /* -> first character of decimal part */
354 const char *last = NULL; /* -> last digit of decimal part */
355 const char *firstexp; /* -> first significant exponent digit */
356 const char *c; /* work */
361 Int residue = 0; /* rounding residue */
362 uInt status = 0; /* error code */
365 if (decCheckOperands (DECUNUSED, DECUNUSED, DECUNUSED, set))
366 return decNumberZero (dn);
370 { /* status & malloc protection */
371 c = chars; /* -> input character */
373 { /* handle leading '-' */
378 c++; /* step over leading '+' */
379 /* We're at the start of the number [we think] */
380 cfirst = c; /* save */
383 if (*c >= '0' && *c <= '9')
384 { /* test for Arabic digit */
386 d++; /* count of real digits */
387 continue; /* still in decimal part */
390 break; /* done with decimal part */
391 /* dot: record, check, and ignore */
394 last = NULL; /* indicate bad */
396 } /* .. and go report */
397 dotchar = c; /* offset into decimal part */
401 { /* no decimal digits, or >1 . */
403 /* If subset then infinities and NaNs are not allowed */
406 status = DEC_Conversion_syntax;
407 break; /* all done */
412 /* Infinities and NaNs are possible, here */
413 decNumberZero (dn); /* be optimistic */
414 if (decStrEq (c, "Infinity") || decStrEq (c, "Inf"))
416 dn->bits = bits | DECINF;
417 break; /* all done */
420 { /* a NaN expected */
421 /* 2003.09.10 NaNs are now permitted to have a sign */
422 status = DEC_Conversion_syntax; /* assume the worst */
423 dn->bits = bits | DECNAN; /* assume simple NaN */
424 if (*c == 's' || *c == 'S')
425 { /* looks like an` sNaN */
427 dn->bits = bits | DECSNAN;
429 if (*c != 'n' && *c != 'N')
430 break; /* check caseless "NaN" */
432 if (*c != 'a' && *c != 'A')
435 if (*c != 'n' && *c != 'N')
438 /* now nothing, or nnnn, expected */
439 /* -> start of integer and skip leading 0s [including plain 0] */
440 for (cfirst = c; *cfirst == '0';)
443 { /* "NaN" or "sNaN", maybe with all 0s */
444 status = 0; /* it's good */
447 /* something other than 0s; setup last and d as usual [no dots] */
448 for (c = cfirst;; c++, d++)
450 if (*c < '0' || *c > '9')
451 break; /* test for Arabic digit */
455 break; /* not all digits */
457 break; /* too many digits */
458 /* good; drop through and convert the integer */
460 bits = dn->bits; /* for copy-back */
468 { /* more there; exponent expected... */
469 Flag nege = 0; /* 1=negative exponent */
470 if (*c != 'e' && *c != 'E')
472 status = DEC_Conversion_syntax;
476 /* Found 'e' or 'E' -- now process explicit exponent */
477 /* 1998.07.11: sign no longer required */
478 c++; /* to (expected) sign */
488 status = DEC_Conversion_syntax;
492 for (; *c == '0' && *(c + 1) != '\0';)
493 c++; /* strip insignificant zeros */
494 firstexp = c; /* save exponent digit place */
497 if (*c < '0' || *c > '9')
498 break; /* not a digit */
499 exponent = X10 (exponent) + (Int) * c - (Int) '0';
501 /* if we didn't end on '\0' must not be a digit */
504 status = DEC_Conversion_syntax;
508 /* (this next test must be after the syntax check) */
509 /* if it was too long the exponent may have wrapped, so check */
510 /* carefully and set it to a certain overflow if wrap possible */
511 if (c >= firstexp + 9 + 1)
513 if (c > firstexp + 9 + 1 || *firstexp > '1')
514 exponent = DECNUMMAXE * 2;
515 /* [up to 1999999999 is OK, for example 1E-1000000998] */
518 exponent = -exponent; /* was negative */
520 /* Here when all inspected; syntax is good */
522 /* Handle decimal point... */
523 if (dotchar != NULL && dotchar < last) /* embedded . found, so */
524 exponent = exponent - (last - dotchar); /* .. adjust exponent */
525 /* [we can now ignore the .] */
527 /* strip leading zeros/dot (leave final if all 0's) */
528 for (c = cfirst; c < last; c++)
531 d--; /* 0 stripped */
534 cfirst++; /* step past leader */
538 /* We can now make a rapid exit for zeros if !extended */
539 if (*cfirst == '0' && !set->extended)
541 decNumberZero (dn); /* clean result */
542 break; /* [could be return] */
546 /* OK, the digits string is good. Copy to the decNumber, or to
547 a temporary decNumber if rounding is needed */
548 if (d <= set->digits)
549 res = dn->lsu; /* fits into given decNumber */
551 { /* rounding needed */
552 need = D2U (d); /* units needed */
553 res = resbuff; /* assume use local buffer */
554 if (need * sizeof (Unit) > sizeof (resbuff))
555 { /* too big for local */
556 allocres = (Unit *) malloc (need * sizeof (Unit));
557 if (allocres == NULL)
559 status |= DEC_Insufficient_storage;
565 /* res now -> number lsu, buffer, or allocated storage for Unit array */
567 /* Place the coefficient into the selected Unit array */
569 i = d % DECDPUN; /* digits in top unit */
572 up = res + D2U (d) - 1; /* -> msu */
574 for (c = cfirst;; c++)
575 { /* along the digits */
577 { /* ignore . [don't decrement i] */
582 *up = (Unit) (X10 (*up) + (Int) * c - (Int) '0');
585 continue; /* more for this unit */
587 break; /* just filled the last unit */
594 up = res; /* -> lsu */
595 for (c = last; c >= cfirst; c--)
596 { /* over each character, from least */
598 continue; /* ignore . [don't step b] */
599 *up = (Unit) ((Int) * c - (Int) '0');
605 dn->exponent = exponent;
608 /* if not in number (too long) shorten into the number */
610 decSetCoeff (dn, set, res, d, &residue, &status);
612 /* Finally check for overflow or subnormal and round as needed */
613 decFinalize (dn, set, &residue, &status);
614 /* decNumberShow(dn); */
616 while (0); /* [for break] */
618 if (allocres != NULL)
619 free (allocres); /* drop any storage we used */
621 decStatus (dn, status, set);
625 /* ================================================================== */
627 /* ================================================================== */
629 /* ------------------------------------------------------------------ */
630 /* decNumberAbs -- absolute value operator */
632 /* This computes C = abs(A) */
634 /* res is C, the result. C may be A */
636 /* set is the context */
638 /* C must have space for set->digits digits. */
639 /* ------------------------------------------------------------------ */
640 /* This has the same effect as decNumberPlus unless A is negative, */
641 /* in which case it has the same effect as decNumberMinus. */
642 /* ------------------------------------------------------------------ */
644 decNumberAbs (decNumber * res, const decNumber * rhs, decContext * set)
646 decNumber dzero; /* for 0 */
647 uInt status = 0; /* accumulator */
650 if (decCheckOperands (res, DECUNUSED, rhs, set))
654 decNumberZero (&dzero); /* set 0 */
655 dzero.exponent = rhs->exponent; /* [no coefficient expansion] */
656 decAddOp (res, &dzero, rhs, set, (uByte) (rhs->bits & DECNEG), &status);
658 decStatus (res, status, set);
662 /* ------------------------------------------------------------------ */
663 /* decNumberAdd -- add two Numbers */
665 /* This computes C = A + B */
667 /* res is C, the result. C may be A and/or B (e.g., X=X+X) */
670 /* set is the context */
672 /* C must have space for set->digits digits. */
673 /* ------------------------------------------------------------------ */
674 /* This just calls the routine shared with Subtract */
676 decNumberAdd (decNumber * res, const decNumber * lhs,
677 const decNumber * rhs, decContext * set)
679 uInt status = 0; /* accumulator */
680 decAddOp (res, lhs, rhs, set, 0, &status);
682 decStatus (res, status, set);
686 /* ------------------------------------------------------------------ */
687 /* decNumberCompare -- compare two Numbers */
689 /* This computes C = A ? B */
691 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
694 /* set is the context */
696 /* C must have space for one digit. */
697 /* ------------------------------------------------------------------ */
699 decNumberCompare (decNumber * res, const decNumber * lhs,
700 const decNumber * rhs, decContext * set)
702 uInt status = 0; /* accumulator */
703 decCompareOp (res, lhs, rhs, set, COMPARE, &status);
705 decStatus (res, status, set);
709 /* ------------------------------------------------------------------ */
710 /* decNumberDivide -- divide one number by another */
712 /* This computes C = A / B */
714 /* res is C, the result. C may be A and/or B (e.g., X=X/X) */
717 /* set is the context */
719 /* C must have space for set->digits digits. */
720 /* ------------------------------------------------------------------ */
722 decNumberDivide (decNumber * res, const decNumber * lhs,
723 const decNumber * rhs, decContext * set)
725 uInt status = 0; /* accumulator */
726 decDivideOp (res, lhs, rhs, set, DIVIDE, &status);
728 decStatus (res, status, set);
732 /* ------------------------------------------------------------------ */
733 /* decNumberDivideInteger -- divide and return integer quotient */
735 /* This computes C = A # B, where # is the integer divide operator */
737 /* res is C, the result. C may be A and/or B (e.g., X=X#X) */
740 /* set is the context */
742 /* C must have space for set->digits digits. */
743 /* ------------------------------------------------------------------ */
745 decNumberDivideInteger (decNumber * res, const decNumber * lhs,
746 const decNumber * rhs, decContext * set)
748 uInt status = 0; /* accumulator */
749 decDivideOp (res, lhs, rhs, set, DIVIDEINT, &status);
751 decStatus (res, status, set);
755 /* ------------------------------------------------------------------ */
756 /* decNumberMax -- compare two Numbers and return the maximum */
758 /* This computes C = A ? B, returning the maximum or A if equal */
760 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
763 /* set is the context */
765 /* C must have space for set->digits digits. */
766 /* ------------------------------------------------------------------ */
768 decNumberMax (decNumber * res, const decNumber * lhs,
769 const decNumber * rhs, decContext * set)
771 uInt status = 0; /* accumulator */
772 decCompareOp (res, lhs, rhs, set, COMPMAX, &status);
774 decStatus (res, status, set);
778 /* ------------------------------------------------------------------ */
779 /* decNumberMin -- compare two Numbers and return the minimum */
781 /* This computes C = A ? B, returning the minimum or A if equal */
783 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
786 /* set is the context */
788 /* C must have space for set->digits digits. */
789 /* ------------------------------------------------------------------ */
791 decNumberMin (decNumber * res, const decNumber * lhs,
792 const decNumber * rhs, decContext * set)
794 uInt status = 0; /* accumulator */
795 decCompareOp (res, lhs, rhs, set, COMPMIN, &status);
797 decStatus (res, status, set);
801 /* ------------------------------------------------------------------ */
802 /* decNumberMinus -- prefix minus operator */
804 /* This computes C = 0 - A */
806 /* res is C, the result. C may be A */
808 /* set is the context */
810 /* C must have space for set->digits digits. */
811 /* ------------------------------------------------------------------ */
812 /* We simply use AddOp for the subtract, which will do the necessary. */
813 /* ------------------------------------------------------------------ */
815 decNumberMinus (decNumber * res, const decNumber * rhs, decContext * set)
818 uInt status = 0; /* accumulator */
821 if (decCheckOperands (res, DECUNUSED, rhs, set))
825 decNumberZero (&dzero); /* make 0 */
826 dzero.exponent = rhs->exponent; /* [no coefficient expansion] */
827 decAddOp (res, &dzero, rhs, set, DECNEG, &status);
829 decStatus (res, status, set);
833 /* ------------------------------------------------------------------ */
834 /* decNumberPlus -- prefix plus operator */
836 /* This computes C = 0 + A */
838 /* res is C, the result. C may be A */
840 /* set is the context */
842 /* C must have space for set->digits digits. */
843 /* ------------------------------------------------------------------ */
844 /* We simply use AddOp; Add will take fast path after preparing A. */
845 /* Performance is a concern here, as this routine is often used to */
846 /* check operands and apply rounding and overflow/underflow testing. */
847 /* ------------------------------------------------------------------ */
849 decNumberPlus (decNumber * res, const decNumber * rhs, decContext * set)
852 uInt status = 0; /* accumulator */
855 if (decCheckOperands (res, DECUNUSED, rhs, set))
859 decNumberZero (&dzero); /* make 0 */
860 dzero.exponent = rhs->exponent; /* [no coefficient expansion] */
861 decAddOp (res, &dzero, rhs, set, 0, &status);
863 decStatus (res, status, set);
867 /* ------------------------------------------------------------------ */
868 /* decNumberMultiply -- multiply two Numbers */
870 /* This computes C = A x B */
872 /* res is C, the result. C may be A and/or B (e.g., X=X+X) */
875 /* set is the context */
877 /* C must have space for set->digits digits. */
878 /* ------------------------------------------------------------------ */
880 decNumberMultiply (decNumber * res, const decNumber * lhs,
881 const decNumber * rhs, decContext * set)
883 uInt status = 0; /* accumulator */
884 decMultiplyOp (res, lhs, rhs, set, &status);
886 decStatus (res, status, set);
890 /* ------------------------------------------------------------------ */
891 /* decNumberNormalize -- remove trailing zeros */
893 /* This computes C = 0 + A, and normalizes the result */
895 /* res is C, the result. C may be A */
897 /* set is the context */
899 /* C must have space for set->digits digits. */
900 /* ------------------------------------------------------------------ */
902 decNumberNormalize (decNumber * res, const decNumber * rhs, decContext * set)
904 decNumber *allocrhs = NULL; /* non-NULL if rounded rhs allocated */
905 uInt status = 0; /* as usual */
906 Int residue = 0; /* as usual */
907 Int dropped; /* work */
910 if (decCheckOperands (res, DECUNUSED, rhs, set))
915 { /* protect allocated storage */
919 /* reduce operand and set lostDigits status, as needed */
920 if (rhs->digits > set->digits)
922 allocrhs = decRoundOperand (rhs, set, &status);
923 if (allocrhs == NULL)
929 /* [following code does not require input rounding] */
931 /* specials copy through, except NaNs need care */
932 if (decNumberIsNaN (rhs))
934 decNaNs (res, rhs, NULL, &status);
938 /* reduce result to the requested length and copy to result */
939 decCopyFit (res, rhs, set, &residue, &status); /* copy & round */
940 decFinish (res, set, &residue, &status); /* cleanup/set flags */
941 decTrim (res, 1, &dropped); /* normalize in place */
943 while (0); /* end protected */
945 if (allocrhs != NULL)
946 free (allocrhs); /* .. */
948 decStatus (res, status, set); /* then report status */
952 /* ------------------------------------------------------------------ */
953 /* decNumberPower -- raise a number to an integer power */
955 /* This computes C = A ** B */
957 /* res is C, the result. C may be A and/or B (e.g., X=X**X) */
960 /* set is the context */
962 /* C must have space for set->digits digits. */
964 /* Specification restriction: abs(n) must be <=999999999 */
965 /* ------------------------------------------------------------------ */
967 decNumberPower (decNumber * res, decNumber * lhs,
968 decNumber * rhs, decContext * set)
970 decNumber *alloclhs = NULL; /* non-NULL if rounded lhs allocated */
971 decNumber *allocrhs = NULL; /* .., rhs */
972 decNumber *allocdac = NULL; /* -> allocated acc buffer, iff used */
973 decNumber *inrhs = rhs; /* save original rhs */
974 Int reqdigits = set->digits; /* requested DIGITS */
975 Int n; /* RHS in binary */
978 Int dropped; /* .. */
980 uInt needbytes; /* buffer size needed */
981 Flag seenbit; /* seen a bit while powering */
982 Int residue = 0; /* rounding residue */
983 uInt status = 0; /* accumulator */
984 uByte bits = 0; /* result sign if errors */
985 decContext workset; /* working context */
986 decNumber dnOne; /* work value 1... */
987 /* local accumulator buffer [a decNumber, with digits+elength+1 digits] */
988 uByte dacbuff[sizeof (decNumber) + D2U (DECBUFFER + 9) * sizeof (Unit)];
989 /* same again for possible 1/lhs calculation */
990 uByte lhsbuff[sizeof (decNumber) + D2U (DECBUFFER + 9) * sizeof (Unit)];
991 decNumber *dac = (decNumber *) dacbuff; /* -> result accumulator */
994 if (decCheckOperands (res, lhs, rhs, set))
999 { /* protect allocated storage */
1003 /* reduce operands and set lostDigits status, as needed */
1004 if (lhs->digits > reqdigits)
1006 alloclhs = decRoundOperand (lhs, set, &status);
1007 if (alloclhs == NULL)
1011 /* rounding won't affect the result, but we might signal lostDigits */
1012 /* as well as the error for non-integer [x**y would need this too] */
1013 if (rhs->digits > reqdigits)
1015 allocrhs = decRoundOperand (rhs, set, &status);
1016 if (allocrhs == NULL)
1022 /* [following code does not require input rounding] */
1024 /* handle rhs Infinity */
1025 if (decNumberIsInfinite (rhs))
1027 status |= DEC_Invalid_operation; /* bad */
1031 if ((lhs->bits | rhs->bits) & (DECNAN | DECSNAN))
1033 decNaNs (res, lhs, rhs, &status);
1037 /* Original rhs must be an integer that fits and is in range */
1039 n = decGetInt (inrhs, set);
1041 n = decGetInt (inrhs);
1043 if (n == BADINT || n > 999999999 || n < -999999999)
1045 status |= DEC_Invalid_operation;
1050 n = -n; /* use the absolute value */
1052 if (decNumberIsNegative (lhs) /* -x .. */
1053 && (n & 0x00000001))
1054 bits = DECNEG; /* .. to an odd power */
1056 /* handle LHS infinity */
1057 if (decNumberIsInfinite (lhs))
1058 { /* [NaNs already handled] */
1059 uByte rbits = rhs->bits; /* save */
1060 decNumberZero (res);
1062 *res->lsu = 1; /* [-]Inf**0 => 1 */
1065 if (!(rbits & DECNEG))
1066 bits |= DECINF; /* was not a **-n */
1067 /* [otherwise will be 0 or -0] */
1073 /* clone the context */
1074 workset = *set; /* copy all fields */
1075 /* calculate the working DIGITS */
1076 workset.digits = reqdigits + (inrhs->digits + inrhs->exponent) + 1;
1077 /* it's an error if this is more than we can handle */
1078 if (workset.digits > DECNUMMAXP)
1080 status |= DEC_Invalid_operation;
1084 /* workset.digits is the count of digits for the accumulator we need */
1085 /* if accumulator is too long for local storage, then allocate */
1087 sizeof (decNumber) + (D2U (workset.digits) - 1) * sizeof (Unit);
1088 /* [needbytes also used below if 1/lhs needed] */
1089 if (needbytes > sizeof (dacbuff))
1091 allocdac = (decNumber *) malloc (needbytes);
1092 if (allocdac == NULL)
1093 { /* hopeless -- abandon */
1094 status |= DEC_Insufficient_storage;
1097 dac = allocdac; /* use the allocated space */
1099 decNumberZero (dac); /* acc=1 */
1100 *dac->lsu = 1; /* .. */
1103 { /* x**0 is usually 1 */
1104 /* 0**0 is bad unless subset, when it becomes 1 */
1110 status |= DEC_Invalid_operation;
1112 decNumberCopy (res, dac); /* copy the 1 */
1116 /* if a negative power we'll need the constant 1, and if not subset */
1117 /* we'll invert the lhs now rather than inverting the result later */
1118 if (decNumberIsNegative (rhs))
1119 { /* was a **-n [hence digits>0] */
1120 decNumberCopy (&dnOne, dac); /* dnOne=1; [needed now or later] */
1123 { /* need to calculate 1/lhs */
1125 /* divide lhs into 1, putting result in dac [dac=1/dac] */
1126 decDivideOp (dac, &dnOne, lhs, &workset, DIVIDE, &status);
1127 if (alloclhs != NULL)
1129 free (alloclhs); /* done with intermediate */
1130 alloclhs = NULL; /* indicate freed */
1132 /* now locate or allocate space for the inverted lhs */
1133 if (needbytes > sizeof (lhsbuff))
1135 alloclhs = (decNumber *) malloc (needbytes);
1136 if (alloclhs == NULL)
1137 { /* hopeless -- abandon */
1138 status |= DEC_Insufficient_storage;
1141 lhs = alloclhs; /* use the allocated space */
1144 lhs = (decNumber *) lhsbuff; /* use stack storage */
1145 /* [lhs now points to buffer or allocated storage] */
1146 decNumberCopy (lhs, dac); /* copy the 1/lhs */
1147 decNumberCopy (dac, &dnOne); /* restore acc=1 */
1153 /* Raise-to-the-power loop... */
1154 seenbit = 0; /* set once we've seen a 1-bit */
1156 { /* for each bit [top bit ignored] */
1157 /* abandon if we have had overflow or terminal underflow */
1158 if (status & (DEC_Overflow | DEC_Underflow))
1159 { /* interesting? */
1160 if (status & DEC_Overflow || ISZERO (dac))
1163 /* [the following two lines revealed an optimizer bug in a C++ */
1164 /* compiler, with symptom: 5**3 -> 25, when n=n+n was used] */
1165 n = n << 1; /* move next bit to testable position */
1167 { /* top bit is set */
1168 seenbit = 1; /* OK, we're off */
1169 decMultiplyOp (dac, dac, lhs, &workset, &status); /* dac=dac*x */
1172 break; /* that was the last bit */
1174 continue; /* we don't have to square 1 */
1175 decMultiplyOp (dac, dac, dac, &workset, &status); /* dac=dac*dac [square] */
1176 } /*i *//* 32 bits */
1178 /* complete internal overflow or underflow processing */
1179 if (status & (DEC_Overflow | DEC_Subnormal))
1182 /* If subset, and power was negative, reverse the kind of -erflow */
1183 /* [1/x not yet done] */
1184 if (!set->extended && decNumberIsNegative (rhs))
1186 if (status & DEC_Overflow)
1187 status ^= DEC_Overflow | DEC_Underflow | DEC_Subnormal;
1189 { /* trickier -- Underflow may or may not be set */
1190 status &= ~(DEC_Underflow | DEC_Subnormal); /* [one or both] */
1191 status |= DEC_Overflow;
1195 dac->bits = (dac->bits & ~DECNEG) | bits; /* force correct sign */
1196 /* round subnormals [to set.digits rather than workset.digits] */
1197 /* or set overflow result similarly as required */
1198 decFinalize (dac, set, &residue, &status);
1199 decNumberCopy (res, dac); /* copy to result (is now OK length) */
1204 if (!set->extended && /* subset math */
1205 decNumberIsNegative (rhs))
1206 { /* was a **-n [hence digits>0] */
1207 /* so divide result into 1 [dac=1/dac] */
1208 decDivideOp (dac, &dnOne, dac, &workset, DIVIDE, &status);
1212 /* reduce result to the requested length and copy to result */
1213 decCopyFit (res, dac, set, &residue, &status);
1214 decFinish (res, set, &residue, &status); /* final cleanup */
1217 decTrim (res, 0, &dropped); /* trailing zeros */
1220 while (0); /* end protected */
1222 if (allocdac != NULL)
1223 free (allocdac); /* drop any storage we used */
1224 if (allocrhs != NULL)
1225 free (allocrhs); /* .. */
1226 if (alloclhs != NULL)
1227 free (alloclhs); /* .. */
1229 decStatus (res, status, set);
1233 /* ------------------------------------------------------------------ */
1234 /* decNumberQuantize -- force exponent to requested value */
1236 /* This computes C = op(A, B), where op adjusts the coefficient */
1237 /* of C (by rounding or shifting) such that the exponent (-scale) */
1238 /* of C has exponent of B. The numerical value of C will equal A, */
1239 /* except for the effects of any rounding that occurred. */
1241 /* res is C, the result. C may be A or B */
1242 /* lhs is A, the number to adjust */
1243 /* rhs is B, the number with exponent to match */
1244 /* set is the context */
1246 /* C must have space for set->digits digits. */
1248 /* Unless there is an error or the result is infinite, the exponent */
1249 /* after the operation is guaranteed to be equal to that of B. */
1250 /* ------------------------------------------------------------------ */
1252 decNumberQuantize (decNumber * res, const decNumber * lhs,
1253 const decNumber * rhs, decContext * set)
1255 uInt status = 0; /* accumulator */
1256 decQuantizeOp (res, lhs, rhs, set, 1, &status);
1258 decStatus (res, status, set);
1262 /* ------------------------------------------------------------------ */
1263 /* decNumberRescale -- force exponent to requested value */
1265 /* This computes C = op(A, B), where op adjusts the coefficient */
1266 /* of C (by rounding or shifting) such that the exponent (-scale) */
1267 /* of C has the value B. The numerical value of C will equal A, */
1268 /* except for the effects of any rounding that occurred. */
1270 /* res is C, the result. C may be A or B */
1271 /* lhs is A, the number to adjust */
1272 /* rhs is B, the requested exponent */
1273 /* set is the context */
1275 /* C must have space for set->digits digits. */
1277 /* Unless there is an error or the result is infinite, the exponent */
1278 /* after the operation is guaranteed to be equal to B. */
1279 /* ------------------------------------------------------------------ */
1281 decNumberRescale (decNumber * res, const decNumber * lhs,
1282 const decNumber * rhs, decContext * set)
1284 uInt status = 0; /* accumulator */
1285 decQuantizeOp (res, lhs, rhs, set, 0, &status);
1287 decStatus (res, status, set);
1291 /* ------------------------------------------------------------------ */
1292 /* decNumberRemainder -- divide and return remainder */
1294 /* This computes C = A % B */
1296 /* res is C, the result. C may be A and/or B (e.g., X=X%X) */
1299 /* set is the context */
1301 /* C must have space for set->digits digits. */
1302 /* ------------------------------------------------------------------ */
1304 decNumberRemainder (decNumber * res, const decNumber * lhs,
1305 const decNumber * rhs, decContext * set)
1307 uInt status = 0; /* accumulator */
1308 decDivideOp (res, lhs, rhs, set, REMAINDER, &status);
1310 decStatus (res, status, set);
1314 /* ------------------------------------------------------------------ */
1315 /* decNumberRemainderNear -- divide and return remainder from nearest */
1317 /* This computes C = A % B, where % is the IEEE remainder operator */
1319 /* res is C, the result. C may be A and/or B (e.g., X=X%X) */
1322 /* set is the context */
1324 /* C must have space for set->digits digits. */
1325 /* ------------------------------------------------------------------ */
1327 decNumberRemainderNear (decNumber * res, const decNumber * lhs,
1328 const decNumber * rhs, decContext * set)
1330 uInt status = 0; /* accumulator */
1331 decDivideOp (res, lhs, rhs, set, REMNEAR, &status);
1333 decStatus (res, status, set);
1337 /* ------------------------------------------------------------------ */
1338 /* decNumberSameQuantum -- test for equal exponents */
1340 /* res is the result number, which will contain either 0 or 1 */
1341 /* lhs is a number to test */
1342 /* rhs is the second (usually a pattern) */
1344 /* No errors are possible and no context is needed. */
1345 /* ------------------------------------------------------------------ */
1347 decNumberSameQuantum (decNumber * res, const decNumber * lhs, const decNumber * rhs)
1349 uByte merged; /* merged flags */
1350 Unit ret = 0; /* return value */
1353 if (decCheckOperands (res, lhs, rhs, DECUNUSED))
1357 merged = (lhs->bits | rhs->bits) & DECSPECIAL;
1360 if (decNumberIsNaN (lhs) && decNumberIsNaN (rhs))
1362 else if (decNumberIsInfinite (lhs) && decNumberIsInfinite (rhs))
1364 /* [anything else with a special gives 0] */
1366 else if (lhs->exponent == rhs->exponent)
1369 decNumberZero (res); /* OK to overwrite an operand */
1374 /* ------------------------------------------------------------------ */
1375 /* decNumberSquareRoot -- square root operator */
1377 /* This computes C = squareroot(A) */
1379 /* res is C, the result. C may be A */
1381 /* set is the context; note that rounding mode has no effect */
1383 /* C must have space for set->digits digits. */
1384 /* ------------------------------------------------------------------ */
1385 /* This uses the following varying-precision algorithm in: */
1387 /* Properly Rounded Variable Precision Square Root, T. E. Hull and */
1388 /* A. Abrham, ACM Transactions on Mathematical Software, Vol 11 #3, */
1389 /* pp229-237, ACM, September 1985. */
1391 /* % [Reformatted original Numerical Turing source code follows.] */
1392 /* function sqrt(x : real) : real */
1393 /* % sqrt(x) returns the properly rounded approximation to the square */
1394 /* % root of x, in the precision of the calling environment, or it */
1395 /* % fails if x < 0. */
1396 /* % t e hull and a abrham, august, 1984 */
1397 /* if x <= 0 then */
1404 /* var f := setexp(x, 0) % fraction part of x [0.1 <= x < 1] */
1405 /* var e := getexp(x) % exponent part of x */
1406 /* var approx : real */
1407 /* if e mod 2 = 0 then */
1408 /* approx := .259 + .819 * f % approx to root of f */
1410 /* f := f/l0 % adjustments */
1411 /* e := e + 1 % for odd */
1412 /* approx := .0819 + 2.59 * f % exponent */
1416 /* const maxp := currentprecision + 2 */
1418 /* p := min(2*p - 2, maxp) % p = 4,6,10, . . . , maxp */
1420 /* approx := .5 * (approx + f/approx) */
1421 /* exit when p = maxp */
1424 /* % approx is now within 1 ulp of the properly rounded square root */
1425 /* % of f; to ensure proper rounding, compare squares of (approx - */
1426 /* % l/2 ulp) and (approx + l/2 ulp) with f. */
1427 /* p := currentprecision */
1429 /* precision p + 2 */
1430 /* const approxsubhalf := approx - setexp(.5, -p) */
1431 /* if mulru(approxsubhalf, approxsubhalf) > f then */
1432 /* approx := approx - setexp(.l, -p + 1) */
1434 /* const approxaddhalf := approx + setexp(.5, -p) */
1435 /* if mulrd(approxaddhalf, approxaddhalf) < f then */
1436 /* approx := approx + setexp(.l, -p + 1) */
1440 /* result setexp(approx, e div 2) % fix exponent */
1442 /* ------------------------------------------------------------------ */
1444 decNumberSquareRoot (decNumber * res, const decNumber * rhs, decContext * set)
1446 decContext workset, approxset; /* work contexts */
1447 decNumber dzero; /* used for constant zero */
1448 Int maxp = set->digits + 2; /* largest working precision */
1449 Int residue = 0; /* rounding residue */
1450 uInt status = 0, ignore = 0; /* status accumulators */
1451 Int exp; /* working exponent */
1452 Int ideal; /* ideal (preferred) exponent */
1453 uInt needbytes; /* work */
1454 Int dropped; /* .. */
1456 decNumber *allocrhs = NULL; /* non-NULL if rounded rhs allocated */
1457 /* buffer for f [needs +1 in case DECBUFFER 0] */
1458 uByte buff[sizeof (decNumber) + (D2U (DECBUFFER + 1) - 1) * sizeof (Unit)];
1459 /* buffer for a [needs +2 to match maxp] */
1460 uByte bufa[sizeof (decNumber) + (D2U (DECBUFFER + 2) - 1) * sizeof (Unit)];
1461 /* buffer for temporary, b [must be same size as a] */
1462 uByte bufb[sizeof (decNumber) + (D2U (DECBUFFER + 2) - 1) * sizeof (Unit)];
1463 decNumber *allocbuff = NULL; /* -> allocated buff, iff allocated */
1464 decNumber *allocbufa = NULL; /* -> allocated bufa, iff allocated */
1465 decNumber *allocbufb = NULL; /* -> allocated bufb, iff allocated */
1466 decNumber *f = (decNumber *) buff; /* reduced fraction */
1467 decNumber *a = (decNumber *) bufa; /* approximation to result */
1468 decNumber *b = (decNumber *) bufb; /* intermediate result */
1469 /* buffer for temporary variable, up to 3 digits */
1470 uByte buft[sizeof (decNumber) + (D2U (3) - 1) * sizeof (Unit)];
1471 decNumber *t = (decNumber *) buft; /* up-to-3-digit constant or work */
1474 if (decCheckOperands (res, DECUNUSED, rhs, set))
1479 { /* protect allocated storage */
1483 /* reduce operand and set lostDigits status, as needed */
1484 if (rhs->digits > set->digits)
1486 allocrhs = decRoundOperand (rhs, set, &status);
1487 if (allocrhs == NULL)
1489 /* [Note: 'f' allocation below could reuse this buffer if */
1490 /* used, but as this is rare we keep them separate for clarity.] */
1495 /* [following code does not require input rounding] */
1497 /* handle infinities and NaNs */
1498 if (rhs->bits & DECSPECIAL)
1500 if (decNumberIsInfinite (rhs))
1502 if (decNumberIsNegative (rhs))
1503 status |= DEC_Invalid_operation;
1505 decNumberCopy (res, rhs); /* +Infinity */
1508 decNaNs (res, rhs, NULL, &status); /* a NaN */
1512 /* calculate the ideal (preferred) exponent [floor(exp/2)] */
1513 /* [We would like to write: ideal=rhs->exponent>>1, but this */
1514 /* generates a compiler warning. Generated code is the same.] */
1515 ideal = (rhs->exponent & ~1) / 2; /* target */
1520 decNumberCopy (res, rhs); /* could be 0 or -0 */
1521 res->exponent = ideal; /* use the ideal [safe] */
1525 /* any other -x is an oops */
1526 if (decNumberIsNegative (rhs))
1528 status |= DEC_Invalid_operation;
1532 /* we need space for three working variables */
1533 /* f -- the same precision as the RHS, reduced to 0.01->0.99... */
1534 /* a -- Hull's approx -- precision, when assigned, is */
1535 /* currentprecision (we allow +2 for use as temporary) */
1536 /* b -- intermediate temporary result */
1537 /* if any is too long for local storage, then allocate */
1539 sizeof (decNumber) + (D2U (rhs->digits) - 1) * sizeof (Unit);
1540 if (needbytes > sizeof (buff))
1542 allocbuff = (decNumber *) malloc (needbytes);
1543 if (allocbuff == NULL)
1544 { /* hopeless -- abandon */
1545 status |= DEC_Insufficient_storage;
1548 f = allocbuff; /* use the allocated space */
1550 /* a and b both need to be able to hold a maxp-length number */
1551 needbytes = sizeof (decNumber) + (D2U (maxp) - 1) * sizeof (Unit);
1552 if (needbytes > sizeof (bufa))
1553 { /* [same applies to b] */
1554 allocbufa = (decNumber *) malloc (needbytes);
1555 allocbufb = (decNumber *) malloc (needbytes);
1556 if (allocbufa == NULL || allocbufb == NULL)
1558 status |= DEC_Insufficient_storage;
1561 a = allocbufa; /* use the allocated space */
1562 b = allocbufb; /* .. */
1565 /* copy rhs -> f, save exponent, and reduce so 0.1 <= f < 1 */
1566 decNumberCopy (f, rhs);
1567 exp = f->exponent + f->digits; /* adjusted to Hull rules */
1568 f->exponent = -(f->digits); /* to range */
1570 /* set up working contexts (the second is used for Numerical */
1571 /* Turing assignment) */
1572 decContextDefault (&workset, DEC_INIT_DECIMAL64);
1573 decContextDefault (&approxset, DEC_INIT_DECIMAL64);
1574 approxset.digits = set->digits; /* approx's length */
1576 /* [Until further notice, no error is possible and status bits */
1577 /* (Rounded, etc.) should be ignored, not accumulated.] */
1579 /* Calculate initial approximation, and allow for odd exponent */
1580 workset.digits = set->digits; /* p for initial calculation */
1586 { /* even exponent */
1587 /* Set t=0.259, a=0.819 */
1608 { /* odd exponent */
1609 /* Set t=0.0819, a=2.59 */
1610 f->exponent--; /* f=f/10 */
1631 decMultiplyOp (a, a, f, &workset, &ignore); /* a=a*f */
1632 decAddOp (a, a, t, &workset, 0, &ignore); /* ..+t */
1633 /* [a is now the initial approximation for sqrt(f), calculated with */
1634 /* currentprecision, which is also a's precision.] */
1636 /* the main calculation loop */
1637 decNumberZero (&dzero); /* make 0 */
1638 decNumberZero (t); /* set t = 0.5 */
1639 t->lsu[0] = 5; /* .. */
1640 t->exponent = -1; /* .. */
1641 workset.digits = 3; /* initial p */
1644 /* set p to min(2*p - 2, maxp) [hence 3; or: 4, 6, 10, ... , maxp] */
1645 workset.digits = workset.digits * 2 - 2;
1646 if (workset.digits > maxp)
1647 workset.digits = maxp;
1648 /* a = 0.5 * (a + f/a) */
1649 /* [calculated at p then rounded to currentprecision] */
1650 decDivideOp (b, f, a, &workset, DIVIDE, &ignore); /* b=f/a */
1651 decAddOp (b, b, a, &workset, 0, &ignore); /* b=b+a */
1652 decMultiplyOp (a, b, t, &workset, &ignore); /* a=b*0.5 */
1653 /* assign to approx [round to length] */
1654 decAddOp (a, &dzero, a, &approxset, 0, &ignore);
1655 if (workset.digits == maxp)
1656 break; /* just did final */
1659 /* a is now at currentprecision and within 1 ulp of the properly */
1660 /* rounded square root of f; to ensure proper rounding, compare */
1661 /* squares of (a - l/2 ulp) and (a + l/2 ulp) with f. */
1662 /* Here workset.digits=maxp and t=0.5 */
1663 workset.digits--; /* maxp-1 is OK now */
1664 t->exponent = -set->digits - 1; /* make 0.5 ulp */
1665 decNumberCopy (b, a);
1666 decAddOp (b, b, t, &workset, DECNEG, &ignore); /* b = a - 0.5 ulp */
1667 workset.round = DEC_ROUND_UP;
1668 decMultiplyOp (b, b, b, &workset, &ignore); /* b = mulru(b, b) */
1669 decCompareOp (b, f, b, &workset, COMPARE, &ignore); /* b ? f, reversed */
1670 if (decNumberIsNegative (b))
1671 { /* f < b [i.e., b > f] */
1672 /* this is the more common adjustment, though both are rare */
1673 t->exponent++; /* make 1.0 ulp */
1674 t->lsu[0] = 1; /* .. */
1675 decAddOp (a, a, t, &workset, DECNEG, &ignore); /* a = a - 1 ulp */
1676 /* assign to approx [round to length] */
1677 decAddOp (a, &dzero, a, &approxset, 0, &ignore);
1681 decNumberCopy (b, a);
1682 decAddOp (b, b, t, &workset, 0, &ignore); /* b = a + 0.5 ulp */
1683 workset.round = DEC_ROUND_DOWN;
1684 decMultiplyOp (b, b, b, &workset, &ignore); /* b = mulrd(b, b) */
1685 decCompareOp (b, b, f, &workset, COMPARE, &ignore); /* b ? f */
1686 if (decNumberIsNegative (b))
1688 t->exponent++; /* make 1.0 ulp */
1689 t->lsu[0] = 1; /* .. */
1690 decAddOp (a, a, t, &workset, 0, &ignore); /* a = a + 1 ulp */
1691 /* assign to approx [round to length] */
1692 decAddOp (a, &dzero, a, &approxset, 0, &ignore);
1695 /* [no errors are possible in the above, and rounding/inexact during */
1696 /* estimation are irrelevant, so status was not accumulated] */
1698 /* Here, 0.1 <= a < 1 [Hull] */
1699 a->exponent += exp / 2; /* set correct exponent */
1701 /* Process Subnormals */
1702 decFinalize (a, set, &residue, &status);
1704 /* count dropable zeros [after any subnormal rounding] */
1705 decNumberCopy (b, a);
1706 decTrim (b, 1, &dropped); /* [drops trailing zeros] */
1708 /* Finally set Inexact and Rounded. The answer can only be exact if */
1709 /* it is short enough so that squaring it could fit in set->digits, */
1710 /* so this is the only (relatively rare) time we have to check */
1712 if (b->digits * 2 - 1 > set->digits)
1714 status |= DEC_Inexact | DEC_Rounded;
1717 { /* could be exact/unrounded */
1718 uInt mstatus = 0; /* local status */
1719 decMultiplyOp (b, b, b, &workset, &mstatus); /* try the multiply */
1721 { /* result won't fit */
1722 status |= DEC_Inexact | DEC_Rounded;
1726 decCompareOp (t, b, rhs, &workset, COMPARE, &mstatus); /* b ? rhs */
1729 status |= DEC_Inexact | DEC_Rounded;
1733 /* here, dropped is the count of trailing zeros in 'a' */
1734 /* use closest exponent to ideal... */
1735 Int todrop = ideal - a->exponent; /* most we can drop */
1738 { /* ideally would add 0s */
1739 status |= DEC_Rounded;
1743 if (dropped < todrop)
1744 todrop = dropped; /* clamp to those available */
1746 { /* OK, some to drop */
1747 decShiftToLeast (a->lsu, D2U (a->digits), todrop);
1748 a->exponent += todrop; /* maintain numerical value */
1749 a->digits -= todrop; /* new length */
1755 decNumberCopy (res, a); /* assume this is the result */
1757 while (0); /* end protected */
1759 if (allocbuff != NULL)
1760 free (allocbuff); /* drop any storage we used */
1761 if (allocbufa != NULL)
1762 free (allocbufa); /* .. */
1763 if (allocbufb != NULL)
1764 free (allocbufb); /* .. */
1765 if (allocrhs != NULL)
1766 free (allocrhs); /* .. */
1768 decStatus (res, status, set); /* then report status */
1772 /* ------------------------------------------------------------------ */
1773 /* decNumberSubtract -- subtract two Numbers */
1775 /* This computes C = A - B */
1777 /* res is C, the result. C may be A and/or B (e.g., X=X-X) */
1780 /* set is the context */
1782 /* C must have space for set->digits digits. */
1783 /* ------------------------------------------------------------------ */
1785 decNumberSubtract (decNumber * res, const decNumber * lhs,
1786 const decNumber * rhs, decContext * set)
1788 uInt status = 0; /* accumulator */
1790 decAddOp (res, lhs, rhs, set, DECNEG, &status);
1792 decStatus (res, status, set);
1796 /* ------------------------------------------------------------------ */
1797 /* decNumberToIntegralValue -- round-to-integral-value */
1799 /* res is the result */
1800 /* rhs is input number */
1801 /* set is the context */
1803 /* res must have space for any value of rhs. */
1805 /* This implements the IEEE special operator and therefore treats */
1806 /* special values as valid, and also never sets Inexact. For finite */
1807 /* numbers it returns rescale(rhs, 0) if rhs->exponent is <0. */
1808 /* Otherwise the result is rhs (so no error is possible). */
1810 /* The context is used for rounding mode and status after sNaN, but */
1811 /* the digits setting is ignored. */
1812 /* ------------------------------------------------------------------ */
1814 decNumberToIntegralValue (decNumber * res, const decNumber * rhs, decContext * set)
1817 decContext workset; /* working context */
1820 if (decCheckOperands (res, DECUNUSED, rhs, set))
1824 /* handle infinities and NaNs */
1825 if (rhs->bits & DECSPECIAL)
1828 if (decNumberIsInfinite (rhs))
1829 decNumberCopy (res, rhs); /* an Infinity */
1831 decNaNs (res, rhs, NULL, &status); /* a NaN */
1833 decStatus (res, status, set);
1837 /* we have a finite number; no error possible */
1838 if (rhs->exponent >= 0)
1839 return decNumberCopy (res, rhs);
1840 /* that was easy, but if negative exponent we have work to do... */
1841 workset = *set; /* clone rounding, etc. */
1842 workset.digits = rhs->digits; /* no length rounding */
1843 workset.traps = 0; /* no traps */
1844 decNumberZero (&dn); /* make a number with exponent 0 */
1845 return decNumberQuantize (res, rhs, &dn, &workset);
1848 /* ================================================================== */
1849 /* Utility routines */
1850 /* ================================================================== */
1852 /* ------------------------------------------------------------------ */
1853 /* decNumberCopy -- copy a number */
1855 /* dest is the target decNumber */
1856 /* src is the source decNumber */
1859 /* (dest==src is allowed and is a no-op) */
1860 /* All fields are updated as required. This is a utility operation, */
1861 /* so special values are unchanged and no error is possible. */
1862 /* ------------------------------------------------------------------ */
1864 decNumberCopy (decNumber * dest, const decNumber * src)
1869 return decNumberZero (dest);
1873 return dest; /* no copy required */
1875 /* We use explicit assignments here as structure assignment can copy */
1876 /* more than just the lsu (for small DECDPUN). This would not affect */
1877 /* the value of the results, but would disturb test harness spill */
1879 dest->bits = src->bits;
1880 dest->exponent = src->exponent;
1881 dest->digits = src->digits;
1882 dest->lsu[0] = src->lsu[0];
1883 if (src->digits > DECDPUN)
1884 { /* more Units to come */
1886 const Unit *s, *smsup; /* work */
1887 /* memcpy for the remaining Units would be safe as they cannot */
1888 /* overlap. However, this explicit loop is faster in short cases. */
1889 d = dest->lsu + 1; /* -> first destination */
1890 smsup = src->lsu + D2U (src->digits); /* -> source msu+1 */
1891 for (s = src->lsu + 1; s < smsup; s++, d++)
1897 /* ------------------------------------------------------------------ */
1898 /* decNumberTrim -- remove insignificant zeros */
1900 /* dn is the number to trim */
1903 /* All fields are updated as required. This is a utility operation, */
1904 /* so special values are unchanged and no error is possible. */
1905 /* ------------------------------------------------------------------ */
1907 decNumberTrim (decNumber * dn)
1909 Int dropped; /* work */
1910 return decTrim (dn, 0, &dropped);
1913 /* ------------------------------------------------------------------ */
1914 /* decNumberVersion -- return the name and version of this module */
1916 /* No error is possible. */
1917 /* ------------------------------------------------------------------ */
1919 decNumberVersion (void)
1924 /* ------------------------------------------------------------------ */
1925 /* decNumberZero -- set a number to 0 */
1927 /* dn is the number to set, with space for one digit */
1930 /* No error is possible. */
1931 /* ------------------------------------------------------------------ */
1932 /* Memset is not used as it is much slower in some environments. */
1934 decNumberZero (decNumber * dn)
1938 if (decCheckOperands (dn, DECUNUSED, DECUNUSED, DECUNUSED))
1949 /* ================================================================== */
1950 /* Local routines */
1951 /* ================================================================== */
1953 /* ------------------------------------------------------------------ */
1954 /* decToString -- lay out a number into a string */
1956 /* dn is the number to lay out */
1957 /* string is where to lay out the number */
1958 /* eng is 1 if Engineering, 0 if Scientific */
1960 /* str must be at least dn->digits+14 characters long */
1961 /* No error is possible. */
1963 /* Note that this routine can generate a -0 or 0.000. These are */
1964 /* never generated in subset to-number or arithmetic, but can occur */
1965 /* in non-subset arithmetic (e.g., -1*0 or 1.234-1.234). */
1966 /* ------------------------------------------------------------------ */
1967 /* If DECCHECK is enabled the string "?" is returned if a number is */
1970 /* TODIGIT -- macro to remove the leading digit from the unsigned */
1971 /* integer u at column cut (counting from the right, LSD=0) and place */
1972 /* it as an ASCII character into the character pointed to by c. Note */
1973 /* that cut must be <= 9, and the maximum value for u is 2,000,000,000 */
1974 /* (as is needed for negative exponents of subnormals). The unsigned */
1975 /* integer pow is used as a temporary variable. */
1976 #define TODIGIT(u, cut, c) { \
1978 pow=powers[cut]*2; \
1981 if ((u)>=pow) {(u)-=pow; *(c)+=8;} \
1983 if ((u)>=pow) {(u)-=pow; *(c)+=4;} \
1986 if ((u)>=pow) {(u)-=pow; *(c)+=2;} \
1988 if ((u)>=pow) {(u)-=pow; *(c)+=1;} \
1992 decToString (const decNumber * dn, char *string, Flag eng)
1994 Int exp = dn->exponent; /* local copy */
1995 Int e; /* E-part value */
1996 Int pre; /* digits before the '.' */
1997 Int cut; /* for counting digits in a Unit */
1998 char *c = string; /* work [output pointer] */
1999 const Unit *up = dn->lsu + D2U (dn->digits) - 1; /* -> msu [input pointer] */
2000 uInt u, pow; /* work */
2003 if (decCheckOperands (DECUNUSED, dn, DECUNUSED, DECUNUSED))
2005 strcpy (string, "?");
2010 if (decNumberIsNegative (dn))
2011 { /* Negatives get a minus (except */
2012 *c = '-'; /* NaNs, which remove the '-' below) */
2015 if (dn->bits & DECSPECIAL)
2016 { /* Is a special value */
2017 if (decNumberIsInfinite (dn))
2019 strcpy (c, "Infinity");
2023 if (dn->bits & DECSNAN)
2024 { /* signalling NaN */
2029 c += 3; /* step past */
2030 /* if not a clean non-zero coefficient, that's all we have in a */
2032 if (exp != 0 || (*dn->lsu == 0 && dn->digits == 1))
2034 /* [drop through to add integer] */
2037 /* calculate how many digits in msu, and hence first cut */
2038 cut = dn->digits % DECDPUN;
2040 cut = DECDPUN; /* msu is full */
2041 cut--; /* power of ten for digit */
2044 { /* simple integer [common fastpath, */
2045 /* used for NaNs, too] */
2046 for (; up >= dn->lsu; up--)
2047 { /* each Unit from msu */
2048 u = *up; /* contains DECDPUN digits to lay out */
2049 for (; cut >= 0; c++, cut--)
2050 TODIGIT (u, cut, c);
2051 cut = DECDPUN - 1; /* next Unit has all digits */
2053 *c = '\0'; /* terminate the string */
2057 /* non-0 exponent -- assume plain form */
2058 pre = dn->digits + exp; /* digits before '.' */
2060 if ((exp > 0) || (pre < -5))
2061 { /* need exponential form */
2062 e = exp + dn->digits - 1; /* calculate E value */
2063 pre = 1; /* assume one digit before '.' */
2064 if (eng && (e != 0))
2065 { /* may need to adjust */
2066 Int adj; /* adjustment */
2067 /* The C remainder operator is undefined for negative numbers, so */
2068 /* we must use positive remainder calculation here */
2080 /* if we are dealing with zero we will use exponent which is a */
2081 /* multiple of three, as expected, but there will only be the */
2082 /* one zero before the E, still. Otherwise note the padding. */
2088 { /* 0.00Esnn needed */
2096 /* lay out the digits of the coefficient, adding 0s and . as needed */
2099 { /* xxx.xxx or xx00 (engineering) form */
2100 for (; pre > 0; pre--, c++, cut--)
2103 { /* need new Unit */
2105 break; /* out of input digits (pre>digits) */
2110 TODIGIT (u, cut, c);
2112 if (up > dn->lsu || (up == dn->lsu && cut >= 0))
2113 { /* more to come, after '.' */
2119 { /* need new Unit */
2121 break; /* out of input digits */
2126 TODIGIT (u, cut, c);
2130 for (; pre > 0; pre--, c++)
2131 *c = '0'; /* 0 padding (for engineering) needed */
2134 { /* 0.xxx or 0.000xxx form */
2139 for (; pre < 0; pre++, c++)
2140 *c = '0'; /* add any 0's after '.' */
2144 { /* need new Unit */
2146 break; /* out of input digits */
2151 TODIGIT (u, cut, c);
2155 /* Finally add the E-part, if needed. It will never be 0, has a
2156 base maximum and minimum of +999999999 through -999999999, but
2157 could range down to -1999999998 for subnormal numbers */
2160 Flag had = 0; /* 1=had non-zero */
2164 c++; /* assume positive */
2168 *(c - 1) = '-'; /* oops, need - */
2169 u = -e; /* uInt, please */
2171 /* layout the exponent (_itoa is not ANSI C) */
2172 for (cut = 9; cut >= 0; cut--)
2174 TODIGIT (u, cut, c);
2175 if (*c == '0' && !had)
2176 continue; /* skip leading zeros */
2177 had = 1; /* had non-0 */
2178 c++; /* step for next */
2181 *c = '\0'; /* terminate the string (all paths) */
2185 /* ------------------------------------------------------------------ */
2186 /* decAddOp -- add/subtract operation */
2188 /* This computes C = A + B */
2190 /* res is C, the result. C may be A and/or B (e.g., X=X+X) */
2193 /* set is the context */
2194 /* negate is DECNEG if rhs should be negated, or 0 otherwise */
2195 /* status accumulates status for the caller */
2197 /* C must have space for set->digits digits. */
2198 /* ------------------------------------------------------------------ */
2199 /* If possible, we calculate the coefficient directly into C. */
2201 /* -- we need a digits+1 calculation because numbers are unaligned */
2202 /* and span more than set->digits digits */
2203 /* -- a carry to digits+1 digits looks possible */
2204 /* -- C is the same as A or B, and the result would destructively */
2205 /* overlap the A or B coefficient */
2206 /* then we must calculate into a temporary buffer. In this latter */
2207 /* case we use the local (stack) buffer if possible, and only if too */
2208 /* long for that do we resort to malloc. */
2210 /* Misalignment is handled as follows: */
2211 /* Apad: (AExp>BExp) Swap operands and proceed as for BExp>AExp. */
2212 /* BPad: Apply the padding by a combination of shifting (whole */
2213 /* units) and multiplication (part units). */
2215 /* Addition, especially x=x+1, is speed-critical, so we take pains */
2216 /* to make returning as fast as possible, by flagging any allocation. */
2217 /* ------------------------------------------------------------------ */
2219 decAddOp (decNumber * res, const decNumber * lhs,
2220 const decNumber * rhs, decContext * set, uByte negate, uInt * status)
2222 decNumber *alloclhs = NULL; /* non-NULL if rounded lhs allocated */
2223 decNumber *allocrhs = NULL; /* .., rhs */
2224 Int rhsshift; /* working shift (in Units) */
2225 Int maxdigits; /* longest logical length */
2226 Int mult; /* multiplier */
2227 Int residue; /* rounding accumulator */
2228 uByte bits; /* result bits */
2229 Flag diffsign; /* non-0 if arguments have different sign */
2230 Unit *acc; /* accumulator for result */
2231 Unit accbuff[D2U (DECBUFFER + 1)]; /* local buffer [+1 is for possible */
2232 /* final carry digit or DECBUFFER=0] */
2233 Unit *allocacc = NULL; /* -> allocated acc buffer, iff allocated */
2234 Flag alloced = 0; /* set non-0 if any allocations */
2235 Int reqdigits = set->digits; /* local copy; requested DIGITS */
2236 uByte merged; /* merged flags */
2237 Int padding; /* work */
2240 if (decCheckOperands (res, lhs, rhs, set))
2245 { /* protect allocated storage */
2249 /* reduce operands and set lostDigits status, as needed */
2250 if (lhs->digits > reqdigits)
2252 alloclhs = decRoundOperand (lhs, set, status);
2253 if (alloclhs == NULL)
2258 if (rhs->digits > reqdigits)
2260 allocrhs = decRoundOperand (rhs, set, status);
2261 if (allocrhs == NULL)
2268 /* [following code does not require input rounding] */
2270 /* note whether signs differ */
2271 diffsign = (Flag) ((lhs->bits ^ rhs->bits ^ negate) & DECNEG);
2273 /* handle infinities and NaNs */
2274 merged = (lhs->bits | rhs->bits) & DECSPECIAL;
2276 { /* a special bit set */
2277 if (merged & (DECSNAN | DECNAN)) /* a NaN */
2278 decNaNs (res, lhs, rhs, status);
2280 { /* one or two infinities */
2281 if (decNumberIsInfinite (lhs))
2282 { /* LHS is infinity */
2283 /* two infinities with different signs is invalid */
2284 if (decNumberIsInfinite (rhs) && diffsign)
2286 *status |= DEC_Invalid_operation;
2289 bits = lhs->bits & DECNEG; /* get sign from LHS */
2292 bits = (rhs->bits ^ negate) & DECNEG; /* RHS must be Infinity */
2294 decNumberZero (res);
2295 res->bits = bits; /* set +/- infinity */
2300 /* Quick exit for add 0s; return the non-0, modified as need be */
2303 Int adjust; /* work */
2304 Int lexp = lhs->exponent; /* save in case LHS==RES */
2305 bits = lhs->bits; /* .. */
2306 residue = 0; /* clear accumulator */
2307 decCopyFit (res, rhs, set, &residue, status); /* copy (as needed) */
2308 res->bits ^= negate; /* flip if rhs was negated */
2311 { /* exponents on zeros count */
2313 /* exponent will be the lower of the two */
2314 adjust = lexp - res->exponent; /* adjustment needed [if -ve] */
2316 { /* both 0: special IEEE 854 rules */
2318 res->exponent = lexp; /* set exponent */
2319 /* 0-0 gives +0 unless rounding to -infinity, and -0-0 gives -0 */
2322 if (set->round != DEC_ROUND_FLOOR)
2325 res->bits = DECNEG; /* preserve 0 sign */
2331 { /* 0-padding needed */
2332 if ((res->digits - adjust) > set->digits)
2334 adjust = res->digits - set->digits; /* to fit exactly */
2335 *status |= DEC_Rounded; /* [but exact] */
2338 decShiftToMost (res->lsu, res->digits, -adjust);
2339 res->exponent += adjust; /* set the exponent. */
2345 decFinish (res, set, &residue, status); /* clean and finalize */
2350 { /* [lhs is non-zero] */
2351 Int adjust; /* work */
2352 Int rexp = rhs->exponent; /* save in case RHS==RES */
2353 bits = rhs->bits; /* be clean */
2354 residue = 0; /* clear accumulator */
2355 decCopyFit (res, lhs, set, &residue, status); /* copy (as needed) */
2358 { /* exponents on zeros count */
2360 /* exponent will be the lower of the two */
2361 /* [0-0 case handled above] */
2362 adjust = rexp - res->exponent; /* adjustment needed [if -ve] */
2364 { /* 0-padding needed */
2365 if ((res->digits - adjust) > set->digits)
2367 adjust = res->digits - set->digits; /* to fit exactly */
2368 *status |= DEC_Rounded; /* [but exact] */
2371 decShiftToMost (res->lsu, res->digits, -adjust);
2372 res->exponent += adjust; /* set the exponent. */
2377 decFinish (res, set, &residue, status); /* clean and finalize */
2380 /* [both fastpath and mainpath code below assume these cases */
2381 /* (notably 0-0) have already been handled] */
2383 /* calculate the padding needed to align the operands */
2384 padding = rhs->exponent - lhs->exponent;
2386 /* Fastpath cases where the numbers are aligned and normal, the RHS */
2387 /* is all in one unit, no operand rounding is needed, and no carry, */
2388 /* lengthening, or borrow is needed */
2389 if (rhs->digits <= DECDPUN && padding == 0 && rhs->exponent >= set->emin /* [some normals drop through] */
2390 && rhs->digits <= reqdigits && lhs->digits <= reqdigits)
2392 Int partial = *lhs->lsu;
2395 Int maxv = DECDPUNMAX; /* highest no-overflow */
2396 if (lhs->digits < DECDPUN)
2397 maxv = powers[lhs->digits] - 1;
2398 partial += *rhs->lsu;
2399 if (partial <= maxv)
2402 decNumberCopy (res, lhs); /* not in place */
2403 *res->lsu = (Unit) partial; /* [copy could have overwritten RHS] */
2406 /* else drop out for careful add */
2409 { /* signs differ */
2410 partial -= *rhs->lsu;
2412 { /* no borrow needed, and non-0 result */
2414 decNumberCopy (res, lhs); /* not in place */
2415 *res->lsu = (Unit) partial;
2416 /* this could have reduced digits [but result>0] */
2417 res->digits = decGetDigits (res->lsu, D2U (res->digits));
2420 /* else drop out for careful subtract */
2424 /* Now align (pad) the lhs or rhs so we can add or subtract them, as
2425 necessary. If one number is much larger than the other (that is,
2426 if in plain form there is a least one digit between the lowest
2427 digit or one and the highest of the other) we need to pad with up
2428 to DIGITS-1 trailing zeros, and then apply rounding (as exotic
2429 rounding modes may be affected by the residue).
2431 rhsshift = 0; /* rhs shift to left (padding) in Units */
2432 bits = lhs->bits; /* assume sign is that of LHS */
2433 mult = 1; /* likely multiplier */
2435 /* if padding==0 the operands are aligned; no padding needed */
2438 /* some padding needed */
2439 /* We always pad the RHS, as we can then effect any required */
2440 /* padding by a combination of shifts and a multiply */
2443 { /* LHS needs the padding */
2445 padding = -padding; /* will be +ve */
2446 bits = (uByte) (rhs->bits ^ negate); /* assumed sign is now that of RHS */
2453 /* If, after pad, rhs would be longer than lhs by digits+1 or */
2454 /* more then lhs cannot affect the answer, except as a residue, */
2455 /* so we only need to pad up to a length of DIGITS+1. */
2456 if (rhs->digits + padding > lhs->digits + reqdigits + 1)
2458 /* The RHS is sufficient */
2459 /* for residue we use the relative sign indication... */
2460 Int shift = reqdigits - rhs->digits; /* left shift needed */
2461 residue = 1; /* residue for rounding */
2463 residue = -residue; /* signs differ */
2464 /* copy, shortening if necessary */
2465 decCopyFit (res, rhs, set, &residue, status);
2466 /* if it was already shorter, then need to pad with zeros */
2469 res->digits = decShiftToMost (res->lsu, res->digits, shift);
2470 res->exponent -= shift; /* adjust the exponent. */
2472 /* flip the result sign if unswapped and rhs was negated */
2474 res->bits ^= negate;
2475 decFinish (res, set, &residue, status); /* done */
2479 /* LHS digits may affect result */
2480 rhsshift = D2U (padding + 1) - 1; /* this much by Unit shift .. */
2481 mult = powers[padding - (rhsshift * DECDPUN)]; /* .. this by multiplication */
2482 } /* padding needed */
2485 mult = -mult; /* signs differ */
2487 /* determine the longer operand */
2488 maxdigits = rhs->digits + padding; /* virtual length of RHS */
2489 if (lhs->digits > maxdigits)
2490 maxdigits = lhs->digits;
2492 /* Decide on the result buffer to use; if possible place directly */
2494 acc = res->lsu; /* assume build direct */
2495 /* If destructive overlap, or the number is too long, or a carry or */
2496 /* borrow to DIGITS+1 might be possible we must use a buffer. */
2497 /* [Might be worth more sophisticated tests when maxdigits==reqdigits] */
2498 if ((maxdigits >= reqdigits) /* is, or could be, too large */
2499 || (res == rhs && rhsshift > 0))
2500 { /* destructive overlap */
2501 /* buffer needed; choose it */
2502 /* we'll need units for maxdigits digits, +1 Unit for carry or borrow */
2503 Int need = D2U (maxdigits) + 1;
2504 acc = accbuff; /* assume use local buffer */
2505 if (need * sizeof (Unit) > sizeof (accbuff))
2507 allocacc = (Unit *) malloc (need * sizeof (Unit));
2508 if (allocacc == NULL)
2509 { /* hopeless -- abandon */
2510 *status |= DEC_Insufficient_storage;
2518 res->bits = (uByte) (bits & DECNEG); /* it's now safe to overwrite.. */
2519 res->exponent = lhs->exponent; /* .. operands (even if aliased) */
2522 decDumpAr ('A', lhs->lsu, D2U (lhs->digits));
2523 decDumpAr ('B', rhs->lsu, D2U (rhs->digits));
2524 printf (" :h: %d %d\n", rhsshift, mult);
2527 /* add [A+B*m] or subtract [A+B*(-m)] */
2528 res->digits = decUnitAddSub (lhs->lsu, D2U (lhs->digits), rhs->lsu, D2U (rhs->digits), rhsshift, acc, mult) * DECDPUN; /* [units -> digits] */
2529 if (res->digits < 0)
2531 res->digits = -res->digits;
2532 res->bits ^= DECNEG; /* flip the sign */
2535 decDumpAr ('+', acc, D2U (res->digits));
2538 /* If we used a buffer we need to copy back, possibly shortening */
2539 /* (If we didn't use buffer it must have fit, so can't need rounding */
2540 /* and residue must be 0.) */
2541 residue = 0; /* clear accumulator */
2542 if (acc != res->lsu)
2546 { /* round from first significant digit */
2548 /* remove leading zeros that we added due to rounding up to */
2549 /* integral Units -- before the test for rounding. */
2550 if (res->digits > reqdigits)
2551 res->digits = decGetDigits (acc, D2U (res->digits));
2552 decSetCoeff (res, set, acc, res->digits, &residue, status);
2556 { /* subset arithmetic rounds from original significant digit */
2557 /* We may have an underestimate. This only occurs when both */
2558 /* numbers fit in DECDPUN digits and we are padding with a */
2559 /* negative multiple (-10, -100...) and the top digit(s) become */
2560 /* 0. (This only matters if we are using X3.274 rules where the */
2561 /* leading zero could be included in the rounding.) */
2562 if (res->digits < maxdigits)
2564 *(acc + D2U (res->digits)) = 0; /* ensure leading 0 is there */
2565 res->digits = maxdigits;
2569 /* remove leading zeros that we added due to rounding up to */
2570 /* integral Units (but only those in excess of the original */
2571 /* maxdigits length, unless extended) before test for rounding. */
2572 if (res->digits > reqdigits)
2574 res->digits = decGetDigits (acc, D2U (res->digits));
2575 if (res->digits < maxdigits)
2576 res->digits = maxdigits;
2579 decSetCoeff (res, set, acc, res->digits, &residue, status);
2580 /* Now apply rounding if needed before removing leading zeros. */
2581 /* This is safe because subnormals are not a possibility */
2584 decApplyRound (res, set, residue, status);
2585 residue = 0; /* we did what we had to do */
2591 /* strip leading zeros [these were left on in case of subset subtract] */
2592 res->digits = decGetDigits (res->lsu, D2U (res->digits));
2594 /* apply checks and rounding */
2595 decFinish (res, set, &residue, status);
2597 /* "When the sum of two operands with opposite signs is exactly */
2598 /* zero, the sign of that sum shall be '+' in all rounding modes */
2599 /* except round toward -Infinity, in which mode that sign shall be */
2600 /* '-'." [Subset zeros also never have '-', set by decFinish.] */
2601 if (ISZERO (res) && diffsign
2605 && (*status & DEC_Inexact) == 0)
2607 if (set->round == DEC_ROUND_FLOOR)
2608 res->bits |= DECNEG; /* sign - */
2610 res->bits &= ~DECNEG; /* sign + */
2613 while (0); /* end protected */
2617 if (allocacc != NULL)
2618 free (allocacc); /* drop any storage we used */
2619 if (allocrhs != NULL)
2620 free (allocrhs); /* .. */
2621 if (alloclhs != NULL)
2622 free (alloclhs); /* .. */
2627 /* ------------------------------------------------------------------ */
2628 /* decDivideOp -- division operation */
2630 /* This routine performs the calculations for all four division */
2631 /* operators (divide, divideInteger, remainder, remainderNear). */
2635 /* res is C, the result. C may be A and/or B (e.g., X=X/X) */
2638 /* set is the context */
2639 /* op is DIVIDE, DIVIDEINT, REMAINDER, or REMNEAR respectively. */
2640 /* status is the usual accumulator */
2642 /* C must have space for set->digits digits. */
2644 /* ------------------------------------------------------------------ */
2645 /* The underlying algorithm of this routine is the same as in the */
2646 /* 1981 S/370 implementation, that is, non-restoring long division */
2647 /* with bi-unit (rather than bi-digit) estimation for each unit */
2648 /* multiplier. In this pseudocode overview, complications for the */
2649 /* Remainder operators and division residues for exact rounding are */
2650 /* omitted for clarity. */
2652 /* Prepare operands and handle special values */
2653 /* Test for x/0 and then 0/x */
2654 /* Exp =Exp1 - Exp2 */
2655 /* Exp =Exp +len(var1) -len(var2) */
2656 /* Sign=Sign1 * Sign2 */
2657 /* Pad accumulator (Var1) to double-length with 0's (pad1) */
2658 /* Pad Var2 to same length as Var1 */
2659 /* msu2pair/plus=1st 2 or 1 units of var2, +1 to allow for round */
2661 /* Do until (have=digits+1 OR residue=0) */
2662 /* if exp<0 then if integer divide/residue then leave */
2665 /* compare numbers */
2666 /* if <0 then leave inner_loop */
2667 /* if =0 then (* quick exit without subtract *) do */
2668 /* this_unit=this_unit+1; output this_unit */
2669 /* leave outer_loop; end */
2670 /* Compare lengths of numbers (mantissae): */
2671 /* If same then tops2=msu2pair -- {units 1&2 of var2} */
2672 /* else tops2=msu2plus -- {0, unit 1 of var2} */
2673 /* tops1=first_unit_of_Var1*10**DECDPUN +second_unit_of_var1 */
2674 /* mult=tops1/tops2 -- Good and safe guess at divisor */
2675 /* if mult=0 then mult=1 */
2676 /* this_unit=this_unit+mult */
2678 /* end inner_loop */
2679 /* if have\=0 | this_unit\=0 then do */
2680 /* output this_unit */
2681 /* have=have+1; end */
2684 /* end outer_loop */
2685 /* exp=exp+1 -- set the proper exponent */
2686 /* if have=0 then generate answer=0 */
2687 /* Return (Result is defined by Var1) */
2689 /* ------------------------------------------------------------------ */
2690 /* We need two working buffers during the long division; one (digits+ */
2691 /* 1) to accumulate the result, and the other (up to 2*digits+1) for */
2692 /* long subtractions. These are acc and var1 respectively. */
2693 /* var1 is a copy of the lhs coefficient, var2 is the rhs coefficient.*/
2694 /* ------------------------------------------------------------------ */
2696 decDivideOp (decNumber * res,
2697 const decNumber * lhs, const decNumber * rhs,
2698 decContext * set, Flag op, uInt * status)
2700 decNumber *alloclhs = NULL; /* non-NULL if rounded lhs allocated */
2701 decNumber *allocrhs = NULL; /* .., rhs */
2702 Unit accbuff[D2U (DECBUFFER + DECDPUN)]; /* local buffer */
2703 Unit *acc = accbuff; /* -> accumulator array for result */
2704 Unit *allocacc = NULL; /* -> allocated buffer, iff allocated */
2705 Unit *accnext; /* -> where next digit will go */
2706 Int acclength; /* length of acc needed [Units] */
2707 Int accunits; /* count of units accumulated */
2708 Int accdigits; /* count of digits accumulated */
2710 Unit varbuff[D2U (DECBUFFER * 2 + DECDPUN) * sizeof (Unit)]; /* buffer for var1 */
2711 Unit *var1 = varbuff; /* -> var1 array for long subtraction */
2712 Unit *varalloc = NULL; /* -> allocated buffer, iff used */
2714 const Unit *var2; /* -> var2 array */
2716 Int var1units, var2units; /* actual lengths */
2717 Int var2ulen; /* logical length (units) */
2718 Int var1initpad = 0; /* var1 initial padding (digits) */
2719 Unit *msu1; /* -> msu of each var */
2720 const Unit *msu2; /* -> msu of each var */
2721 Int msu2plus; /* msu2 plus one [does not vary] */
2722 eInt msu2pair; /* msu2 pair plus one [does not vary] */
2723 Int maxdigits; /* longest LHS or required acc length */
2724 Int mult; /* multiplier for subtraction */
2725 Unit thisunit; /* current unit being accumulated */
2726 Int residue; /* for rounding */
2727 Int reqdigits = set->digits; /* requested DIGITS */
2728 Int exponent; /* working exponent */
2729 Int maxexponent = 0; /* DIVIDE maximum exponent if unrounded */
2730 uByte bits; /* working sign */
2731 uByte merged; /* merged flags */
2732 Unit *target; /* work */
2733 const Unit *source; /* work */
2734 uInt const *pow; /* .. */
2735 Int shift, cut; /* .. */
2737 Int dropped; /* work */
2741 if (decCheckOperands (res, lhs, rhs, set))
2746 { /* protect allocated storage */
2750 /* reduce operands and set lostDigits status, as needed */
2751 if (lhs->digits > reqdigits)
2753 alloclhs = decRoundOperand (lhs, set, status);
2754 if (alloclhs == NULL)
2758 if (rhs->digits > reqdigits)
2760 allocrhs = decRoundOperand (rhs, set, status);
2761 if (allocrhs == NULL)
2767 /* [following code does not require input rounding] */
2769 bits = (lhs->bits ^ rhs->bits) & DECNEG; /* assumed sign for divisions */
2771 /* handle infinities and NaNs */
2772 merged = (lhs->bits | rhs->bits) & DECSPECIAL;
2774 { /* a special bit set */
2775 if (merged & (DECSNAN | DECNAN))
2776 { /* one or two NaNs */
2777 decNaNs (res, lhs, rhs, status);
2780 /* one or two infinities */
2781 if (decNumberIsInfinite (lhs))
2782 { /* LHS (dividend) is infinite */
2783 if (decNumberIsInfinite (rhs) || /* two infinities are invalid .. */
2784 op & (REMAINDER | REMNEAR))
2785 { /* as is remainder of infinity */
2786 *status |= DEC_Invalid_operation;
2789 /* [Note that infinity/0 raises no exceptions] */
2790 decNumberZero (res);
2791 res->bits = bits | DECINF; /* set +/- infinity */
2795 { /* RHS (divisor) is infinite */
2797 if (op & (REMAINDER | REMNEAR))
2799 /* result is [finished clone of] lhs */
2800 decCopyFit (res, lhs, set, &residue, status);
2804 decNumberZero (res);
2805 res->bits = bits; /* set +/- zero */
2806 /* for DIVIDEINT the exponent is always 0. For DIVIDE, result */
2807 /* is a 0 with infinitely negative exponent, clamped to minimum */
2810 res->exponent = set->emin - set->digits + 1;
2811 *status |= DEC_Clamped;
2814 decFinish (res, set, &residue, status);
2819 /* handle 0 rhs (x/0) */
2821 { /* x/0 is always exceptional */
2824 decNumberZero (res); /* [after lhs test] */
2825 *status |= DEC_Division_undefined; /* 0/0 will become NaN */
2829 decNumberZero (res);
2830 if (op & (REMAINDER | REMNEAR))
2831 *status |= DEC_Invalid_operation;
2834 *status |= DEC_Division_by_zero; /* x/0 */
2835 res->bits = bits | DECINF; /* .. is +/- Infinity */
2841 /* handle 0 lhs (0/x) */
2846 decNumberZero (res);
2853 exponent = lhs->exponent - rhs->exponent; /* ideal exponent */
2854 decNumberCopy (res, lhs); /* [zeros always fit] */
2855 res->bits = bits; /* sign as computed */
2856 res->exponent = exponent; /* exponent, too */
2857 decFinalize (res, set, &residue, status); /* check exponent */
2859 else if (op & DIVIDEINT)
2861 decNumberZero (res); /* integer 0 */
2862 res->bits = bits; /* sign as computed */
2866 exponent = rhs->exponent; /* [save in case overwrite] */
2867 decNumberCopy (res, lhs); /* [zeros always fit] */
2868 if (exponent < res->exponent)
2869 res->exponent = exponent; /* use lower */
2877 /* Precalculate exponent. This starts off adjusted (and hence fits */
2878 /* in 31 bits) and becomes the usual unadjusted exponent as the */
2879 /* division proceeds. The order of evaluation is important, here, */
2880 /* to avoid wrap. */
2882 (lhs->exponent + lhs->digits) - (rhs->exponent + rhs->digits);
2884 /* If the working exponent is -ve, then some quick exits are */
2885 /* possible because the quotient is known to be <1 */
2886 /* [for REMNEAR, it needs to be < -1, as -0.5 could need work] */
2887 if (exponent < 0 && !(op == DIVIDE))
2891 decNumberZero (res); /* integer part is 0 */
2895 res->bits = bits; /* set +/- zero */
2898 /* we can fastpath remainders so long as the lhs has the */
2899 /* smaller (or equal) exponent */
2900 if (lhs->exponent <= rhs->exponent)
2902 if (op & REMAINDER || exponent < -1)
2904 /* It is REMAINDER or safe REMNEAR; result is [finished */
2905 /* clone of] lhs (r = x - 0*y) */
2907 decCopyFit (res, lhs, set, &residue, status);
2908 decFinish (res, set, &residue, status);
2911 /* [unsafe REMNEAR drops through] */
2915 /* We need long (slow) division; roll up the sleeves... */
2917 /* The accumulator will hold the quotient of the division. */
2918 /* If it needs to be too long for stack storage, then allocate. */
2919 acclength = D2U (reqdigits + DECDPUN); /* in Units */
2920 if (acclength * sizeof (Unit) > sizeof (accbuff))
2922 allocacc = (Unit *) malloc (acclength * sizeof (Unit));
2923 if (allocacc == NULL)
2924 { /* hopeless -- abandon */
2925 *status |= DEC_Insufficient_storage;
2928 acc = allocacc; /* use the allocated space */
2931 /* var1 is the padded LHS ready for subtractions. */
2932 /* If it needs to be too long for stack storage, then allocate. */
2933 /* The maximum units we need for var1 (long subtraction) is: */
2935 /* (rhs->digits+reqdigits-1) -- to allow full slide to right */
2936 /* or (lhs->digits) -- to allow for long lhs */
2937 /* whichever is larger */
2938 /* +1 -- for rounding of slide to right */
2939 /* +1 -- for leading 0s */
2940 /* +1 -- for pre-adjust if a remainder or DIVIDEINT */
2941 /* [Note: unused units do not participate in decUnitAddSub data] */
2942 maxdigits = rhs->digits + reqdigits - 1;
2943 if (lhs->digits > maxdigits)
2944 maxdigits = lhs->digits;
2945 var1units = D2U (maxdigits) + 2;
2946 /* allocate a guard unit above msu1 for REMAINDERNEAR */
2949 if ((var1units + 1) * sizeof (Unit) > sizeof (varbuff))
2951 varalloc = (Unit *) malloc ((var1units + 1) * sizeof (Unit));
2952 if (varalloc == NULL)
2953 { /* hopeless -- abandon */
2954 *status |= DEC_Insufficient_storage;
2957 var1 = varalloc; /* use the allocated space */
2960 /* Extend the lhs and rhs to full long subtraction length. The lhs */
2961 /* is truly extended into the var1 buffer, with 0 padding, so we can */
2962 /* subtract in place. The rhs (var2) has virtual padding */
2963 /* (implemented by decUnitAddSub). */
2964 /* We allocated one guard unit above msu1 for rem=rem+rem in REMAINDERNEAR */
2965 msu1 = var1 + var1units - 1; /* msu of var1 */
2966 source = lhs->lsu + D2U (lhs->digits) - 1; /* msu of input array */
2967 for (target = msu1; source >= lhs->lsu; source--, target--)
2969 for (; target >= var1; target--)
2972 /* rhs (var2) is left-aligned with var1 at the start */
2973 var2ulen = var1units; /* rhs logical length (units) */
2974 var2units = D2U (rhs->digits); /* rhs actual length (units) */
2975 var2 = rhs->lsu; /* -> rhs array */
2976 msu2 = var2 + var2units - 1; /* -> msu of var2 [never changes] */
2977 /* now set up the variables which we'll use for estimating the */
2978 /* multiplication factor. If these variables are not exact, we add */
2979 /* 1 to make sure that we never overestimate the multiplier. */
2980 msu2plus = *msu2; /* it's value .. */
2982 msu2plus++; /* .. +1 if any more */
2983 msu2pair = (eInt) * msu2 * (DECDPUNMAX + 1); /* top two pair .. */
2985 { /* .. [else treat 2nd as 0] */
2986 msu2pair += *(msu2 - 1); /* .. */
2988 msu2pair++; /* .. +1 if any more */
2991 /* Since we are working in units, the units may have leading zeros, */
2992 /* but we calculated the exponent on the assumption that they are */
2993 /* both left-aligned. Adjust the exponent to compensate: add the */
2994 /* number of leading zeros in var1 msu and subtract those in var2 msu. */
2995 /* [We actually do this by counting the digits and negating, as */
2996 /* lead1=DECDPUN-digits1, and similarly for lead2.] */
2997 for (pow = &powers[1]; *msu1 >= *pow; pow++)
2999 for (pow = &powers[1]; *msu2 >= *pow; pow++)
3002 /* Now, if doing an integer divide or remainder, we want to ensure */
3003 /* that the result will be Unit-aligned. To do this, we shift the */
3004 /* var1 accumulator towards least if need be. (It's much easier to */
3005 /* do this now than to reassemble the residue afterwards, if we are */
3006 /* doing a remainder.) Also ensure the exponent is not negative. */
3010 /* save the initial 'false' padding of var1, in digits */
3011 var1initpad = (var1units - D2U (lhs->digits)) * DECDPUN;
3012 /* Determine the shift to do. */
3016 cut = DECDPUN - exponent % DECDPUN;
3017 decShiftToLeast (var1, var1units, cut);
3018 exponent += cut; /* maintain numerical value */
3019 var1initpad -= cut; /* .. and reduce padding */
3020 /* clean any most-significant units we just emptied */
3021 for (u = msu1; cut >= DECDPUN; cut -= DECDPUN, u--)
3026 maxexponent = lhs->exponent - rhs->exponent; /* save */
3027 /* optimization: if the first iteration will just produce 0, */
3028 /* preadjust to skip it [valid for DIVIDE only] */
3031 var2ulen--; /* shift down */
3032 exponent -= DECDPUN; /* update the exponent */
3036 /* ---- start the long-division loops ------------------------------ */
3037 accunits = 0; /* no units accumulated yet */
3038 accdigits = 0; /* .. or digits */
3039 accnext = acc + acclength - 1; /* -> msu of acc [NB: allows digits+1] */
3041 { /* outer forever loop */
3042 thisunit = 0; /* current unit assumed 0 */
3043 /* find the next unit */
3045 { /* inner forever loop */
3046 /* strip leading zero units [from either pre-adjust or from */
3047 /* subtract last time around]. Leave at least one unit. */
3048 for (; *msu1 == 0 && msu1 > var1; msu1--)
3051 if (var1units < var2ulen)
3052 break; /* var1 too low for subtract */
3053 if (var1units == var2ulen)
3054 { /* unit-by-unit compare needed */
3055 /* compare the two numbers, from msu */
3056 Unit *pv1, v2; /* units to compare */
3057 const Unit *pv2; /* units to compare */
3058 pv2 = msu2; /* -> msu */
3059 for (pv1 = msu1;; pv1--, pv2--)
3061 /* v1=*pv1 -- always OK */
3062 v2 = 0; /* assume in padding */
3064 v2 = *pv2; /* in range */
3066 break; /* no longer the same */
3068 break; /* done; leave pv1 as is */
3070 /* here when all inspected or a difference seen */
3072 break; /* var1 too low to subtract */
3074 { /* var1 == var2 */
3075 /* reach here if var1 and var2 are identical; subtraction */
3076 /* would increase digit by one, and the residue will be 0 so */
3077 /* we are done; leave the loop with residue set to 0. */
3078 thisunit++; /* as though subtracted */
3079 *var1 = 0; /* set var1 to 0 */
3080 var1units = 1; /* .. */
3081 break; /* from inner */
3082 } /* var1 == var2 */
3083 /* *pv1>v2. Prepare for real subtraction; the lengths are equal */
3084 /* Estimate the multiplier (there's always a msu1-1)... */
3085 /* Bring in two units of var2 to provide a good estimate. */
3087 (Int) (((eInt) * msu1 * (DECDPUNMAX + 1) +
3088 *(msu1 - 1)) / msu2pair);
3089 } /* lengths the same */
3091 { /* var1units > var2ulen, so subtraction is safe */
3092 /* The var2 msu is one unit towards the lsu of the var1 msu, */
3093 /* so we can only use one unit for var2. */
3095 (Int) (((eInt) * msu1 * (DECDPUNMAX + 1) +
3096 *(msu1 - 1)) / msu2plus);
3099 mult = 1; /* must always be at least 1 */
3100 /* subtraction needed; var1 is > var2 */
3101 thisunit = (Unit) (thisunit + mult); /* accumulate */
3102 /* subtract var1-var2, into var1; only the overlap needs */
3103 /* processing, as we are in place */
3104 shift = var2ulen - var2units;
3106 decDumpAr ('1', &var1[shift], var1units - shift);
3107 decDumpAr ('2', var2, var2units);
3108 printf ("m=%d\n", -mult);
3110 decUnitAddSub (&var1[shift], var1units - shift,
3111 var2, var2units, 0, &var1[shift], -mult);
3113 decDumpAr ('#', &var1[shift], var1units - shift);
3115 /* var1 now probably has leading zeros; these are removed at the */
3116 /* top of the inner loop. */
3119 /* We have the next unit; unless it's a leading zero, add to acc */
3120 if (accunits != 0 || thisunit != 0)
3121 { /* put the unit we got */
3122 *accnext = thisunit; /* store in accumulator */
3123 /* account exactly for the digits we got */
3126 accdigits++; /* at least one */
3127 for (pow = &powers[1]; thisunit >= *pow; pow++)
3131 accdigits += DECDPUN;
3132 accunits++; /* update count */
3133 accnext--; /* ready for next */
3134 if (accdigits > reqdigits)
3135 break; /* we have all we need */
3138 /* if the residue is zero, we're done (unless divide or */
3139 /* divideInteger and we haven't got enough digits yet) */
3140 if (*var1 == 0 && var1units == 1)
3141 { /* residue is 0 */
3142 if (op & (REMAINDER | REMNEAR))
3144 if ((op & DIVIDE) && (exponent <= maxexponent))
3146 /* [drop through if divideInteger] */
3148 /* we've also done enough if calculating remainder or integer */
3149 /* divide and we just did the last ('units') unit */
3150 if (exponent == 0 && !(op & DIVIDE))
3153 /* to get here, var1 is less than var2, so divide var2 by the per- */
3154 /* Unit power of ten and go for the next digit */
3155 var2ulen--; /* shift down */
3156 exponent -= DECDPUN; /* update the exponent */
3159 /* ---- division is complete --------------------------------------- */
3160 /* here: acc has at least reqdigits+1 of good results (or fewer */
3161 /* if early stop), starting at accnext+1 (its lsu) */
3162 /* var1 has any residue at the stopping point */
3163 /* accunits is the number of digits we collected in acc */
3166 accunits = 1; /* show we have one .. */
3167 accdigits = 1; /* .. */
3168 *accnext = 0; /* .. whose value is 0 */
3171 accnext++; /* back to last placed */
3172 /* accnext now -> lowest unit of result */
3174 residue = 0; /* assume no residue */
3177 /* record the presence of any residue, for rounding */
3178 if (*var1 != 0 || var1units > 1)
3182 /* We had an exact division; clean up spurious trailing 0s. */
3183 /* There will be at most DECDPUN-1, from the final multiply, */
3184 /* and then only if the result is non-0 (and even) and the */
3185 /* exponent is 'loose'. */
3187 Unit lsu = *accnext;
3188 if (!(lsu & 0x01) && (lsu != 0))
3190 /* count the trailing zeros */
3193 { /* [will terminate because lsu!=0] */