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 *, decNumber *, decNumber *,
210 decContext *, uByte, uInt *);
211 static void decApplyRound (decNumber *, decContext *, Int, uInt *);
212 static Int decCompare (decNumber * lhs, decNumber * rhs);
213 static decNumber *decCompareOp (decNumber *, decNumber *, decNumber *,
214 decContext *, Flag, uInt *);
215 static void decCopyFit (decNumber *, decNumber *, decContext *,
217 static decNumber *decDivideOp (decNumber *, decNumber *, decNumber *,
218 decContext *, Flag, uInt *);
219 static void decFinalize (decNumber *, decContext *, Int *, uInt *);
220 static Int decGetDigits (Unit *, Int);
222 static Int decGetInt (decNumber *, decContext *);
224 static Int decGetInt (decNumber *);
226 static decNumber *decMultiplyOp (decNumber *, decNumber *, decNumber *,
227 decContext *, uInt *);
228 static decNumber *decNaNs (decNumber *, decNumber *, decNumber *, uInt *);
229 static decNumber *decQuantizeOp (decNumber *, decNumber *, decNumber *,
230 decContext *, Flag, uInt *);
231 static void decSetCoeff (decNumber *, decContext *, Unit *,
233 static void decSetOverflow (decNumber *, decContext *, uInt *);
234 static void decSetSubnormal (decNumber *, decContext *, Int *, uInt *);
235 static Int decShiftToLeast (Unit *, Int, Int);
236 static Int decShiftToMost (Unit *, Int, Int);
237 static void decStatus (decNumber *, uInt, decContext *);
238 static Flag decStrEq (const char *, const char *);
239 static void decToString (decNumber *, char[], Flag);
240 static decNumber *decTrim (decNumber *, Flag, Int *);
241 static Int decUnitAddSub (Unit *, Int, Unit *, Int, Int, Unit *, Int);
242 static Int decUnitCompare (Unit *, Int, Unit *, Int, Int);
245 /* decFinish == decFinalize when no subset arithmetic needed */
246 #define decFinish(a,b,c,d) decFinalize(a,b,c,d)
248 static void decFinish (decNumber *, decContext *, Int *, uInt *);
249 static decNumber *decRoundOperand (decNumber *, decContext *, uInt *);
252 /* Diagnostic macros, etc. */
254 /* Handle malloc/free accounting. If enabled, our accountable routines */
255 /* are used; otherwise the code just goes straight to the system malloc */
256 /* and free routines. */
257 #define malloc(a) decMalloc(a)
258 #define free(a) decFree(a)
259 #define DECFENCE 0x5a /* corruption detector */
260 /* 'Our' malloc and free: */
261 static void *decMalloc (size_t);
262 static void decFree (void *);
263 uInt decAllocBytes = 0; /* count of bytes allocated */
264 /* Note that DECALLOC code only checks for storage buffer overflow. */
265 /* To check for memory leaks, the decAllocBytes variable should be */
266 /* checked to be 0 at appropriate times (e.g., after the test */
267 /* harness completes a set of tests). This checking may be unreliable */
268 /* if the testing is done in a multi-thread environment. */
272 /* Optional operand checking routines. Enabling these means that */
273 /* decNumber and decContext operands to operator routines are checked */
274 /* for correctness. This roughly doubles the execution time of the */
275 /* fastest routines (and adds 600+ bytes), so should not normally be */
276 /* used in 'production'. */
277 #define DECUNUSED (void *)(0xffffffff)
278 static Flag decCheckOperands (decNumber *, decNumber *, decNumber *,
280 static Flag decCheckNumber (decNumber *, decContext *);
283 #if DECTRACE || DECCHECK
284 /* Optional trace/debugging routines. */
285 void decNumberShow (decNumber *); /* displays the components of a number */
286 static void decDumpAr (char, Unit *, Int);
289 /* ================================================================== */
291 /* ================================================================== */
293 /* ------------------------------------------------------------------ */
294 /* to-scientific-string -- conversion to numeric string */
295 /* to-engineering-string -- conversion to numeric string */
297 /* decNumberToString(dn, string); */
298 /* decNumberToEngString(dn, string); */
300 /* dn is the decNumber to convert */
301 /* string is the string where the result will be laid out */
303 /* string must be at least dn->digits+14 characters long */
305 /* No error is possible, and no status can be set. */
306 /* ------------------------------------------------------------------ */
308 decNumberToString (decNumber * dn, char *string)
310 decToString (dn, string, 0);
315 decNumberToEngString (decNumber * dn, char *string)
317 decToString (dn, string, 1);
321 /* ------------------------------------------------------------------ */
322 /* to-number -- conversion from numeric string */
324 /* decNumberFromString -- convert string to decNumber */
325 /* dn -- the number structure to fill */
326 /* chars[] -- the string to convert ('\0' terminated) */
327 /* set -- the context used for processing any error, */
328 /* determining the maximum precision available */
329 /* (set.digits), determining the maximum and minimum */
330 /* exponent (set.emax and set.emin), determining if */
331 /* extended values are allowed, and checking the */
332 /* rounding mode if overflow occurs or rounding is */
335 /* The length of the coefficient and the size of the exponent are */
336 /* checked by this routine, so the correct error (Underflow or */
337 /* Overflow) can be reported or rounding applied, as necessary. */
339 /* If bad syntax is detected, the result will be a quiet NaN. */
340 /* ------------------------------------------------------------------ */
342 decNumberFromString (decNumber * dn, char chars[], decContext * set)
344 Int exponent = 0; /* working exponent [assume 0] */
345 uByte bits = 0; /* working flags [assume +ve] */
346 Unit *res; /* where result will be built */
347 Unit resbuff[D2U (DECBUFFER + 1)]; /* local buffer in case need temporary */
348 Unit *allocres = NULL; /* -> allocated result, iff allocated */
349 Int need; /* units needed for result */
350 Int d = 0; /* count of digits found in decimal part */
351 char *dotchar = NULL; /* where dot was found */
352 char *cfirst; /* -> first character of decimal part */
353 char *last = NULL; /* -> last digit of decimal part */
354 char *firstexp; /* -> first significant exponent digit */
360 Int residue = 0; /* rounding residue */
361 uInt status = 0; /* error code */
364 if (decCheckOperands (DECUNUSED, DECUNUSED, DECUNUSED, set))
365 return decNumberZero (dn);
369 { /* status & malloc protection */
370 c = chars; /* -> input character */
372 { /* handle leading '-' */
377 c++; /* step over leading '+' */
378 /* We're at the start of the number [we think] */
379 cfirst = c; /* save */
382 if (*c >= '0' && *c <= '9')
383 { /* test for Arabic digit */
385 d++; /* count of real digits */
386 continue; /* still in decimal part */
389 break; /* done with decimal part */
390 /* dot: record, check, and ignore */
393 last = NULL; /* indicate bad */
395 } /* .. and go report */
396 dotchar = c; /* offset into decimal part */
400 { /* no decimal digits, or >1 . */
402 /* If subset then infinities and NaNs are not allowed */
405 status = DEC_Conversion_syntax;
406 break; /* all done */
411 /* Infinities and NaNs are possible, here */
412 decNumberZero (dn); /* be optimistic */
413 if (decStrEq (c, "Infinity") || decStrEq (c, "Inf"))
415 dn->bits = bits | DECINF;
416 break; /* all done */
419 { /* a NaN expected */
420 /* 2003.09.10 NaNs are now permitted to have a sign */
421 status = DEC_Conversion_syntax; /* assume the worst */
422 dn->bits = bits | DECNAN; /* assume simple NaN */
423 if (*c == 's' || *c == 'S')
424 { /* looks like an` sNaN */
426 dn->bits = bits | DECSNAN;
428 if (*c != 'n' && *c != 'N')
429 break; /* check caseless "NaN" */
431 if (*c != 'a' && *c != 'A')
434 if (*c != 'n' && *c != 'N')
437 /* now nothing, or nnnn, expected */
438 /* -> start of integer and skip leading 0s [including plain 0] */
439 for (cfirst = c; *cfirst == '0';)
442 { /* "NaN" or "sNaN", maybe with all 0s */
443 status = 0; /* it's good */
446 /* something other than 0s; setup last and d as usual [no dots] */
447 for (c = cfirst;; c++, d++)
449 if (*c < '0' || *c > '9')
450 break; /* test for Arabic digit */
454 break; /* not all digits */
456 break; /* too many digits */
457 /* good; drop through and convert the integer */
459 bits = dn->bits; /* for copy-back */
467 { /* more there; exponent expected... */
468 Flag nege = 0; /* 1=negative exponent */
469 if (*c != 'e' && *c != 'E')
471 status = DEC_Conversion_syntax;
475 /* Found 'e' or 'E' -- now process explicit exponent */
476 /* 1998.07.11: sign no longer required */
477 c++; /* to (expected) sign */
487 status = DEC_Conversion_syntax;
491 for (; *c == '0' && *(c + 1) != '\0';)
492 c++; /* strip insignificant zeros */
493 firstexp = c; /* save exponent digit place */
496 if (*c < '0' || *c > '9')
497 break; /* not a digit */
498 exponent = X10 (exponent) + (Int) * c - (Int) '0';
500 /* if we didn't end on '\0' must not be a digit */
503 status = DEC_Conversion_syntax;
507 /* (this next test must be after the syntax check) */
508 /* if it was too long the exponent may have wrapped, so check */
509 /* carefully and set it to a certain overflow if wrap possible */
510 if (c >= firstexp + 9 + 1)
512 if (c > firstexp + 9 + 1 || *firstexp > '1')
513 exponent = DECNUMMAXE * 2;
514 /* [up to 1999999999 is OK, for example 1E-1000000998] */
517 exponent = -exponent; /* was negative */
519 /* Here when all inspected; syntax is good */
521 /* Handle decimal point... */
522 if (dotchar != NULL && dotchar < last) /* embedded . found, so */
523 exponent = exponent - (last - dotchar); /* .. adjust exponent */
524 /* [we can now ignore the .] */
526 /* strip leading zeros/dot (leave final if all 0's) */
527 for (c = cfirst; c < last; c++)
530 d--; /* 0 stripped */
533 cfirst++; /* step past leader */
537 /* We can now make a rapid exit for zeros if !extended */
538 if (*cfirst == '0' && !set->extended)
540 decNumberZero (dn); /* clean result */
541 break; /* [could be return] */
545 /* OK, the digits string is good. Copy to the decNumber, or to
546 a temporary decNumber if rounding is needed */
547 if (d <= set->digits)
548 res = dn->lsu; /* fits into given decNumber */
550 { /* rounding needed */
551 need = D2U (d); /* units needed */
552 res = resbuff; /* assume use local buffer */
553 if (need * sizeof (Unit) > sizeof (resbuff))
554 { /* too big for local */
555 allocres = (Unit *) malloc (need * sizeof (Unit));
556 if (allocres == NULL)
558 status |= DEC_Insufficient_storage;
564 /* res now -> number lsu, buffer, or allocated storage for Unit array */
566 /* Place the coefficient into the selected Unit array */
568 i = d % DECDPUN; /* digits in top unit */
571 up = res + D2U (d) - 1; /* -> msu */
573 for (c = cfirst;; c++)
574 { /* along the digits */
576 { /* ignore . [don't decrement i] */
581 *up = (Unit) (X10 (*up) + (Int) * c - (Int) '0');
584 continue; /* more for this unit */
586 break; /* just filled the last unit */
593 up = res; /* -> lsu */
594 for (c = last; c >= cfirst; c--)
595 { /* over each character, from least */
597 continue; /* ignore . [don't step b] */
598 *up = (Unit) ((Int) * c - (Int) '0');
604 dn->exponent = exponent;
607 /* if not in number (too long) shorten into the number */
609 decSetCoeff (dn, set, res, d, &residue, &status);
611 /* Finally check for overflow or subnormal and round as needed */
612 decFinalize (dn, set, &residue, &status);
613 /* decNumberShow(dn); */
615 while (0); /* [for break] */
617 if (allocres != NULL)
618 free (allocres); /* drop any storage we used */
620 decStatus (dn, status, set);
624 /* ================================================================== */
626 /* ================================================================== */
628 /* ------------------------------------------------------------------ */
629 /* decNumberAbs -- absolute value operator */
631 /* This computes C = abs(A) */
633 /* res is C, the result. C may be A */
635 /* set is the context */
637 /* C must have space for set->digits digits. */
638 /* ------------------------------------------------------------------ */
639 /* This has the same effect as decNumberPlus unless A is negative, */
640 /* in which case it has the same effect as decNumberMinus. */
641 /* ------------------------------------------------------------------ */
643 decNumberAbs (decNumber * res, decNumber * rhs, decContext * set)
645 decNumber dzero; /* for 0 */
646 uInt status = 0; /* accumulator */
649 if (decCheckOperands (res, DECUNUSED, rhs, set))
653 decNumberZero (&dzero); /* set 0 */
654 dzero.exponent = rhs->exponent; /* [no coefficient expansion] */
655 decAddOp (res, &dzero, rhs, set, (uByte) (rhs->bits & DECNEG), &status);
657 decStatus (res, status, set);
661 /* ------------------------------------------------------------------ */
662 /* decNumberAdd -- add two Numbers */
664 /* This computes C = A + B */
666 /* res is C, the result. C may be A and/or B (e.g., X=X+X) */
669 /* set is the context */
671 /* C must have space for set->digits digits. */
672 /* ------------------------------------------------------------------ */
673 /* This just calls the routine shared with Subtract */
675 decNumberAdd (decNumber * res, decNumber * lhs, decNumber * rhs,
678 uInt status = 0; /* accumulator */
679 decAddOp (res, lhs, rhs, set, 0, &status);
681 decStatus (res, status, set);
685 /* ------------------------------------------------------------------ */
686 /* decNumberCompare -- compare two Numbers */
688 /* This computes C = A ? B */
690 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
693 /* set is the context */
695 /* C must have space for one digit. */
696 /* ------------------------------------------------------------------ */
698 decNumberCompare (decNumber * res, decNumber * lhs, decNumber * rhs,
701 uInt status = 0; /* accumulator */
702 decCompareOp (res, lhs, rhs, set, COMPARE, &status);
704 decStatus (res, status, set);
708 /* ------------------------------------------------------------------ */
709 /* decNumberDivide -- divide one number by another */
711 /* This computes C = A / B */
713 /* res is C, the result. C may be A and/or B (e.g., X=X/X) */
716 /* set is the context */
718 /* C must have space for set->digits digits. */
719 /* ------------------------------------------------------------------ */
721 decNumberDivide (decNumber * res, decNumber * lhs,
722 decNumber * rhs, decContext * set)
724 uInt status = 0; /* accumulator */
725 decDivideOp (res, lhs, rhs, set, DIVIDE, &status);
727 decStatus (res, status, set);
731 /* ------------------------------------------------------------------ */
732 /* decNumberDivideInteger -- divide and return integer quotient */
734 /* This computes C = A # B, where # is the integer divide operator */
736 /* res is C, the result. C may be A and/or B (e.g., X=X#X) */
739 /* set is the context */
741 /* C must have space for set->digits digits. */
742 /* ------------------------------------------------------------------ */
744 decNumberDivideInteger (decNumber * res, decNumber * lhs,
745 decNumber * rhs, decContext * set)
747 uInt status = 0; /* accumulator */
748 decDivideOp (res, lhs, rhs, set, DIVIDEINT, &status);
750 decStatus (res, status, set);
754 /* ------------------------------------------------------------------ */
755 /* decNumberMax -- compare two Numbers and return the maximum */
757 /* This computes C = A ? B, returning the maximum or A if equal */
759 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
762 /* set is the context */
764 /* C must have space for set->digits digits. */
765 /* ------------------------------------------------------------------ */
767 decNumberMax (decNumber * res, decNumber * lhs, decNumber * rhs,
770 uInt status = 0; /* accumulator */
771 decCompareOp (res, lhs, rhs, set, COMPMAX, &status);
773 decStatus (res, status, set);
777 /* ------------------------------------------------------------------ */
778 /* decNumberMin -- compare two Numbers and return the minimum */
780 /* This computes C = A ? B, returning the minimum or A if equal */
782 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
785 /* set is the context */
787 /* C must have space for set->digits digits. */
788 /* ------------------------------------------------------------------ */
790 decNumberMin (decNumber * res, decNumber * lhs, decNumber * rhs,
793 uInt status = 0; /* accumulator */
794 decCompareOp (res, lhs, rhs, set, COMPMIN, &status);
796 decStatus (res, status, set);
800 /* ------------------------------------------------------------------ */
801 /* decNumberMinus -- prefix minus operator */
803 /* This computes C = 0 - A */
805 /* res is C, the result. C may be A */
807 /* set is the context */
809 /* C must have space for set->digits digits. */
810 /* ------------------------------------------------------------------ */
811 /* We simply use AddOp for the subtract, which will do the necessary. */
812 /* ------------------------------------------------------------------ */
814 decNumberMinus (decNumber * res, decNumber * rhs, decContext * set)
817 uInt status = 0; /* accumulator */
820 if (decCheckOperands (res, DECUNUSED, rhs, set))
824 decNumberZero (&dzero); /* make 0 */
825 dzero.exponent = rhs->exponent; /* [no coefficient expansion] */
826 decAddOp (res, &dzero, rhs, set, DECNEG, &status);
828 decStatus (res, status, set);
832 /* ------------------------------------------------------------------ */
833 /* decNumberPlus -- prefix plus operator */
835 /* This computes C = 0 + A */
837 /* res is C, the result. C may be A */
839 /* set is the context */
841 /* C must have space for set->digits digits. */
842 /* ------------------------------------------------------------------ */
843 /* We simply use AddOp; Add will take fast path after preparing A. */
844 /* Performance is a concern here, as this routine is often used to */
845 /* check operands and apply rounding and overflow/underflow testing. */
846 /* ------------------------------------------------------------------ */
848 decNumberPlus (decNumber * res, decNumber * rhs, decContext * set)
851 uInt status = 0; /* accumulator */
854 if (decCheckOperands (res, DECUNUSED, rhs, set))
858 decNumberZero (&dzero); /* make 0 */
859 dzero.exponent = rhs->exponent; /* [no coefficient expansion] */
860 decAddOp (res, &dzero, rhs, set, 0, &status);
862 decStatus (res, status, set);
866 /* ------------------------------------------------------------------ */
867 /* decNumberMultiply -- multiply two Numbers */
869 /* This computes C = A x B */
871 /* res is C, the result. C may be A and/or B (e.g., X=X+X) */
874 /* set is the context */
876 /* C must have space for set->digits digits. */
877 /* ------------------------------------------------------------------ */
879 decNumberMultiply (decNumber * res, decNumber * lhs,
880 decNumber * rhs, decContext * set)
882 uInt status = 0; /* accumulator */
883 decMultiplyOp (res, lhs, rhs, set, &status);
885 decStatus (res, status, set);
889 /* ------------------------------------------------------------------ */
890 /* decNumberNormalize -- remove trailing zeros */
892 /* This computes C = 0 + A, and normalizes the result */
894 /* res is C, the result. C may be A */
896 /* set is the context */
898 /* C must have space for set->digits digits. */
899 /* ------------------------------------------------------------------ */
901 decNumberNormalize (decNumber * res, decNumber * rhs, decContext * set)
903 decNumber *allocrhs = NULL; /* non-NULL if rounded rhs allocated */
904 uInt status = 0; /* as usual */
905 Int residue = 0; /* as usual */
906 Int dropped; /* work */
909 if (decCheckOperands (res, DECUNUSED, rhs, set))
914 { /* protect allocated storage */
918 /* reduce operand and set lostDigits status, as needed */
919 if (rhs->digits > set->digits)
921 allocrhs = decRoundOperand (rhs, set, &status);
922 if (allocrhs == NULL)
928 /* [following code does not require input rounding] */
930 /* specials copy through, except NaNs need care */
931 if (decNumberIsNaN (rhs))
933 decNaNs (res, rhs, NULL, &status);
937 /* reduce result to the requested length and copy to result */
938 decCopyFit (res, rhs, set, &residue, &status); /* copy & round */
939 decFinish (res, set, &residue, &status); /* cleanup/set flags */
940 decTrim (res, 1, &dropped); /* normalize in place */
942 while (0); /* end protected */
944 if (allocrhs != NULL)
945 free (allocrhs); /* .. */
947 decStatus (res, status, set); /* then report status */
951 /* ------------------------------------------------------------------ */
952 /* decNumberPower -- raise a number to an integer power */
954 /* This computes C = A ** B */
956 /* res is C, the result. C may be A and/or B (e.g., X=X**X) */
959 /* set is the context */
961 /* C must have space for set->digits digits. */
963 /* Specification restriction: abs(n) must be <=999999999 */
964 /* ------------------------------------------------------------------ */
966 decNumberPower (decNumber * res, decNumber * lhs,
967 decNumber * rhs, decContext * set)
969 decNumber *alloclhs = NULL; /* non-NULL if rounded lhs allocated */
970 decNumber *allocrhs = NULL; /* .., rhs */
971 decNumber *allocdac = NULL; /* -> allocated acc buffer, iff used */
972 decNumber *inrhs = rhs; /* save original rhs */
973 Int reqdigits = set->digits; /* requested DIGITS */
974 Int n; /* RHS in binary */
977 Int dropped; /* .. */
979 uInt needbytes; /* buffer size needed */
980 Flag seenbit; /* seen a bit while powering */
981 Int residue = 0; /* rounding residue */
982 uInt status = 0; /* accumulator */
983 uByte bits = 0; /* result sign if errors */
984 decContext workset; /* working context */
985 decNumber dnOne; /* work value 1... */
986 /* local accumulator buffer [a decNumber, with digits+elength+1 digits] */
987 uByte dacbuff[sizeof (decNumber) + D2U (DECBUFFER + 9) * sizeof (Unit)];
988 /* same again for possible 1/lhs calculation */
989 uByte lhsbuff[sizeof (decNumber) + D2U (DECBUFFER + 9) * sizeof (Unit)];
990 decNumber *dac = (decNumber *) dacbuff; /* -> result accumulator */
993 if (decCheckOperands (res, lhs, rhs, set))
998 { /* protect allocated storage */
1002 /* reduce operands and set lostDigits status, as needed */
1003 if (lhs->digits > reqdigits)
1005 alloclhs = decRoundOperand (lhs, set, &status);
1006 if (alloclhs == NULL)
1010 /* rounding won't affect the result, but we might signal lostDigits */
1011 /* as well as the error for non-integer [x**y would need this too] */
1012 if (rhs->digits > reqdigits)
1014 allocrhs = decRoundOperand (rhs, set, &status);
1015 if (allocrhs == NULL)
1021 /* [following code does not require input rounding] */
1023 /* handle rhs Infinity */
1024 if (decNumberIsInfinite (rhs))
1026 status |= DEC_Invalid_operation; /* bad */
1030 if ((lhs->bits | rhs->bits) & (DECNAN | DECSNAN))
1032 decNaNs (res, lhs, rhs, &status);
1036 /* Original rhs must be an integer that fits and is in range */
1038 n = decGetInt (inrhs, set);
1040 n = decGetInt (inrhs);
1042 if (n == BADINT || n > 999999999 || n < -999999999)
1044 status |= DEC_Invalid_operation;
1049 n = -n; /* use the absolute value */
1051 if (decNumberIsNegative (lhs) /* -x .. */
1052 && (n & 0x00000001))
1053 bits = DECNEG; /* .. to an odd power */
1055 /* handle LHS infinity */
1056 if (decNumberIsInfinite (lhs))
1057 { /* [NaNs already handled] */
1058 uByte rbits = rhs->bits; /* save */
1059 decNumberZero (res);
1061 *res->lsu = 1; /* [-]Inf**0 => 1 */
1064 if (!(rbits & DECNEG))
1065 bits |= DECINF; /* was not a **-n */
1066 /* [otherwise will be 0 or -0] */
1072 /* clone the context */
1073 workset = *set; /* copy all fields */
1074 /* calculate the working DIGITS */
1075 workset.digits = reqdigits + (inrhs->digits + inrhs->exponent) + 1;
1076 /* it's an error if this is more than we can handle */
1077 if (workset.digits > DECNUMMAXP)
1079 status |= DEC_Invalid_operation;
1083 /* workset.digits is the count of digits for the accumulator we need */
1084 /* if accumulator is too long for local storage, then allocate */
1086 sizeof (decNumber) + (D2U (workset.digits) - 1) * sizeof (Unit);
1087 /* [needbytes also used below if 1/lhs needed] */
1088 if (needbytes > sizeof (dacbuff))
1090 allocdac = (decNumber *) malloc (needbytes);
1091 if (allocdac == NULL)
1092 { /* hopeless -- abandon */
1093 status |= DEC_Insufficient_storage;
1096 dac = allocdac; /* use the allocated space */
1098 decNumberZero (dac); /* acc=1 */
1099 *dac->lsu = 1; /* .. */
1102 { /* x**0 is usually 1 */
1103 /* 0**0 is bad unless subset, when it becomes 1 */
1109 status |= DEC_Invalid_operation;
1111 decNumberCopy (res, dac); /* copy the 1 */
1115 /* if a negative power we'll need the constant 1, and if not subset */
1116 /* we'll invert the lhs now rather than inverting the result later */
1117 if (decNumberIsNegative (rhs))
1118 { /* was a **-n [hence digits>0] */
1119 decNumberCopy (&dnOne, dac); /* dnOne=1; [needed now or later] */
1122 { /* need to calculate 1/lhs */
1124 /* divide lhs into 1, putting result in dac [dac=1/dac] */
1125 decDivideOp (dac, &dnOne, lhs, &workset, DIVIDE, &status);
1126 if (alloclhs != NULL)
1128 free (alloclhs); /* done with intermediate */
1129 alloclhs = NULL; /* indicate freed */
1131 /* now locate or allocate space for the inverted lhs */
1132 if (needbytes > sizeof (lhsbuff))
1134 alloclhs = (decNumber *) malloc (needbytes);
1135 if (alloclhs == NULL)
1136 { /* hopeless -- abandon */
1137 status |= DEC_Insufficient_storage;
1140 lhs = alloclhs; /* use the allocated space */
1143 lhs = (decNumber *) lhsbuff; /* use stack storage */
1144 /* [lhs now points to buffer or allocated storage] */
1145 decNumberCopy (lhs, dac); /* copy the 1/lhs */
1146 decNumberCopy (dac, &dnOne); /* restore acc=1 */
1152 /* Raise-to-the-power loop... */
1153 seenbit = 0; /* set once we've seen a 1-bit */
1155 { /* for each bit [top bit ignored] */
1156 /* abandon if we have had overflow or terminal underflow */
1157 if (status & (DEC_Overflow | DEC_Underflow))
1158 { /* interesting? */
1159 if (status & DEC_Overflow || ISZERO (dac))
1162 /* [the following two lines revealed an optimizer bug in a C++ */
1163 /* compiler, with symptom: 5**3 -> 25, when n=n+n was used] */
1164 n = n << 1; /* move next bit to testable position */
1166 { /* top bit is set */
1167 seenbit = 1; /* OK, we're off */
1168 decMultiplyOp (dac, dac, lhs, &workset, &status); /* dac=dac*x */
1171 break; /* that was the last bit */
1173 continue; /* we don't have to square 1 */
1174 decMultiplyOp (dac, dac, dac, &workset, &status); /* dac=dac*dac [square] */
1175 } /*i *//* 32 bits */
1177 /* complete internal overflow or underflow processing */
1178 if (status & (DEC_Overflow | DEC_Subnormal))
1181 /* If subset, and power was negative, reverse the kind of -erflow */
1182 /* [1/x not yet done] */
1183 if (!set->extended && decNumberIsNegative (rhs))
1185 if (status & DEC_Overflow)
1186 status ^= DEC_Overflow | DEC_Underflow | DEC_Subnormal;
1188 { /* trickier -- Underflow may or may not be set */
1189 status &= ~(DEC_Underflow | DEC_Subnormal); /* [one or both] */
1190 status |= DEC_Overflow;
1194 dac->bits = (dac->bits & ~DECNEG) | bits; /* force correct sign */
1195 /* round subnormals [to set.digits rather than workset.digits] */
1196 /* or set overflow result similarly as required */
1197 decFinalize (dac, set, &residue, &status);
1198 decNumberCopy (res, dac); /* copy to result (is now OK length) */
1203 if (!set->extended && /* subset math */
1204 decNumberIsNegative (rhs))
1205 { /* was a **-n [hence digits>0] */
1206 /* so divide result into 1 [dac=1/dac] */
1207 decDivideOp (dac, &dnOne, dac, &workset, DIVIDE, &status);
1211 /* reduce result to the requested length and copy to result */
1212 decCopyFit (res, dac, set, &residue, &status);
1213 decFinish (res, set, &residue, &status); /* final cleanup */
1216 decTrim (res, 0, &dropped); /* trailing zeros */
1219 while (0); /* end protected */
1221 if (allocdac != NULL)
1222 free (allocdac); /* drop any storage we used */
1223 if (allocrhs != NULL)
1224 free (allocrhs); /* .. */
1225 if (alloclhs != NULL)
1226 free (alloclhs); /* .. */
1228 decStatus (res, status, set);
1232 /* ------------------------------------------------------------------ */
1233 /* decNumberQuantize -- force exponent to requested value */
1235 /* This computes C = op(A, B), where op adjusts the coefficient */
1236 /* of C (by rounding or shifting) such that the exponent (-scale) */
1237 /* of C has exponent of B. The numerical value of C will equal A, */
1238 /* except for the effects of any rounding that occurred. */
1240 /* res is C, the result. C may be A or B */
1241 /* lhs is A, the number to adjust */
1242 /* rhs is B, the number with exponent to match */
1243 /* set is the context */
1245 /* C must have space for set->digits digits. */
1247 /* Unless there is an error or the result is infinite, the exponent */
1248 /* after the operation is guaranteed to be equal to that of B. */
1249 /* ------------------------------------------------------------------ */
1251 decNumberQuantize (decNumber * res, decNumber * lhs,
1252 decNumber * rhs, decContext * set)
1254 uInt status = 0; /* accumulator */
1255 decQuantizeOp (res, lhs, rhs, set, 1, &status);
1257 decStatus (res, status, set);
1261 /* ------------------------------------------------------------------ */
1262 /* decNumberRescale -- force exponent to requested value */
1264 /* This computes C = op(A, B), where op adjusts the coefficient */
1265 /* of C (by rounding or shifting) such that the exponent (-scale) */
1266 /* of C has the value B. The numerical value of C will equal A, */
1267 /* except for the effects of any rounding that occurred. */
1269 /* res is C, the result. C may be A or B */
1270 /* lhs is A, the number to adjust */
1271 /* rhs is B, the requested exponent */
1272 /* set is the context */
1274 /* C must have space for set->digits digits. */
1276 /* Unless there is an error or the result is infinite, the exponent */
1277 /* after the operation is guaranteed to be equal to B. */
1278 /* ------------------------------------------------------------------ */
1280 decNumberRescale (decNumber * res, decNumber * lhs,
1281 decNumber * rhs, decContext * set)
1283 uInt status = 0; /* accumulator */
1284 decQuantizeOp (res, lhs, rhs, set, 0, &status);
1286 decStatus (res, status, set);
1290 /* ------------------------------------------------------------------ */
1291 /* decNumberRemainder -- divide and return remainder */
1293 /* This computes C = A % B */
1295 /* res is C, the result. C may be A and/or B (e.g., X=X%X) */
1298 /* set is the context */
1300 /* C must have space for set->digits digits. */
1301 /* ------------------------------------------------------------------ */
1303 decNumberRemainder (decNumber * res, decNumber * lhs,
1304 decNumber * rhs, decContext * set)
1306 uInt status = 0; /* accumulator */
1307 decDivideOp (res, lhs, rhs, set, REMAINDER, &status);
1309 decStatus (res, status, set);
1313 /* ------------------------------------------------------------------ */
1314 /* decNumberRemainderNear -- divide and return remainder from nearest */
1316 /* This computes C = A % B, where % is the IEEE remainder operator */
1318 /* res is C, the result. C may be A and/or B (e.g., X=X%X) */
1321 /* set is the context */
1323 /* C must have space for set->digits digits. */
1324 /* ------------------------------------------------------------------ */
1326 decNumberRemainderNear (decNumber * res, decNumber * lhs,
1327 decNumber * rhs, decContext * set)
1329 uInt status = 0; /* accumulator */
1330 decDivideOp (res, lhs, rhs, set, REMNEAR, &status);
1332 decStatus (res, status, set);
1336 /* ------------------------------------------------------------------ */
1337 /* decNumberSameQuantum -- test for equal exponents */
1339 /* res is the result number, which will contain either 0 or 1 */
1340 /* lhs is a number to test */
1341 /* rhs is the second (usually a pattern) */
1343 /* No errors are possible and no context is needed. */
1344 /* ------------------------------------------------------------------ */
1346 decNumberSameQuantum (decNumber * res, decNumber * lhs, decNumber * rhs)
1348 uByte merged; /* merged flags */
1349 Unit ret = 0; /* return value */
1352 if (decCheckOperands (res, lhs, rhs, DECUNUSED))
1356 merged = (lhs->bits | rhs->bits) & DECSPECIAL;
1359 if (decNumberIsNaN (lhs) && decNumberIsNaN (rhs))
1361 else if (decNumberIsInfinite (lhs) && decNumberIsInfinite (rhs))
1363 /* [anything else with a special gives 0] */
1365 else if (lhs->exponent == rhs->exponent)
1368 decNumberZero (res); /* OK to overwrite an operand */
1373 /* ------------------------------------------------------------------ */
1374 /* decNumberSquareRoot -- square root operator */
1376 /* This computes C = squareroot(A) */
1378 /* res is C, the result. C may be A */
1380 /* set is the context; note that rounding mode has no effect */
1382 /* C must have space for set->digits digits. */
1383 /* ------------------------------------------------------------------ */
1384 /* This uses the following varying-precision algorithm in: */
1386 /* Properly Rounded Variable Precision Square Root, T. E. Hull and */
1387 /* A. Abrham, ACM Transactions on Mathematical Software, Vol 11 #3, */
1388 /* pp229-237, ACM, September 1985. */
1390 /* % [Reformatted original Numerical Turing source code follows.] */
1391 /* function sqrt(x : real) : real */
1392 /* % sqrt(x) returns the properly rounded approximation to the square */
1393 /* % root of x, in the precision of the calling environment, or it */
1394 /* % fails if x < 0. */
1395 /* % t e hull and a abrham, august, 1984 */
1396 /* if x <= 0 then */
1403 /* var f := setexp(x, 0) % fraction part of x [0.1 <= x < 1] */
1404 /* var e := getexp(x) % exponent part of x */
1405 /* var approx : real */
1406 /* if e mod 2 = 0 then */
1407 /* approx := .259 + .819 * f % approx to root of f */
1409 /* f := f/l0 % adjustments */
1410 /* e := e + 1 % for odd */
1411 /* approx := .0819 + 2.59 * f % exponent */
1415 /* const maxp := currentprecision + 2 */
1417 /* p := min(2*p - 2, maxp) % p = 4,6,10, . . . , maxp */
1419 /* approx := .5 * (approx + f/approx) */
1420 /* exit when p = maxp */
1423 /* % approx is now within 1 ulp of the properly rounded square root */
1424 /* % of f; to ensure proper rounding, compare squares of (approx - */
1425 /* % l/2 ulp) and (approx + l/2 ulp) with f. */
1426 /* p := currentprecision */
1428 /* precision p + 2 */
1429 /* const approxsubhalf := approx - setexp(.5, -p) */
1430 /* if mulru(approxsubhalf, approxsubhalf) > f then */
1431 /* approx := approx - setexp(.l, -p + 1) */
1433 /* const approxaddhalf := approx + setexp(.5, -p) */
1434 /* if mulrd(approxaddhalf, approxaddhalf) < f then */
1435 /* approx := approx + setexp(.l, -p + 1) */
1439 /* result setexp(approx, e div 2) % fix exponent */
1441 /* ------------------------------------------------------------------ */
1443 decNumberSquareRoot (decNumber * res, decNumber * rhs, decContext * set)
1445 decContext workset, approxset; /* work contexts */
1446 decNumber dzero; /* used for constant zero */
1447 Int maxp = set->digits + 2; /* largest working precision */
1448 Int residue = 0; /* rounding residue */
1449 uInt status = 0, ignore = 0; /* status accumulators */
1450 Int exp; /* working exponent */
1451 Int ideal; /* ideal (preferred) exponent */
1452 uInt needbytes; /* work */
1453 Int dropped; /* .. */
1455 decNumber *allocrhs = NULL; /* non-NULL if rounded rhs allocated */
1456 /* buffer for f [needs +1 in case DECBUFFER 0] */
1457 uByte buff[sizeof (decNumber) + (D2U (DECBUFFER + 1) - 1) * sizeof (Unit)];
1458 /* buffer for a [needs +2 to match maxp] */
1459 uByte bufa[sizeof (decNumber) + (D2U (DECBUFFER + 2) - 1) * sizeof (Unit)];
1460 /* buffer for temporary, b [must be same size as a] */
1461 uByte bufb[sizeof (decNumber) + (D2U (DECBUFFER + 2) - 1) * sizeof (Unit)];
1462 decNumber *allocbuff = NULL; /* -> allocated buff, iff allocated */
1463 decNumber *allocbufa = NULL; /* -> allocated bufa, iff allocated */
1464 decNumber *allocbufb = NULL; /* -> allocated bufb, iff allocated */
1465 decNumber *f = (decNumber *) buff; /* reduced fraction */
1466 decNumber *a = (decNumber *) bufa; /* approximation to result */
1467 decNumber *b = (decNumber *) bufb; /* intermediate result */
1468 /* buffer for temporary variable, up to 3 digits */
1469 uByte buft[sizeof (decNumber) + (D2U (3) - 1) * sizeof (Unit)];
1470 decNumber *t = (decNumber *) buft; /* up-to-3-digit constant or work */
1473 if (decCheckOperands (res, DECUNUSED, rhs, set))
1478 { /* protect allocated storage */
1482 /* reduce operand and set lostDigits status, as needed */
1483 if (rhs->digits > set->digits)
1485 allocrhs = decRoundOperand (rhs, set, &status);
1486 if (allocrhs == NULL)
1488 /* [Note: 'f' allocation below could reuse this buffer if */
1489 /* used, but as this is rare we keep them separate for clarity.] */
1494 /* [following code does not require input rounding] */
1496 /* handle infinities and NaNs */
1497 if (rhs->bits & DECSPECIAL)
1499 if (decNumberIsInfinite (rhs))
1501 if (decNumberIsNegative (rhs))
1502 status |= DEC_Invalid_operation;
1504 decNumberCopy (res, rhs); /* +Infinity */
1507 decNaNs (res, rhs, NULL, &status); /* a NaN */
1511 /* calculate the ideal (preferred) exponent [floor(exp/2)] */
1512 /* [We would like to write: ideal=rhs->exponent>>1, but this */
1513 /* generates a compiler warning. Generated code is the same.] */
1514 ideal = (rhs->exponent & ~1) / 2; /* target */
1519 decNumberCopy (res, rhs); /* could be 0 or -0 */
1520 res->exponent = ideal; /* use the ideal [safe] */
1524 /* any other -x is an oops */
1525 if (decNumberIsNegative (rhs))
1527 status |= DEC_Invalid_operation;
1531 /* we need space for three working variables */
1532 /* f -- the same precision as the RHS, reduced to 0.01->0.99... */
1533 /* a -- Hull's approx -- precision, when assigned, is */
1534 /* currentprecision (we allow +2 for use as temporary) */
1535 /* b -- intermediate temporary result */
1536 /* if any is too long for local storage, then allocate */
1538 sizeof (decNumber) + (D2U (rhs->digits) - 1) * sizeof (Unit);
1539 if (needbytes > sizeof (buff))
1541 allocbuff = (decNumber *) malloc (needbytes);
1542 if (allocbuff == NULL)
1543 { /* hopeless -- abandon */
1544 status |= DEC_Insufficient_storage;
1547 f = allocbuff; /* use the allocated space */
1549 /* a and b both need to be able to hold a maxp-length number */
1550 needbytes = sizeof (decNumber) + (D2U (maxp) - 1) * sizeof (Unit);
1551 if (needbytes > sizeof (bufa))
1552 { /* [same applies to b] */
1553 allocbufa = (decNumber *) malloc (needbytes);
1554 allocbufb = (decNumber *) malloc (needbytes);
1555 if (allocbufa == NULL || allocbufb == NULL)
1557 status |= DEC_Insufficient_storage;
1560 a = allocbufa; /* use the allocated space */
1561 b = allocbufb; /* .. */
1564 /* copy rhs -> f, save exponent, and reduce so 0.1 <= f < 1 */
1565 decNumberCopy (f, rhs);
1566 exp = f->exponent + f->digits; /* adjusted to Hull rules */
1567 f->exponent = -(f->digits); /* to range */
1569 /* set up working contexts (the second is used for Numerical */
1570 /* Turing assignment) */
1571 decContextDefault (&workset, DEC_INIT_DECIMAL64);
1572 decContextDefault (&approxset, DEC_INIT_DECIMAL64);
1573 approxset.digits = set->digits; /* approx's length */
1575 /* [Until further notice, no error is possible and status bits */
1576 /* (Rounded, etc.) should be ignored, not accumulated.] */
1578 /* Calculate initial approximation, and allow for odd exponent */
1579 workset.digits = set->digits; /* p for initial calculation */
1585 { /* even exponent */
1586 /* Set t=0.259, a=0.819 */
1607 { /* odd exponent */
1608 /* Set t=0.0819, a=2.59 */
1609 f->exponent--; /* f=f/10 */
1630 decMultiplyOp (a, a, f, &workset, &ignore); /* a=a*f */
1631 decAddOp (a, a, t, &workset, 0, &ignore); /* ..+t */
1632 /* [a is now the initial approximation for sqrt(f), calculated with */
1633 /* currentprecision, which is also a's precision.] */
1635 /* the main calculation loop */
1636 decNumberZero (&dzero); /* make 0 */
1637 decNumberZero (t); /* set t = 0.5 */
1638 t->lsu[0] = 5; /* .. */
1639 t->exponent = -1; /* .. */
1640 workset.digits = 3; /* initial p */
1643 /* set p to min(2*p - 2, maxp) [hence 3; or: 4, 6, 10, ... , maxp] */
1644 workset.digits = workset.digits * 2 - 2;
1645 if (workset.digits > maxp)
1646 workset.digits = maxp;
1647 /* a = 0.5 * (a + f/a) */
1648 /* [calculated at p then rounded to currentprecision] */
1649 decDivideOp (b, f, a, &workset, DIVIDE, &ignore); /* b=f/a */
1650 decAddOp (b, b, a, &workset, 0, &ignore); /* b=b+a */
1651 decMultiplyOp (a, b, t, &workset, &ignore); /* a=b*0.5 */
1652 /* assign to approx [round to length] */
1653 decAddOp (a, &dzero, a, &approxset, 0, &ignore);
1654 if (workset.digits == maxp)
1655 break; /* just did final */
1658 /* a is now at currentprecision and within 1 ulp of the properly */
1659 /* rounded square root of f; to ensure proper rounding, compare */
1660 /* squares of (a - l/2 ulp) and (a + l/2 ulp) with f. */
1661 /* Here workset.digits=maxp and t=0.5 */
1662 workset.digits--; /* maxp-1 is OK now */
1663 t->exponent = -set->digits - 1; /* make 0.5 ulp */
1664 decNumberCopy (b, a);
1665 decAddOp (b, b, t, &workset, DECNEG, &ignore); /* b = a - 0.5 ulp */
1666 workset.round = DEC_ROUND_UP;
1667 decMultiplyOp (b, b, b, &workset, &ignore); /* b = mulru(b, b) */
1668 decCompareOp (b, f, b, &workset, COMPARE, &ignore); /* b ? f, reversed */
1669 if (decNumberIsNegative (b))
1670 { /* f < b [i.e., b > f] */
1671 /* this is the more common adjustment, though both are rare */
1672 t->exponent++; /* make 1.0 ulp */
1673 t->lsu[0] = 1; /* .. */
1674 decAddOp (a, a, t, &workset, DECNEG, &ignore); /* a = a - 1 ulp */
1675 /* assign to approx [round to length] */
1676 decAddOp (a, &dzero, a, &approxset, 0, &ignore);
1680 decNumberCopy (b, a);
1681 decAddOp (b, b, t, &workset, 0, &ignore); /* b = a + 0.5 ulp */
1682 workset.round = DEC_ROUND_DOWN;
1683 decMultiplyOp (b, b, b, &workset, &ignore); /* b = mulrd(b, b) */
1684 decCompareOp (b, b, f, &workset, COMPARE, &ignore); /* b ? f */
1685 if (decNumberIsNegative (b))
1687 t->exponent++; /* make 1.0 ulp */
1688 t->lsu[0] = 1; /* .. */
1689 decAddOp (a, a, t, &workset, 0, &ignore); /* a = a + 1 ulp */
1690 /* assign to approx [round to length] */
1691 decAddOp (a, &dzero, a, &approxset, 0, &ignore);
1694 /* [no errors are possible in the above, and rounding/inexact during */
1695 /* estimation are irrelevant, so status was not accumulated] */
1697 /* Here, 0.1 <= a < 1 [Hull] */
1698 a->exponent += exp / 2; /* set correct exponent */
1700 /* Process Subnormals */
1701 decFinalize (a, set, &residue, &status);
1703 /* count dropable zeros [after any subnormal rounding] */
1704 decNumberCopy (b, a);
1705 decTrim (b, 1, &dropped); /* [drops trailing zeros] */
1707 /* Finally set Inexact and Rounded. The answer can only be exact if */
1708 /* it is short enough so that squaring it could fit in set->digits, */
1709 /* so this is the only (relatively rare) time we have to check */
1711 if (b->digits * 2 - 1 > set->digits)
1713 status |= DEC_Inexact | DEC_Rounded;
1716 { /* could be exact/unrounded */
1717 uInt mstatus = 0; /* local status */
1718 decMultiplyOp (b, b, b, &workset, &mstatus); /* try the multiply */
1720 { /* result won't fit */
1721 status |= DEC_Inexact | DEC_Rounded;
1725 decCompareOp (t, b, rhs, &workset, COMPARE, &mstatus); /* b ? rhs */
1728 status |= DEC_Inexact | DEC_Rounded;
1732 /* here, dropped is the count of trailing zeros in 'a' */
1733 /* use closest exponent to ideal... */
1734 Int todrop = ideal - a->exponent; /* most we can drop */
1737 { /* ideally would add 0s */
1738 status |= DEC_Rounded;
1742 if (dropped < todrop)
1743 todrop = dropped; /* clamp to those available */
1745 { /* OK, some to drop */
1746 decShiftToLeast (a->lsu, D2U (a->digits), todrop);
1747 a->exponent += todrop; /* maintain numerical value */
1748 a->digits -= todrop; /* new length */
1754 decNumberCopy (res, a); /* assume this is the result */
1756 while (0); /* end protected */
1758 if (allocbuff != NULL)
1759 free (allocbuff); /* drop any storage we used */
1760 if (allocbufa != NULL)
1761 free (allocbufa); /* .. */
1762 if (allocbufb != NULL)
1763 free (allocbufb); /* .. */
1764 if (allocrhs != NULL)
1765 free (allocrhs); /* .. */
1767 decStatus (res, status, set); /* then report status */
1771 /* ------------------------------------------------------------------ */
1772 /* decNumberSubtract -- subtract two Numbers */
1774 /* This computes C = A - B */
1776 /* res is C, the result. C may be A and/or B (e.g., X=X-X) */
1779 /* set is the context */
1781 /* C must have space for set->digits digits. */
1782 /* ------------------------------------------------------------------ */
1784 decNumberSubtract (decNumber * res, decNumber * lhs,
1785 decNumber * rhs, decContext * set)
1787 uInt status = 0; /* accumulator */
1789 decAddOp (res, lhs, rhs, set, DECNEG, &status);
1791 decStatus (res, status, set);
1795 /* ------------------------------------------------------------------ */
1796 /* decNumberToIntegralValue -- round-to-integral-value */
1798 /* res is the result */
1799 /* rhs is input number */
1800 /* set is the context */
1802 /* res must have space for any value of rhs. */
1804 /* This implements the IEEE special operator and therefore treats */
1805 /* special values as valid, and also never sets Inexact. For finite */
1806 /* numbers it returns rescale(rhs, 0) if rhs->exponent is <0. */
1807 /* Otherwise the result is rhs (so no error is possible). */
1809 /* The context is used for rounding mode and status after sNaN, but */
1810 /* the digits setting is ignored. */
1811 /* ------------------------------------------------------------------ */
1813 decNumberToIntegralValue (decNumber * res, decNumber * rhs, decContext * set)
1816 decContext workset; /* working context */
1819 if (decCheckOperands (res, DECUNUSED, rhs, set))
1823 /* handle infinities and NaNs */
1824 if (rhs->bits & DECSPECIAL)
1827 if (decNumberIsInfinite (rhs))
1828 decNumberCopy (res, rhs); /* an Infinity */
1830 decNaNs (res, rhs, NULL, &status); /* a NaN */
1832 decStatus (res, status, set);
1836 /* we have a finite number; no error possible */
1837 if (rhs->exponent >= 0)
1838 return decNumberCopy (res, rhs);
1839 /* that was easy, but if negative exponent we have work to do... */
1840 workset = *set; /* clone rounding, etc. */
1841 workset.digits = rhs->digits; /* no length rounding */
1842 workset.traps = 0; /* no traps */
1843 decNumberZero (&dn); /* make a number with exponent 0 */
1844 return decNumberQuantize (res, rhs, &dn, &workset);
1847 /* ================================================================== */
1848 /* Utility routines */
1849 /* ================================================================== */
1851 /* ------------------------------------------------------------------ */
1852 /* decNumberCopy -- copy a number */
1854 /* dest is the target decNumber */
1855 /* src is the source decNumber */
1858 /* (dest==src is allowed and is a no-op) */
1859 /* All fields are updated as required. This is a utility operation, */
1860 /* so special values are unchanged and no error is possible. */
1861 /* ------------------------------------------------------------------ */
1863 decNumberCopy (decNumber * dest, decNumber * src)
1868 return decNumberZero (dest);
1872 return dest; /* no copy required */
1874 /* We use explicit assignments here as structure assignment can copy */
1875 /* more than just the lsu (for small DECDPUN). This would not affect */
1876 /* the value of the results, but would disturb test harness spill */
1878 dest->bits = src->bits;
1879 dest->exponent = src->exponent;
1880 dest->digits = src->digits;
1881 dest->lsu[0] = src->lsu[0];
1882 if (src->digits > DECDPUN)
1883 { /* more Units to come */
1884 Unit *s, *d, *smsup; /* work */
1885 /* memcpy for the remaining Units would be safe as they cannot */
1886 /* overlap. However, this explicit loop is faster in short cases. */
1887 d = dest->lsu + 1; /* -> first destination */
1888 smsup = src->lsu + D2U (src->digits); /* -> source msu+1 */
1889 for (s = src->lsu + 1; s < smsup; s++, d++)
1895 /* ------------------------------------------------------------------ */
1896 /* decNumberTrim -- remove insignificant zeros */
1898 /* dn is the number to trim */
1901 /* All fields are updated as required. This is a utility operation, */
1902 /* so special values are unchanged and no error is possible. */
1903 /* ------------------------------------------------------------------ */
1905 decNumberTrim (decNumber * dn)
1907 Int dropped; /* work */
1908 return decTrim (dn, 0, &dropped);
1911 /* ------------------------------------------------------------------ */
1912 /* decNumberVersion -- return the name and version of this module */
1914 /* No error is possible. */
1915 /* ------------------------------------------------------------------ */
1917 decNumberVersion (void)
1922 /* ------------------------------------------------------------------ */
1923 /* decNumberZero -- set a number to 0 */
1925 /* dn is the number to set, with space for one digit */
1928 /* No error is possible. */
1929 /* ------------------------------------------------------------------ */
1930 /* Memset is not used as it is much slower in some environments. */
1932 decNumberZero (decNumber * dn)
1936 if (decCheckOperands (dn, DECUNUSED, DECUNUSED, DECUNUSED))
1947 /* ================================================================== */
1948 /* Local routines */
1949 /* ================================================================== */
1951 /* ------------------------------------------------------------------ */
1952 /* decToString -- lay out a number into a string */
1954 /* dn is the number to lay out */
1955 /* string is where to lay out the number */
1956 /* eng is 1 if Engineering, 0 if Scientific */
1958 /* str must be at least dn->digits+14 characters long */
1959 /* No error is possible. */
1961 /* Note that this routine can generate a -0 or 0.000. These are */
1962 /* never generated in subset to-number or arithmetic, but can occur */
1963 /* in non-subset arithmetic (e.g., -1*0 or 1.234-1.234). */
1964 /* ------------------------------------------------------------------ */
1965 /* If DECCHECK is enabled the string "?" is returned if a number is */
1968 /* TODIGIT -- macro to remove the leading digit from the unsigned */
1969 /* integer u at column cut (counting from the right, LSD=0) and place */
1970 /* it as an ASCII character into the character pointed to by c. Note */
1971 /* that cut must be <= 9, and the maximum value for u is 2,000,000,000 */
1972 /* (as is needed for negative exponents of subnormals). The unsigned */
1973 /* integer pow is used as a temporary variable. */
1974 #define TODIGIT(u, cut, c) { \
1976 pow=powers[cut]*2; \
1979 if ((u)>=pow) {(u)-=pow; *(c)+=8;} \
1981 if ((u)>=pow) {(u)-=pow; *(c)+=4;} \
1984 if ((u)>=pow) {(u)-=pow; *(c)+=2;} \
1986 if ((u)>=pow) {(u)-=pow; *(c)+=1;} \
1990 decToString (decNumber * dn, char *string, Flag eng)
1992 Int exp = dn->exponent; /* local copy */
1993 Int e; /* E-part value */
1994 Int pre; /* digits before the '.' */
1995 Int cut; /* for counting digits in a Unit */
1996 char *c = string; /* work [output pointer] */
1997 Unit *up = dn->lsu + D2U (dn->digits) - 1; /* -> msu [input pointer] */
1998 uInt u, pow; /* work */
2001 if (decCheckOperands (DECUNUSED, dn, DECUNUSED, DECUNUSED))
2003 strcpy (string, "?");
2008 if (decNumberIsNegative (dn))
2009 { /* Negatives get a minus (except */
2010 *c = '-'; /* NaNs, which remove the '-' below) */
2013 if (dn->bits & DECSPECIAL)
2014 { /* Is a special value */
2015 if (decNumberIsInfinite (dn))
2017 strcpy (c, "Infinity");
2021 if (dn->bits & DECSNAN)
2022 { /* signalling NaN */
2027 c += 3; /* step past */
2028 /* if not a clean non-zero coefficient, that's all we have in a */
2030 if (exp != 0 || (*dn->lsu == 0 && dn->digits == 1))
2032 /* [drop through to add integer] */
2035 /* calculate how many digits in msu, and hence first cut */
2036 cut = dn->digits % DECDPUN;
2038 cut = DECDPUN; /* msu is full */
2039 cut--; /* power of ten for digit */
2042 { /* simple integer [common fastpath, */
2043 /* used for NaNs, too] */
2044 for (; up >= dn->lsu; up--)
2045 { /* each Unit from msu */
2046 u = *up; /* contains DECDPUN digits to lay out */
2047 for (; cut >= 0; c++, cut--)
2048 TODIGIT (u, cut, c);
2049 cut = DECDPUN - 1; /* next Unit has all digits */
2051 *c = '\0'; /* terminate the string */
2055 /* non-0 exponent -- assume plain form */
2056 pre = dn->digits + exp; /* digits before '.' */
2058 if ((exp > 0) || (pre < -5))
2059 { /* need exponential form */
2060 e = exp + dn->digits - 1; /* calculate E value */
2061 pre = 1; /* assume one digit before '.' */
2062 if (eng && (e != 0))
2063 { /* may need to adjust */
2064 Int adj; /* adjustment */
2065 /* The C remainder operator is undefined for negative numbers, so */
2066 /* we must use positive remainder calculation here */
2078 /* if we are dealing with zero we will use exponent which is a */
2079 /* multiple of three, as expected, but there will only be the */
2080 /* one zero before the E, still. Otherwise note the padding. */
2086 { /* 0.00Esnn needed */
2094 /* lay out the digits of the coefficient, adding 0s and . as needed */
2097 { /* xxx.xxx or xx00 (engineering) form */
2098 for (; pre > 0; pre--, c++, cut--)
2101 { /* need new Unit */
2103 break; /* out of input digits (pre>digits) */
2108 TODIGIT (u, cut, c);
2110 if (up > dn->lsu || (up == dn->lsu && cut >= 0))
2111 { /* more to come, after '.' */
2117 { /* need new Unit */
2119 break; /* out of input digits */
2124 TODIGIT (u, cut, c);
2128 for (; pre > 0; pre--, c++)
2129 *c = '0'; /* 0 padding (for engineering) needed */
2132 { /* 0.xxx or 0.000xxx form */
2137 for (; pre < 0; pre++, c++)
2138 *c = '0'; /* add any 0's after '.' */
2142 { /* need new Unit */
2144 break; /* out of input digits */
2149 TODIGIT (u, cut, c);
2153 /* Finally add the E-part, if needed. It will never be 0, has a
2154 base maximum and minimum of +999999999 through -999999999, but
2155 could range down to -1999999998 for subnormal numbers */
2158 Flag had = 0; /* 1=had non-zero */
2162 c++; /* assume positive */
2166 *(c - 1) = '-'; /* oops, need - */
2167 u = -e; /* uInt, please */
2169 /* layout the exponent (_itoa is not ANSI C) */
2170 for (cut = 9; cut >= 0; cut--)
2172 TODIGIT (u, cut, c);
2173 if (*c == '0' && !had)
2174 continue; /* skip leading zeros */
2175 had = 1; /* had non-0 */
2176 c++; /* step for next */
2179 *c = '\0'; /* terminate the string (all paths) */
2183 /* ------------------------------------------------------------------ */
2184 /* decAddOp -- add/subtract operation */
2186 /* This computes C = A + B */
2188 /* res is C, the result. C may be A and/or B (e.g., X=X+X) */
2191 /* set is the context */
2192 /* negate is DECNEG if rhs should be negated, or 0 otherwise */
2193 /* status accumulates status for the caller */
2195 /* C must have space for set->digits digits. */
2196 /* ------------------------------------------------------------------ */
2197 /* If possible, we calculate the coefficient directly into C. */
2199 /* -- we need a digits+1 calculation because numbers are unaligned */
2200 /* and span more than set->digits digits */
2201 /* -- a carry to digits+1 digits looks possible */
2202 /* -- C is the same as A or B, and the result would destructively */
2203 /* overlap the A or B coefficient */
2204 /* then we must calculate into a temporary buffer. In this latter */
2205 /* case we use the local (stack) buffer if possible, and only if too */
2206 /* long for that do we resort to malloc. */
2208 /* Misalignment is handled as follows: */
2209 /* Apad: (AExp>BExp) Swap operands and proceed as for BExp>AExp. */
2210 /* BPad: Apply the padding by a combination of shifting (whole */
2211 /* units) and multiplication (part units). */
2213 /* Addition, especially x=x+1, is speed-critical, so we take pains */
2214 /* to make returning as fast as possible, by flagging any allocation. */
2215 /* ------------------------------------------------------------------ */
2217 decAddOp (decNumber * res, decNumber * lhs,
2218 decNumber * rhs, decContext * set, uByte negate, uInt * status)
2220 decNumber *alloclhs = NULL; /* non-NULL if rounded lhs allocated */
2221 decNumber *allocrhs = NULL; /* .., rhs */
2222 Int rhsshift; /* working shift (in Units) */
2223 Int maxdigits; /* longest logical length */
2224 Int mult; /* multiplier */
2225 Int residue; /* rounding accumulator */
2226 uByte bits; /* result bits */
2227 Flag diffsign; /* non-0 if arguments have different sign */
2228 Unit *acc; /* accumulator for result */
2229 Unit accbuff[D2U (DECBUFFER + 1)]; /* local buffer [+1 is for possible */
2230 /* final carry digit or DECBUFFER=0] */
2231 Unit *allocacc = NULL; /* -> allocated acc buffer, iff allocated */
2232 Flag alloced = 0; /* set non-0 if any allocations */
2233 Int reqdigits = set->digits; /* local copy; requested DIGITS */
2234 uByte merged; /* merged flags */
2235 Int padding; /* work */
2238 if (decCheckOperands (res, lhs, rhs, set))
2243 { /* protect allocated storage */
2247 /* reduce operands and set lostDigits status, as needed */
2248 if (lhs->digits > reqdigits)
2250 alloclhs = decRoundOperand (lhs, set, status);
2251 if (alloclhs == NULL)
2256 if (rhs->digits > reqdigits)
2258 allocrhs = decRoundOperand (rhs, set, status);
2259 if (allocrhs == NULL)
2266 /* [following code does not require input rounding] */
2268 /* note whether signs differ */
2269 diffsign = (Flag) ((lhs->bits ^ rhs->bits ^ negate) & DECNEG);
2271 /* handle infinities and NaNs */
2272 merged = (lhs->bits | rhs->bits) & DECSPECIAL;
2274 { /* a special bit set */
2275 if (merged & (DECSNAN | DECNAN)) /* a NaN */
2276 decNaNs (res, lhs, rhs, status);
2278 { /* one or two infinities */
2279 if (decNumberIsInfinite (lhs))
2280 { /* LHS is infinity */
2281 /* two infinities with different signs is invalid */
2282 if (decNumberIsInfinite (rhs) && diffsign)
2284 *status |= DEC_Invalid_operation;
2287 bits = lhs->bits & DECNEG; /* get sign from LHS */
2290 bits = (rhs->bits ^ negate) & DECNEG; /* RHS must be Infinity */
2292 decNumberZero (res);
2293 res->bits = bits; /* set +/- infinity */
2298 /* Quick exit for add 0s; return the non-0, modified as need be */
2301 Int adjust; /* work */
2302 Int lexp = lhs->exponent; /* save in case LHS==RES */
2303 bits = lhs->bits; /* .. */
2304 residue = 0; /* clear accumulator */
2305 decCopyFit (res, rhs, set, &residue, status); /* copy (as needed) */
2306 res->bits ^= negate; /* flip if rhs was negated */
2309 { /* exponents on zeros count */
2311 /* exponent will be the lower of the two */
2312 adjust = lexp - res->exponent; /* adjustment needed [if -ve] */
2314 { /* both 0: special IEEE 854 rules */
2316 res->exponent = lexp; /* set exponent */
2317 /* 0-0 gives +0 unless rounding to -infinity, and -0-0 gives -0 */
2320 if (set->round != DEC_ROUND_FLOOR)
2323 res->bits = DECNEG; /* preserve 0 sign */
2329 { /* 0-padding needed */
2330 if ((res->digits - adjust) > set->digits)
2332 adjust = res->digits - set->digits; /* to fit exactly */
2333 *status |= DEC_Rounded; /* [but exact] */
2336 decShiftToMost (res->lsu, res->digits, -adjust);
2337 res->exponent += adjust; /* set the exponent. */
2343 decFinish (res, set, &residue, status); /* clean and finalize */
2348 { /* [lhs is non-zero] */
2349 Int adjust; /* work */
2350 Int rexp = rhs->exponent; /* save in case RHS==RES */
2351 bits = rhs->bits; /* be clean */
2352 residue = 0; /* clear accumulator */
2353 decCopyFit (res, lhs, set, &residue, status); /* copy (as needed) */
2356 { /* exponents on zeros count */
2358 /* exponent will be the lower of the two */
2359 /* [0-0 case handled above] */
2360 adjust = rexp - res->exponent; /* adjustment needed [if -ve] */
2362 { /* 0-padding needed */
2363 if ((res->digits - adjust) > set->digits)
2365 adjust = res->digits - set->digits; /* to fit exactly */
2366 *status |= DEC_Rounded; /* [but exact] */
2369 decShiftToMost (res->lsu, res->digits, -adjust);
2370 res->exponent += adjust; /* set the exponent. */
2375 decFinish (res, set, &residue, status); /* clean and finalize */
2378 /* [both fastpath and mainpath code below assume these cases */
2379 /* (notably 0-0) have already been handled] */
2381 /* calculate the padding needed to align the operands */
2382 padding = rhs->exponent - lhs->exponent;
2384 /* Fastpath cases where the numbers are aligned and normal, the RHS */
2385 /* is all in one unit, no operand rounding is needed, and no carry, */
2386 /* lengthening, or borrow is needed */
2387 if (rhs->digits <= DECDPUN && padding == 0 && rhs->exponent >= set->emin /* [some normals drop through] */
2388 && rhs->digits <= reqdigits && lhs->digits <= reqdigits)
2390 Int partial = *lhs->lsu;
2393 Int maxv = DECDPUNMAX; /* highest no-overflow */
2394 if (lhs->digits < DECDPUN)
2395 maxv = powers[lhs->digits] - 1;
2396 partial += *rhs->lsu;
2397 if (partial <= maxv)
2400 decNumberCopy (res, lhs); /* not in place */
2401 *res->lsu = (Unit) partial; /* [copy could have overwritten RHS] */
2404 /* else drop out for careful add */
2407 { /* signs differ */
2408 partial -= *rhs->lsu;
2410 { /* no borrow needed, and non-0 result */
2412 decNumberCopy (res, lhs); /* not in place */
2413 *res->lsu = (Unit) partial;
2414 /* this could have reduced digits [but result>0] */
2415 res->digits = decGetDigits (res->lsu, D2U (res->digits));
2418 /* else drop out for careful subtract */
2422 /* Now align (pad) the lhs or rhs so we can add or subtract them, as
2423 necessary. If one number is much larger than the other (that is,
2424 if in plain form there is a least one digit between the lowest
2425 digit or one and the highest of the other) we need to pad with up
2426 to DIGITS-1 trailing zeros, and then apply rounding (as exotic
2427 rounding modes may be affected by the residue).
2429 rhsshift = 0; /* rhs shift to left (padding) in Units */
2430 bits = lhs->bits; /* assume sign is that of LHS */
2431 mult = 1; /* likely multiplier */
2433 /* if padding==0 the operands are aligned; no padding needed */
2436 /* some padding needed */
2437 /* We always pad the RHS, as we can then effect any required */
2438 /* padding by a combination of shifts and a multiply */
2441 { /* LHS needs the padding */
2443 padding = -padding; /* will be +ve */
2444 bits = (uByte) (rhs->bits ^ negate); /* assumed sign is now that of RHS */
2451 /* If, after pad, rhs would be longer than lhs by digits+1 or */
2452 /* more then lhs cannot affect the answer, except as a residue, */
2453 /* so we only need to pad up to a length of DIGITS+1. */
2454 if (rhs->digits + padding > lhs->digits + reqdigits + 1)
2456 /* The RHS is sufficient */
2457 /* for residue we use the relative sign indication... */
2458 Int shift = reqdigits - rhs->digits; /* left shift needed */
2459 residue = 1; /* residue for rounding */
2461 residue = -residue; /* signs differ */
2462 /* copy, shortening if necessary */
2463 decCopyFit (res, rhs, set, &residue, status);
2464 /* if it was already shorter, then need to pad with zeros */
2467 res->digits = decShiftToMost (res->lsu, res->digits, shift);
2468 res->exponent -= shift; /* adjust the exponent. */
2470 /* flip the result sign if unswapped and rhs was negated */
2472 res->bits ^= negate;
2473 decFinish (res, set, &residue, status); /* done */
2477 /* LHS digits may affect result */
2478 rhsshift = D2U (padding + 1) - 1; /* this much by Unit shift .. */
2479 mult = powers[padding - (rhsshift * DECDPUN)]; /* .. this by multiplication */
2480 } /* padding needed */
2483 mult = -mult; /* signs differ */
2485 /* determine the longer operand */
2486 maxdigits = rhs->digits + padding; /* virtual length of RHS */
2487 if (lhs->digits > maxdigits)
2488 maxdigits = lhs->digits;
2490 /* Decide on the result buffer to use; if possible place directly */
2492 acc = res->lsu; /* assume build direct */
2493 /* If destructive overlap, or the number is too long, or a carry or */
2494 /* borrow to DIGITS+1 might be possible we must use a buffer. */
2495 /* [Might be worth more sophisticated tests when maxdigits==reqdigits] */
2496 if ((maxdigits >= reqdigits) /* is, or could be, too large */
2497 || (res == rhs && rhsshift > 0))
2498 { /* destructive overlap */
2499 /* buffer needed; choose it */
2500 /* we'll need units for maxdigits digits, +1 Unit for carry or borrow */
2501 Int need = D2U (maxdigits) + 1;
2502 acc = accbuff; /* assume use local buffer */
2503 if (need * sizeof (Unit) > sizeof (accbuff))
2505 allocacc = (Unit *) malloc (need * sizeof (Unit));
2506 if (allocacc == NULL)
2507 { /* hopeless -- abandon */
2508 *status |= DEC_Insufficient_storage;
2516 res->bits = (uByte) (bits & DECNEG); /* it's now safe to overwrite.. */
2517 res->exponent = lhs->exponent; /* .. operands (even if aliased) */
2520 decDumpAr ('A', lhs->lsu, D2U (lhs->digits));
2521 decDumpAr ('B', rhs->lsu, D2U (rhs->digits));
2522 printf (" :h: %d %d\n", rhsshift, mult);
2525 /* add [A+B*m] or subtract [A+B*(-m)] */
2526 res->digits = decUnitAddSub (lhs->lsu, D2U (lhs->digits), rhs->lsu, D2U (rhs->digits), rhsshift, acc, mult) * DECDPUN; /* [units -> digits] */
2527 if (res->digits < 0)
2529 res->digits = -res->digits;
2530 res->bits ^= DECNEG; /* flip the sign */
2533 decDumpAr ('+', acc, D2U (res->digits));
2536 /* If we used a buffer we need to copy back, possibly shortening */
2537 /* (If we didn't use buffer it must have fit, so can't need rounding */
2538 /* and residue must be 0.) */
2539 residue = 0; /* clear accumulator */
2540 if (acc != res->lsu)
2544 { /* round from first significant digit */
2546 /* remove leading zeros that we added due to rounding up to */
2547 /* integral Units -- before the test for rounding. */
2548 if (res->digits > reqdigits)
2549 res->digits = decGetDigits (acc, D2U (res->digits));
2550 decSetCoeff (res, set, acc, res->digits, &residue, status);
2554 { /* subset arithmetic rounds from original significant digit */
2555 /* We may have an underestimate. This only occurs when both */
2556 /* numbers fit in DECDPUN digits and we are padding with a */
2557 /* negative multiple (-10, -100...) and the top digit(s) become */
2558 /* 0. (This only matters if we are using X3.274 rules where the */
2559 /* leading zero could be included in the rounding.) */
2560 if (res->digits < maxdigits)
2562 *(acc + D2U (res->digits)) = 0; /* ensure leading 0 is there */
2563 res->digits = maxdigits;
2567 /* remove leading zeros that we added due to rounding up to */
2568 /* integral Units (but only those in excess of the original */
2569 /* maxdigits length, unless extended) before test for rounding. */
2570 if (res->digits > reqdigits)
2572 res->digits = decGetDigits (acc, D2U (res->digits));
2573 if (res->digits < maxdigits)
2574 res->digits = maxdigits;
2577 decSetCoeff (res, set, acc, res->digits, &residue, status);
2578 /* Now apply rounding if needed before removing leading zeros. */
2579 /* This is safe because subnormals are not a possibility */
2582 decApplyRound (res, set, residue, status);
2583 residue = 0; /* we did what we had to do */
2589 /* strip leading zeros [these were left on in case of subset subtract] */
2590 res->digits = decGetDigits (res->lsu, D2U (res->digits));
2592 /* apply checks and rounding */
2593 decFinish (res, set, &residue, status);
2595 /* "When the sum of two operands with opposite signs is exactly */
2596 /* zero, the sign of that sum shall be '+' in all rounding modes */
2597 /* except round toward -Infinity, in which mode that sign shall be */
2598 /* '-'." [Subset zeros also never have '-', set by decFinish.] */
2599 if (ISZERO (res) && diffsign
2603 && (*status & DEC_Inexact) == 0)
2605 if (set->round == DEC_ROUND_FLOOR)
2606 res->bits |= DECNEG; /* sign - */
2608 res->bits &= ~DECNEG; /* sign + */
2611 while (0); /* end protected */
2615 if (allocacc != NULL)
2616 free (allocacc); /* drop any storage we used */
2617 if (allocrhs != NULL)
2618 free (allocrhs); /* .. */
2619 if (alloclhs != NULL)
2620 free (alloclhs); /* .. */
2625 /* ------------------------------------------------------------------ */
2626 /* decDivideOp -- division operation */
2628 /* This routine performs the calculations for all four division */
2629 /* operators (divide, divideInteger, remainder, remainderNear). */
2633 /* res is C, the result. C may be A and/or B (e.g., X=X/X) */
2636 /* set is the context */
2637 /* op is DIVIDE, DIVIDEINT, REMAINDER, or REMNEAR respectively. */
2638 /* status is the usual accumulator */
2640 /* C must have space for set->digits digits. */
2642 /* ------------------------------------------------------------------ */
2643 /* The underlying algorithm of this routine is the same as in the */
2644 /* 1981 S/370 implementation, that is, non-restoring long division */
2645 /* with bi-unit (rather than bi-digit) estimation for each unit */
2646 /* multiplier. In this pseudocode overview, complications for the */
2647 /* Remainder operators and division residues for exact rounding are */
2648 /* omitted for clarity. */
2650 /* Prepare operands and handle special values */
2651 /* Test for x/0 and then 0/x */
2652 /* Exp =Exp1 - Exp2 */
2653 /* Exp =Exp +len(var1) -len(var2) */
2654 /* Sign=Sign1 * Sign2 */
2655 /* Pad accumulator (Var1) to double-length with 0's (pad1) */
2656 /* Pad Var2 to same length as Var1 */
2657 /* msu2pair/plus=1st 2 or 1 units of var2, +1 to allow for round */
2659 /* Do until (have=digits+1 OR residue=0) */
2660 /* if exp<0 then if integer divide/residue then leave */
2663 /* compare numbers */
2664 /* if <0 then leave inner_loop */
2665 /* if =0 then (* quick exit without subtract *) do */
2666 /* this_unit=this_unit+1; output this_unit */
2667 /* leave outer_loop; end */
2668 /* Compare lengths of numbers (mantissae): */
2669 /* If same then tops2=msu2pair -- {units 1&2 of var2} */
2670 /* else tops2=msu2plus -- {0, unit 1 of var2} */
2671 /* tops1=first_unit_of_Var1*10**DECDPUN +second_unit_of_var1 */
2672 /* mult=tops1/tops2 -- Good and safe guess at divisor */
2673 /* if mult=0 then mult=1 */
2674 /* this_unit=this_unit+mult */
2676 /* end inner_loop */
2677 /* if have\=0 | this_unit\=0 then do */
2678 /* output this_unit */
2679 /* have=have+1; end */
2682 /* end outer_loop */
2683 /* exp=exp+1 -- set the proper exponent */
2684 /* if have=0 then generate answer=0 */
2685 /* Return (Result is defined by Var1) */
2687 /* ------------------------------------------------------------------ */
2688 /* We need two working buffers during the long division; one (digits+ */
2689 /* 1) to accumulate the result, and the other (up to 2*digits+1) for */
2690 /* long subtractions. These are acc and var1 respectively. */
2691 /* var1 is a copy of the lhs coefficient, var2 is the rhs coefficient.*/
2692 /* ------------------------------------------------------------------ */
2694 decDivideOp (decNumber * res,
2695 decNumber * lhs, decNumber * rhs,
2696 decContext * set, Flag op, uInt * status)
2698 decNumber *alloclhs = NULL; /* non-NULL if rounded lhs allocated */
2699 decNumber *allocrhs = NULL; /* .., rhs */
2700 Unit accbuff[D2U (DECBUFFER + DECDPUN)]; /* local buffer */
2701 Unit *acc = accbuff; /* -> accumulator array for result */
2702 Unit *allocacc = NULL; /* -> allocated buffer, iff allocated */
2703 Unit *accnext; /* -> where next digit will go */
2704 Int acclength; /* length of acc needed [Units] */
2705 Int accunits; /* count of units accumulated */
2706 Int accdigits; /* count of digits accumulated */
2708 Unit varbuff[D2U (DECBUFFER * 2 + DECDPUN) * sizeof (Unit)]; /* buffer for var1 */
2709 Unit *var1 = varbuff; /* -> var1 array for long subtraction */
2710 Unit *varalloc = NULL; /* -> allocated buffer, iff used */
2712 Unit *var2; /* -> var2 array */
2714 Int var1units, var2units; /* actual lengths */
2715 Int var2ulen; /* logical length (units) */
2716 Int var1initpad = 0; /* var1 initial padding (digits) */
2717 Unit *msu1, *msu2; /* -> msu of each var */
2718 Int msu2plus; /* msu2 plus one [does not vary] */
2719 eInt msu2pair; /* msu2 pair plus one [does not vary] */
2720 Int maxdigits; /* longest LHS or required acc length */
2721 Int mult; /* multiplier for subtraction */
2722 Unit thisunit; /* current unit being accumulated */
2723 Int residue; /* for rounding */
2724 Int reqdigits = set->digits; /* requested DIGITS */
2725 Int exponent; /* working exponent */
2726 Int maxexponent = 0; /* DIVIDE maximum exponent if unrounded */
2727 uByte bits; /* working sign */
2728 uByte merged; /* merged flags */
2729 Unit *target, *source; /* work */
2730 uInt const *pow; /* .. */
2731 Int shift, cut; /* .. */
2733 Int dropped; /* work */
2737 if (decCheckOperands (res, lhs, rhs, set))
2742 { /* protect allocated storage */
2746 /* reduce operands and set lostDigits status, as needed */
2747 if (lhs->digits > reqdigits)
2749 alloclhs = decRoundOperand (lhs, set, status);
2750 if (alloclhs == NULL)
2754 if (rhs->digits > reqdigits)
2756 allocrhs = decRoundOperand (rhs, set, status);
2757 if (allocrhs == NULL)
2763 /* [following code does not require input rounding] */
2765 bits = (lhs->bits ^ rhs->bits) & DECNEG; /* assumed sign for divisions */
2767 /* handle infinities and NaNs */
2768 merged = (lhs->bits | rhs->bits) & DECSPECIAL;
2770 { /* a special bit set */
2771 if (merged & (DECSNAN | DECNAN))
2772 { /* one or two NaNs */
2773 decNaNs (res, lhs, rhs, status);
2776 /* one or two infinities */
2777 if (decNumberIsInfinite (lhs))
2778 { /* LHS (dividend) is infinite */
2779 if (decNumberIsInfinite (rhs) || /* two infinities are invalid .. */
2780 op & (REMAINDER | REMNEAR))
2781 { /* as is remainder of infinity */
2782 *status |= DEC_Invalid_operation;
2785 /* [Note that infinity/0 raises no exceptions] */
2786 decNumberZero (res);
2787 res->bits = bits | DECINF; /* set +/- infinity */
2791 { /* RHS (divisor) is infinite */
2793 if (op & (REMAINDER | REMNEAR))
2795 /* result is [finished clone of] lhs */
2796 decCopyFit (res, lhs, set, &residue, status);
2800 decNumberZero (res);
2801 res->bits = bits; /* set +/- zero */
2802 /* for DIVIDEINT the exponent is always 0. For DIVIDE, result */
2803 /* is a 0 with infinitely negative exponent, clamped to minimum */
2806 res->exponent = set->emin - set->digits + 1;
2807 *status |= DEC_Clamped;
2810 decFinish (res, set, &residue, status);
2815 /* handle 0 rhs (x/0) */
2817 { /* x/0 is always exceptional */
2820 decNumberZero (res); /* [after lhs test] */
2821 *status |= DEC_Division_undefined; /* 0/0 will become NaN */
2825 decNumberZero (res);
2826 if (op & (REMAINDER | REMNEAR))
2827 *status |= DEC_Invalid_operation;
2830 *status |= DEC_Division_by_zero; /* x/0 */
2831 res->bits = bits | DECINF; /* .. is +/- Infinity */
2837 /* handle 0 lhs (0/x) */
2842 decNumberZero (res);
2849 exponent = lhs->exponent - rhs->exponent; /* ideal exponent */
2850 decNumberCopy (res, lhs); /* [zeros always fit] */
2851 res->bits = bits; /* sign as computed */
2852 res->exponent = exponent; /* exponent, too */
2853 decFinalize (res, set, &residue, status); /* check exponent */
2855 else if (op & DIVIDEINT)
2857 decNumberZero (res); /* integer 0 */
2858 res->bits = bits; /* sign as computed */
2862 exponent = rhs->exponent; /* [save in case overwrite] */
2863 decNumberCopy (res, lhs); /* [zeros always fit] */
2864 if (exponent < res->exponent)
2865 res->exponent = exponent; /* use lower */
2873 /* Precalculate exponent. This starts off adjusted (and hence fits */
2874 /* in 31 bits) and becomes the usual unadjusted exponent as the */
2875 /* division proceeds. The order of evaluation is important, here, */
2876 /* to avoid wrap. */
2878 (lhs->exponent + lhs->digits) - (rhs->exponent + rhs->digits);
2880 /* If the working exponent is -ve, then some quick exits are */
2881 /* possible because the quotient is known to be <1 */
2882 /* [for REMNEAR, it needs to be < -1, as -0.5 could need work] */
2883 if (exponent < 0 && !(op == DIVIDE))
2887 decNumberZero (res); /* integer part is 0 */
2891 res->bits = bits; /* set +/- zero */
2894 /* we can fastpath remainders so long as the lhs has the */
2895 /* smaller (or equal) exponent */
2896 if (lhs->exponent <= rhs->exponent)
2898 if (op & REMAINDER || exponent < -1)
2900 /* It is REMAINDER or safe REMNEAR; result is [finished */
2901 /* clone of] lhs (r = x - 0*y) */
2903 decCopyFit (res, lhs, set, &residue, status);
2904 decFinish (res, set, &residue, status);
2907 /* [unsafe REMNEAR drops through] */
2911 /* We need long (slow) division; roll up the sleeves... */
2913 /* The accumulator will hold the quotient of the division. */
2914 /* If it needs to be too long for stack storage, then allocate. */
2915 acclength = D2U (reqdigits + DECDPUN); /* in Units */
2916 if (acclength * sizeof (Unit) > sizeof (accbuff))
2918 allocacc = (Unit *) malloc (acclength * sizeof (Unit));
2919 if (allocacc == NULL)
2920 { /* hopeless -- abandon */
2921 *status |= DEC_Insufficient_storage;
2924 acc = allocacc; /* use the allocated space */
2927 /* var1 is the padded LHS ready for subtractions. */
2928 /* If it needs to be too long for stack storage, then allocate. */
2929 /* The maximum units we need for var1 (long subtraction) is: */
2931 /* (rhs->digits+reqdigits-1) -- to allow full slide to right */
2932 /* or (lhs->digits) -- to allow for long lhs */
2933 /* whichever is larger */
2934 /* +1 -- for rounding of slide to right */
2935 /* +1 -- for leading 0s */
2936 /* +1 -- for pre-adjust if a remainder or DIVIDEINT */
2937 /* [Note: unused units do not participate in decUnitAddSub data] */
2938 maxdigits = rhs->digits + reqdigits - 1;
2939 if (lhs->digits > maxdigits)
2940 maxdigits = lhs->digits;
2941 var1units = D2U (maxdigits) + 2;
2942 /* allocate a guard unit above msu1 for REMAINDERNEAR */
2945 if ((var1units + 1) * sizeof (Unit) > sizeof (varbuff))
2947 varalloc = (Unit *) malloc ((var1units + 1) * sizeof (Unit));
2948 if (varalloc == NULL)
2949 { /* hopeless -- abandon */
2950 *status |= DEC_Insufficient_storage;
2953 var1 = varalloc; /* use the allocated space */
2956 /* Extend the lhs and rhs to full long subtraction length. The lhs */
2957 /* is truly extended into the var1 buffer, with 0 padding, so we can */
2958 /* subtract in place. The rhs (var2) has virtual padding */
2959 /* (implemented by decUnitAddSub). */
2960 /* We allocated one guard unit above msu1 for rem=rem+rem in REMAINDERNEAR */
2961 msu1 = var1 + var1units - 1; /* msu of var1 */
2962 source = lhs->lsu + D2U (lhs->digits) - 1; /* msu of input array */
2963 for (target = msu1; source >= lhs->lsu; source--, target--)
2965 for (; target >= var1; target--)
2968 /* rhs (var2) is left-aligned with var1 at the start */
2969 var2ulen = var1units; /* rhs logical length (units) */
2970 var2units = D2U (rhs->digits); /* rhs actual length (units) */
2971 var2 = rhs->lsu; /* -> rhs array */
2972 msu2 = var2 + var2units - 1; /* -> msu of var2 [never changes] */
2973 /* now set up the variables which we'll use for estimating the */
2974 /* multiplication factor. If these variables are not exact, we add */
2975 /* 1 to make sure that we never overestimate the multiplier. */
2976 msu2plus = *msu2; /* it's value .. */
2978 msu2plus++; /* .. +1 if any more */
2979 msu2pair = (eInt) * msu2 * (DECDPUNMAX + 1); /* top two pair .. */
2981 { /* .. [else treat 2nd as 0] */
2982 msu2pair += *(msu2 - 1); /* .. */
2984 msu2pair++; /* .. +1 if any more */
2987 /* Since we are working in units, the units may have leading zeros, */
2988 /* but we calculated the exponent on the assumption that they are */
2989 /* both left-aligned. Adjust the exponent to compensate: add the */
2990 /* number of leading zeros in var1 msu and subtract those in var2 msu. */
2991 /* [We actually do this by counting the digits and negating, as */
2992 /* lead1=DECDPUN-digits1, and similarly for lead2.] */
2993 for (pow = &powers[1]; *msu1 >= *pow; pow++)
2995 for (pow = &powers[1]; *msu2 >= *pow; pow++)
2998 /* Now, if doing an integer divide or remainder, we want to ensure */
2999 /* that the result will be Unit-aligned. To do this, we shift the */
3000 /* var1 accumulator towards least if need be. (It's much easier to */
3001 /* do this now than to reassemble the residue afterwards, if we are */
3002 /* doing a remainder.) Also ensure the exponent is not negative. */
3006 /* save the initial 'false' padding of var1, in digits */
3007 var1initpad = (var1units - D2U (lhs->digits)) * DECDPUN;
3008 /* Determine the shift to do. */
3012 cut = DECDPUN - exponent % DECDPUN;
3013 decShiftToLeast (var1, var1units, cut);
3014 exponent += cut; /* maintain numerical value */
3015 var1initpad -= cut; /* .. and reduce padding */
3016 /* clean any most-significant units we just emptied */
3017 for (u = msu1; cut >= DECDPUN; cut -= DECDPUN, u--)
3022 maxexponent = lhs->exponent - rhs->exponent; /* save */
3023 /* optimization: if the first iteration will just produce 0, */
3024 /* preadjust to skip it [valid for DIVIDE only] */
3027 var2ulen--; /* shift down */
3028 exponent -= DECDPUN; /* update the exponent */
3032 /* ---- start the long-division loops ------------------------------ */
3033 accunits = 0; /* no units accumulated yet */
3034 accdigits = 0; /* .. or digits */
3035 accnext = acc + acclength - 1; /* -> msu of acc [NB: allows digits+1] */
3037 { /* outer forever loop */
3038 thisunit = 0; /* current unit assumed 0 */
3039 /* find the next unit */
3041 { /* inner forever loop */
3042 /* strip leading zero units [from either pre-adjust or from */
3043 /* subtract last time around]. Leave at least one unit. */
3044 for (; *msu1 == 0 && msu1 > var1; msu1--)
3047 if (var1units < var2ulen)
3048 break; /* var1 too low for subtract */
3049 if (var1units == var2ulen)
3050 { /* unit-by-unit compare needed */
3051 /* compare the two numbers, from msu */
3052 Unit *pv1, *pv2, v2; /* units to compare */
3053 pv2 = msu2; /* -> msu */
3054 for (pv1 = msu1;; pv1--, pv2--)
3056 /* v1=*pv1 -- always OK */
3057 v2 = 0; /* assume in padding */
3059 v2 = *pv2; /* in range */
3061 break; /* no longer the same */
3063 break; /* done; leave pv1 as is */
3065 /* here when all inspected or a difference seen */
3067 break; /* var1 too low to subtract */
3069 { /* var1 == var2 */
3070 /* reach here if var1 and var2 are identical; subtraction */
3071 /* would increase digit by one, and the residue will be 0 so */
3072 /* we are done; leave the loop with residue set to 0. */
3073 thisunit++; /* as though subtracted */
3074 *var1 = 0; /* set var1 to 0 */
3075 var1units = 1; /* .. */
3076 break; /* from inner */
3077 } /* var1 == var2 */
3078 /* *pv1>v2. Prepare for real subtraction; the lengths are equal */
3079 /* Estimate the multiplier (there's always a msu1-1)... */
3080 /* Bring in two units of var2 to provide a good estimate. */
3082 (Int) (((eInt) * msu1 * (DECDPUNMAX + 1) +
3083 *(msu1 - 1)) / msu2pair);
3084 } /* lengths the same */
3086 { /* var1units > var2ulen, so subtraction is safe */
3087 /* The var2 msu is one unit towards the lsu of the var1 msu, */
3088 /* so we can only use one unit for var2. */
3090 (Int) (((eInt) * msu1 * (DECDPUNMAX + 1) +
3091 *(msu1 - 1)) / msu2plus);
3094 mult = 1; /* must always be at least 1 */
3095 /* subtraction needed; var1 is > var2 */
3096 thisunit = (Unit) (thisunit + mult); /* accumulate */
3097 /* subtract var1-var2, into var1; only the overlap needs */
3098 /* processing, as we are in place */
3099 shift = var2ulen - var2units;
3101 decDumpAr ('1', &var1[shift], var1units - shift);
3102 decDumpAr ('2', var2, var2units);
3103 printf ("m=%d\n", -mult);
3105 decUnitAddSub (&var1[shift], var1units - shift,
3106 var2, var2units, 0, &var1[shift], -mult);
3108 decDumpAr ('#', &var1[shift], var1units - shift);
3110 /* var1 now probably has leading zeros; these are removed at the */
3111 /* top of the inner loop. */
3114 /* We have the next unit; unless it's a leading zero, add to acc */
3115 if (accunits != 0 || thisunit != 0)
3116 { /* put the unit we got */
3117 *accnext = thisunit; /* store in accumulator */
3118 /* account exactly for the digits we got */
3121 accdigits++; /* at least one */
3122 for (pow = &powers[1]; thisunit >= *pow; pow++)
3126 accdigits += DECDPUN;
3127 accunits++; /* update count */
3128 accnext--; /* ready for next */
3129 if (accdigits > reqdigits)
3130 break; /* we have all we need */
3133 /* if the residue is zero, we're done (unless divide or */
3134 /* divideInteger and we haven't got enough digits yet) */
3135 if (*var1 == 0 && var1units == 1)
3136 { /* residue is 0 */
3137 if (op & (REMAINDER | REMNEAR))
3139 if ((op & DIVIDE) && (exponent <= maxexponent))
3141 /* [drop through if divideInteger] */
3143 /* we've also done enough if calculating remainder or integer */
3144 /* divide and we just did the last ('units') unit */
3145 if (exponent == 0 && !(op & DIVIDE))
3148 /* to get here, var1 is less than var2, so divide var2 by the per- */
3149 /* Unit power of ten and go for the next digit */
3150 var2ulen--; /* shift down */
3151 exponent -= DECDPUN; /* update the exponent */
3154 /* ---- division is complete --------------------------------------- */
3155 /* here: acc has at least reqdigits+1 of good results (or fewer */
3156 /* if early stop), starting at accnext+1 (its lsu) */
3157 /* var1 has any residue at the stopping point */
3158 /* accunits is the number of digits we collected in acc */
3161 accunits = 1; /* show we have one .. */
3162 accdigits = 1; /* .. */
3163 *accnext = 0; /* .. whose value is 0 */
3166 accnext++; /* back to last placed */
3167 /* accnext now -> lowest unit of result */
3169 residue = 0; /* assume no residue */
3172 /* record the presence of any residue, for rounding */
3173 if (*var1 != 0 || var1units > 1)
3177 /* We had an exact division; clean up spurious trailing 0s. */
3178 /* There will be at most DECDPUN-1, from the final multiply, */
3179 /* and then only if the result is non-0 (and even) and the */
3180 /* exponent is 'loose'. */
3182 Unit lsu = *accnext;
3183 if (!(lsu & 0x01) && (lsu != 0))
3185 /* count the trailing zeros */
3188 { /* [will terminate because lsu!=0] */
3189 if (exponent >= maxexponent)
3190 break; /* don't chop real 0s */
3192 if ((lsu - QUOT10 (lsu, drop + 1)
3193 * powers[drop + 1]) != 0)
3194 break; /* found non-0 digit */
3196 if (lsu % powers[drop + 1] != 0)