Update
[gdb.git] / libdecnumber / decNumber.c
blobc5e223c812fea3e755700734025db06168cb7aa1
1 /* Decimal number arithmetic module for the decNumber C Library.
2 Copyright (C) 2005, 2007 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
10 version.
12 In addition to the permissions in the GNU General Public License,
13 the Free Software Foundation gives you unlimited permission to link
14 the compiled version of this file into combinations with other
15 programs, and to distribute those combinations without any
16 restriction coming from the use of this file. (The General Public
17 License restrictions do apply in other respects; for example, they
18 cover modification of the file, and distribution when not linked
19 into a combine executable.)
21 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
22 WARRANTY; without even the implied warranty of MERCHANTABILITY or
23 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
24 for more details.
26 You should have received a copy of the GNU General Public License
27 along with GCC; see the file COPYING. If not, write to the Free
28 Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
29 02110-1301, USA. */
31 /* ------------------------------------------------------------------ */
32 /* Decimal Number arithmetic module */
33 /* ------------------------------------------------------------------ */
34 /* This module comprises the routines for General Decimal Arithmetic */
35 /* as defined in the specification which may be found on the */
36 /* http://www2.hursley.ibm.com/decimal web pages. It implements both */
37 /* the full ('extended') arithmetic and the simpler ('subset') */
38 /* arithmetic. */
39 /* */
40 /* Usage notes: */
41 /* */
42 /* 1. This code is ANSI C89 except: */
43 /* */
44 /* If DECDPUN>4 or DECUSE64=1, the C99 64-bit int64_t and */
45 /* uint64_t types may be used. To avoid these, set DECUSE64=0 */
46 /* and DECDPUN<=4 (see documentation). */
47 /* */
48 /* 2. The decNumber format which this library uses is optimized for */
49 /* efficient processing of relatively short numbers; in particular */
50 /* it allows the use of fixed sized structures and minimizes copy */
51 /* and move operations. It does, however, support arbitrary */
52 /* precision (up to 999,999,999 digits) and arbitrary exponent */
53 /* range (Emax in the range 0 through 999,999,999 and Emin in the */
54 /* range -999,999,999 through 0). Mathematical functions (for */
55 /* example decNumberExp) as identified below are restricted more */
56 /* tightly: digits, emax, and -emin in the context must be <= */
57 /* DEC_MAX_MATH (999999), and their operand(s) must be within */
58 /* these bounds. */
59 /* */
60 /* 3. Logical functions are further restricted; their operands must */
61 /* be finite, positive, have an exponent of zero, and all digits */
62 /* must be either 0 or 1. The result will only contain digits */
63 /* which are 0 or 1 (and will have exponent=0 and a sign of 0). */
64 /* */
65 /* 4. Operands to operator functions are never modified unless they */
66 /* are also specified to be the result number (which is always */
67 /* permitted). Other than that case, operands must not overlap. */
68 /* */
69 /* 5. Error handling: the type of the error is ORed into the status */
70 /* flags in the current context (decContext structure). The */
71 /* SIGFPE signal is then raised if the corresponding trap-enabler */
72 /* flag in the decContext is set (is 1). */
73 /* */
74 /* It is the responsibility of the caller to clear the status */
75 /* flags as required. */
76 /* */
77 /* The result of any routine which returns a number will always */
78 /* be a valid number (which may be a special value, such as an */
79 /* Infinity or NaN). */
80 /* */
81 /* 6. The decNumber format is not an exchangeable concrete */
82 /* representation as it comprises fields which may be machine- */
83 /* dependent (packed or unpacked, or special length, for example). */
84 /* Canonical conversions to and from strings are provided; other */
85 /* conversions are available in separate modules. */
86 /* */
87 /* 7. Normally, input operands are assumed to be valid. Set DECCHECK */
88 /* to 1 for extended operand checking (including NULL operands). */
89 /* Results are undefined if a badly-formed structure (or a NULL */
90 /* pointer to a structure) is provided, though with DECCHECK */
91 /* enabled the operator routines are protected against exceptions. */
92 /* (Except if the result pointer is NULL, which is unrecoverable.) */
93 /* */
94 /* However, the routines will never cause exceptions if they are */
95 /* given well-formed operands, even if the value of the operands */
96 /* is inappropriate for the operation and DECCHECK is not set. */
97 /* (Except for SIGFPE, as and where documented.) */
98 /* */
99 /* 8. Subset arithmetic is available only if DECSUBSET is set to 1. */
100 /* ------------------------------------------------------------------ */
101 /* Implementation notes for maintenance of this module: */
102 /* */
103 /* 1. Storage leak protection: Routines which use malloc are not */
104 /* permitted to use return for fastpath or error exits (i.e., */
105 /* they follow strict structured programming conventions). */
106 /* Instead they have a do{}while(0); construct surrounding the */
107 /* code which is protected -- break may be used to exit this. */
108 /* Other routines can safely use the return statement inline. */
109 /* */
110 /* Storage leak accounting can be enabled using DECALLOC. */
111 /* */
112 /* 2. All loops use the for(;;) construct. Any do construct does */
113 /* not loop; it is for allocation protection as just described. */
114 /* */
115 /* 3. Setting status in the context must always be the very last */
116 /* action in a routine, as non-0 status may raise a trap and hence */
117 /* the call to set status may not return (if the handler uses long */
118 /* jump). Therefore all cleanup must be done first. In general, */
119 /* to achieve this status is accumulated and is only applied just */
120 /* before return by calling decContextSetStatus (via decStatus). */
121 /* */
122 /* Routines which allocate storage cannot, in general, use the */
123 /* 'top level' routines which could cause a non-returning */
124 /* transfer of control. The decXxxxOp routines are safe (do not */
125 /* call decStatus even if traps are set in the context) and should */
126 /* be used instead (they are also a little faster). */
127 /* */
128 /* 4. Exponent checking is minimized by allowing the exponent to */
129 /* grow outside its limits during calculations, provided that */
130 /* the decFinalize function is called later. Multiplication and */
131 /* division, and intermediate calculations in exponentiation, */
132 /* require more careful checks because of the risk of 31-bit */
133 /* overflow (the most negative valid exponent is -1999999997, for */
134 /* a 999999999-digit number with adjusted exponent of -999999999). */
135 /* */
136 /* 5. Rounding is deferred until finalization of results, with any */
137 /* 'off to the right' data being represented as a single digit */
138 /* residue (in the range -1 through 9). This avoids any double- */
139 /* rounding when more than one shortening takes place (for */
140 /* example, when a result is subnormal). */
141 /* */
142 /* 6. The digits count is allowed to rise to a multiple of DECDPUN */
143 /* during many operations, so whole Units are handled and exact */
144 /* accounting of digits is not needed. The correct digits value */
145 /* is found by decGetDigits, which accounts for leading zeros. */
146 /* This must be called before any rounding if the number of digits */
147 /* is not known exactly. */
148 /* */
149 /* 7. The multiply-by-reciprocal 'trick' is used for partitioning */
150 /* numbers up to four digits, using appropriate constants. This */
151 /* is not useful for longer numbers because overflow of 32 bits */
152 /* would lead to 4 multiplies, which is almost as expensive as */
153 /* a divide (unless a floating-point or 64-bit multiply is */
154 /* assumed to be available). */
155 /* */
156 /* 8. Unusual abbreviations that may be used in the commentary: */
157 /* lhs -- left hand side (operand, of an operation) */
158 /* lsd -- least significant digit (of coefficient) */
159 /* lsu -- least significant Unit (of coefficient) */
160 /* msd -- most significant digit (of coefficient) */
161 /* msi -- most significant item (in an array) */
162 /* msu -- most significant Unit (of coefficient) */
163 /* rhs -- right hand side (operand, of an operation) */
164 /* +ve -- positive */
165 /* -ve -- negative */
166 /* ** -- raise to the power */
167 /* ------------------------------------------------------------------ */
169 #include <stdlib.h> /* for malloc, free, etc. */
170 #include <stdio.h> /* for printf [if needed] */
171 #include <string.h> /* for strcpy */
172 #include <ctype.h> /* for lower */
173 #include "config.h" /* for GCC definitions */
174 #include "decNumber.h" /* base number library */
175 #include "decNumberLocal.h" /* decNumber local types, etc. */
177 /* Constants */
178 /* Public lookup table used by the D2U macro */
179 const uByte d2utable[DECMAXD2U+1]=D2UTABLE;
181 #define DECVERB 1 /* set to 1 for verbose DECCHECK */
182 #define powers DECPOWERS /* old internal name */
184 /* Local constants */
185 #define DIVIDE 0x80 /* Divide operators */
186 #define REMAINDER 0x40 /* .. */
187 #define DIVIDEINT 0x20 /* .. */
188 #define REMNEAR 0x10 /* .. */
189 #define COMPARE 0x01 /* Compare operators */
190 #define COMPMAX 0x02 /* .. */
191 #define COMPMIN 0x03 /* .. */
192 #define COMPTOTAL 0x04 /* .. */
193 #define COMPNAN 0x05 /* .. [NaN processing] */
194 #define COMPSIG 0x06 /* .. [signaling COMPARE] */
195 #define COMPMAXMAG 0x07 /* .. */
196 #define COMPMINMAG 0x08 /* .. */
198 #define DEC_sNaN 0x40000000 /* local status: sNaN signal */
199 #define BADINT (Int)0x80000000 /* most-negative Int; error indicator */
200 /* Next two indicate an integer >= 10**6, and its parity (bottom bit) */
201 #define BIGEVEN (Int)0x80000002
202 #define BIGODD (Int)0x80000003
204 static Unit uarrone[1]={1}; /* Unit array of 1, used for incrementing */
206 /* Granularity-dependent code */
207 #if DECDPUN<=4
208 #define eInt Int /* extended integer */
209 #define ueInt uInt /* unsigned extended integer */
210 /* Constant multipliers for divide-by-power-of five using reciprocal */
211 /* multiply, after removing powers of 2 by shifting, and final shift */
212 /* of 17 [we only need up to **4] */
213 static const uInt multies[]={131073, 26215, 5243, 1049, 210};
214 /* QUOT10 -- macro to return the quotient of unit u divided by 10**n */
215 #define QUOT10(u, n) ((((uInt)(u)>>(n))*multies[n])>>17)
216 #else
217 /* For DECDPUN>4 non-ANSI-89 64-bit types are needed. */
218 #if !DECUSE64
219 #error decNumber.c: DECUSE64 must be 1 when DECDPUN>4
220 #endif
221 #define eInt Long /* extended integer */
222 #define ueInt uLong /* unsigned extended integer */
223 #endif
225 /* Local routines */
226 static decNumber * decAddOp(decNumber *, const decNumber *, const decNumber *,
227 decContext *, uByte, uInt *);
228 static Flag decBiStr(const char *, const char *, const char *);
229 static uInt decCheckMath(const decNumber *, decContext *, uInt *);
230 static void decApplyRound(decNumber *, decContext *, Int, uInt *);
231 static Int decCompare(const decNumber *lhs, const decNumber *rhs, Flag);
232 static decNumber * decCompareOp(decNumber *, const decNumber *,
233 const decNumber *, decContext *,
234 Flag, uInt *);
235 static void decCopyFit(decNumber *, const decNumber *, decContext *,
236 Int *, uInt *);
237 static decNumber * decDecap(decNumber *, Int);
238 static decNumber * decDivideOp(decNumber *, const decNumber *,
239 const decNumber *, decContext *, Flag, uInt *);
240 static decNumber * decExpOp(decNumber *, const decNumber *,
241 decContext *, uInt *);
242 static void decFinalize(decNumber *, decContext *, Int *, uInt *);
243 static Int decGetDigits(Unit *, Int);
244 static Int decGetInt(const decNumber *);
245 static decNumber * decLnOp(decNumber *, const decNumber *,
246 decContext *, uInt *);
247 static decNumber * decMultiplyOp(decNumber *, const decNumber *,
248 const decNumber *, decContext *,
249 uInt *);
250 static decNumber * decNaNs(decNumber *, const decNumber *,
251 const decNumber *, decContext *, uInt *);
252 static decNumber * decQuantizeOp(decNumber *, const decNumber *,
253 const decNumber *, decContext *, Flag,
254 uInt *);
255 static void decReverse(Unit *, Unit *);
256 static void decSetCoeff(decNumber *, decContext *, const Unit *,
257 Int, Int *, uInt *);
258 static void decSetMaxValue(decNumber *, decContext *);
259 static void decSetOverflow(decNumber *, decContext *, uInt *);
260 static void decSetSubnormal(decNumber *, decContext *, Int *, uInt *);
261 static Int decShiftToLeast(Unit *, Int, Int);
262 static Int decShiftToMost(Unit *, Int, Int);
263 static void decStatus(decNumber *, uInt, decContext *);
264 static void decToString(const decNumber *, char[], Flag);
265 static decNumber * decTrim(decNumber *, decContext *, Flag, Int *);
266 static Int decUnitAddSub(const Unit *, Int, const Unit *, Int, Int,
267 Unit *, Int);
268 static Int decUnitCompare(const Unit *, Int, const Unit *, Int, Int);
270 #if !DECSUBSET
271 /* decFinish == decFinalize when no subset arithmetic needed */
272 #define decFinish(a,b,c,d) decFinalize(a,b,c,d)
273 #else
274 static void decFinish(decNumber *, decContext *, Int *, uInt *);
275 static decNumber * decRoundOperand(const decNumber *, decContext *, uInt *);
276 #endif
278 /* Local macros */
279 /* masked special-values bits */
280 #define SPECIALARG (rhs->bits & DECSPECIAL)
281 #define SPECIALARGS ((lhs->bits | rhs->bits) & DECSPECIAL)
283 /* Diagnostic macros, etc. */
284 #if DECALLOC
285 /* Handle malloc/free accounting. If enabled, our accountable routines */
286 /* are used; otherwise the code just goes straight to the system malloc */
287 /* and free routines. */
288 #define malloc(a) decMalloc(a)
289 #define free(a) decFree(a)
290 #define DECFENCE 0x5a /* corruption detector */
291 /* 'Our' malloc and free: */
292 static void *decMalloc(size_t);
293 static void decFree(void *);
294 uInt decAllocBytes=0; /* count of bytes allocated */
295 /* Note that DECALLOC code only checks for storage buffer overflow. */
296 /* To check for memory leaks, the decAllocBytes variable must be */
297 /* checked to be 0 at appropriate times (e.g., after the test */
298 /* harness completes a set of tests). This checking may be unreliable */
299 /* if the testing is done in a multi-thread environment. */
300 #endif
302 #if DECCHECK
303 /* Optional checking routines. Enabling these means that decNumber */
304 /* and decContext operands to operator routines are checked for */
305 /* correctness. This roughly doubles the execution time of the */
306 /* fastest routines (and adds 600+ bytes), so should not normally be */
307 /* used in 'production'. */
308 /* decCheckInexact is used to check that inexact results have a full */
309 /* complement of digits (where appropriate -- this is not the case */
310 /* for Quantize, for example) */
311 #define DECUNRESU ((decNumber *)(void *)0xffffffff)
312 #define DECUNUSED ((const decNumber *)(void *)0xffffffff)
313 #define DECUNCONT ((decContext *)(void *)(0xffffffff))
314 static Flag decCheckOperands(decNumber *, const decNumber *,
315 const decNumber *, decContext *);
316 static Flag decCheckNumber(const decNumber *);
317 static void decCheckInexact(const decNumber *, decContext *);
318 #endif
320 #if DECTRACE || DECCHECK
321 /* Optional trace/debugging routines (may or may not be used) */
322 void decNumberShow(const decNumber *); /* displays the components of a number */
323 static void decDumpAr(char, const Unit *, Int);
324 #endif
326 /* ================================================================== */
327 /* Conversions */
328 /* ================================================================== */
330 /* ------------------------------------------------------------------ */
331 /* from-int32 -- conversion from Int or uInt */
332 /* */
333 /* dn is the decNumber to receive the integer */
334 /* in or uin is the integer to be converted */
335 /* returns dn */
336 /* */
337 /* No error is possible. */
338 /* ------------------------------------------------------------------ */
339 decNumber * decNumberFromInt32(decNumber *dn, Int in) {
340 uInt unsig;
341 if (in>=0) unsig=in;
342 else { /* negative (possibly BADINT) */
343 if (in==BADINT) unsig=(uInt)1073741824*2; /* special case */
344 else unsig=-in; /* invert */
346 /* in is now positive */
347 decNumberFromUInt32(dn, unsig);
348 if (in<0) dn->bits=DECNEG; /* sign needed */
349 return dn;
350 } /* decNumberFromInt32 */
352 decNumber * decNumberFromUInt32(decNumber *dn, uInt uin) {
353 Unit *up; /* work pointer */
354 decNumberZero(dn); /* clean */
355 if (uin==0) return dn; /* [or decGetDigits bad call] */
356 for (up=dn->lsu; uin>0; up++) {
357 *up=(Unit)(uin%(DECDPUNMAX+1));
358 uin=uin/(DECDPUNMAX+1);
360 dn->digits=decGetDigits(dn->lsu, up-dn->lsu);
361 return dn;
362 } /* decNumberFromUInt32 */
364 /* ------------------------------------------------------------------ */
365 /* to-int32 -- conversion to Int or uInt */
366 /* */
367 /* dn is the decNumber to convert */
368 /* set is the context for reporting errors */
369 /* returns the converted decNumber, or 0 if Invalid is set */
370 /* */
371 /* Invalid is set if the decNumber does not have exponent==0 or if */
372 /* it is a NaN, Infinite, or out-of-range. */
373 /* ------------------------------------------------------------------ */
374 Int decNumberToInt32(const decNumber *dn, decContext *set) {
375 #if DECCHECK
376 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
377 #endif
379 /* special or too many digits, or bad exponent */
380 if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0) ; /* bad */
381 else { /* is a finite integer with 10 or fewer digits */
382 Int d; /* work */
383 const Unit *up; /* .. */
384 uInt hi=0, lo; /* .. */
385 up=dn->lsu; /* -> lsu */
386 lo=*up; /* get 1 to 9 digits */
387 #if DECDPUN>1 /* split to higher */
388 hi=lo/10;
389 lo=lo%10;
390 #endif
391 up++;
392 /* collect remaining Units, if any, into hi */
393 for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
394 /* now low has the lsd, hi the remainder */
395 if (hi>214748364 || (hi==214748364 && lo>7)) { /* out of range? */
396 /* most-negative is a reprieve */
397 if (dn->bits&DECNEG && hi==214748364 && lo==8) return 0x80000000;
398 /* bad -- drop through */
400 else { /* in-range always */
401 Int i=X10(hi)+lo;
402 if (dn->bits&DECNEG) return -i;
403 return i;
405 } /* integer */
406 decContextSetStatus(set, DEC_Invalid_operation); /* [may not return] */
407 return 0;
408 } /* decNumberToInt32 */
410 uInt decNumberToUInt32(const decNumber *dn, decContext *set) {
411 #if DECCHECK
412 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
413 #endif
414 /* special or too many digits, or bad exponent, or negative (<0) */
415 if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0
416 || (dn->bits&DECNEG && !ISZERO(dn))); /* bad */
417 else { /* is a finite integer with 10 or fewer digits */
418 Int d; /* work */
419 const Unit *up; /* .. */
420 uInt hi=0, lo; /* .. */
421 up=dn->lsu; /* -> lsu */
422 lo=*up; /* get 1 to 9 digits */
423 #if DECDPUN>1 /* split to higher */
424 hi=lo/10;
425 lo=lo%10;
426 #endif
427 up++;
428 /* collect remaining Units, if any, into hi */
429 for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
431 /* now low has the lsd, hi the remainder */
432 if (hi>429496729 || (hi==429496729 && lo>5)) ; /* no reprieve possible */
433 else return X10(hi)+lo;
434 } /* integer */
435 decContextSetStatus(set, DEC_Invalid_operation); /* [may not return] */
436 return 0;
437 } /* decNumberToUInt32 */
439 /* ------------------------------------------------------------------ */
440 /* to-scientific-string -- conversion to numeric string */
441 /* to-engineering-string -- conversion to numeric string */
442 /* */
443 /* decNumberToString(dn, string); */
444 /* decNumberToEngString(dn, string); */
445 /* */
446 /* dn is the decNumber to convert */
447 /* string is the string where the result will be laid out */
448 /* */
449 /* string must be at least dn->digits+14 characters long */
450 /* */
451 /* No error is possible, and no status can be set. */
452 /* ------------------------------------------------------------------ */
453 char * decNumberToString(const decNumber *dn, char *string){
454 decToString(dn, string, 0);
455 return string;
456 } /* DecNumberToString */
458 char * decNumberToEngString(const decNumber *dn, char *string){
459 decToString(dn, string, 1);
460 return string;
461 } /* DecNumberToEngString */
463 /* ------------------------------------------------------------------ */
464 /* to-number -- conversion from numeric string */
465 /* */
466 /* decNumberFromString -- convert string to decNumber */
467 /* dn -- the number structure to fill */
468 /* chars[] -- the string to convert ('\0' terminated) */
469 /* set -- the context used for processing any error, */
470 /* determining the maximum precision available */
471 /* (set.digits), determining the maximum and minimum */
472 /* exponent (set.emax and set.emin), determining if */
473 /* extended values are allowed, and checking the */
474 /* rounding mode if overflow occurs or rounding is */
475 /* needed. */
476 /* */
477 /* The length of the coefficient and the size of the exponent are */
478 /* checked by this routine, so the correct error (Underflow or */
479 /* Overflow) can be reported or rounding applied, as necessary. */
480 /* */
481 /* If bad syntax is detected, the result will be a quiet NaN. */
482 /* ------------------------------------------------------------------ */
483 decNumber * decNumberFromString(decNumber *dn, const char chars[],
484 decContext *set) {
485 Int exponent=0; /* working exponent [assume 0] */
486 uByte bits=0; /* working flags [assume +ve] */
487 Unit *res; /* where result will be built */
488 Unit resbuff[SD2U(DECBUFFER+9)];/* local buffer in case need temporary */
489 /* [+9 allows for ln() constants] */
490 Unit *allocres=NULL; /* -> allocated result, iff allocated */
491 Int d=0; /* count of digits found in decimal part */
492 const char *dotchar=NULL; /* where dot was found */
493 const char *cfirst=chars; /* -> first character of decimal part */
494 const char *last=NULL; /* -> last digit of decimal part */
495 const char *c; /* work */
496 Unit *up; /* .. */
497 #if DECDPUN>1
498 Int cut, out; /* .. */
499 #endif
500 Int residue; /* rounding residue */
501 uInt status=0; /* error code */
503 #if DECCHECK
504 if (decCheckOperands(DECUNRESU, DECUNUSED, DECUNUSED, set))
505 return decNumberZero(dn);
506 #endif
508 do { /* status & malloc protection */
509 for (c=chars;; c++) { /* -> input character */
510 if (*c>='0' && *c<='9') { /* test for Arabic digit */
511 last=c;
512 d++; /* count of real digits */
513 continue; /* still in decimal part */
515 if (*c=='.' && dotchar==NULL) { /* first '.' */
516 dotchar=c; /* record offset into decimal part */
517 if (c==cfirst) cfirst++; /* first digit must follow */
518 continue;}
519 if (c==chars) { /* first in string... */
520 if (*c=='-') { /* valid - sign */
521 cfirst++;
522 bits=DECNEG;
523 continue;}
524 if (*c=='+') { /* valid + sign */
525 cfirst++;
526 continue;}
528 /* *c is not a digit, or a valid +, -, or '.' */
529 break;
530 } /* c */
532 if (last==NULL) { /* no digits yet */
533 status=DEC_Conversion_syntax;/* assume the worst */
534 if (*c=='\0') break; /* and no more to come... */
535 #if DECSUBSET
536 /* if subset then infinities and NaNs are not allowed */
537 if (!set->extended) break; /* hopeless */
538 #endif
539 /* Infinities and NaNs are possible, here */
540 if (dotchar!=NULL) break; /* .. unless had a dot */
541 decNumberZero(dn); /* be optimistic */
542 if (decBiStr(c, "infinity", "INFINITY")
543 || decBiStr(c, "inf", "INF")) {
544 dn->bits=bits | DECINF;
545 status=0; /* is OK */
546 break; /* all done */
548 /* a NaN expected */
549 /* 2003.09.10 NaNs are now permitted to have a sign */
550 dn->bits=bits | DECNAN; /* assume simple NaN */
551 if (*c=='s' || *c=='S') { /* looks like an sNaN */
552 c++;
553 dn->bits=bits | DECSNAN;
555 if (*c!='n' && *c!='N') break; /* check caseless "NaN" */
556 c++;
557 if (*c!='a' && *c!='A') break; /* .. */
558 c++;
559 if (*c!='n' && *c!='N') break; /* .. */
560 c++;
561 /* now either nothing, or nnnn payload, expected */
562 /* -> start of integer and skip leading 0s [including plain 0] */
563 for (cfirst=c; *cfirst=='0';) cfirst++;
564 if (*cfirst=='\0') { /* "NaN" or "sNaN", maybe with all 0s */
565 status=0; /* it's good */
566 break; /* .. */
568 /* something other than 0s; setup last and d as usual [no dots] */
569 for (c=cfirst;; c++, d++) {
570 if (*c<'0' || *c>'9') break; /* test for Arabic digit */
571 last=c;
573 if (*c!='\0') break; /* not all digits */
574 if (d>set->digits-1) {
575 /* [NB: payload in a decNumber can be full length unless */
576 /* clamped, in which case can only be digits-1] */
577 if (set->clamp) break;
578 if (d>set->digits) break;
579 } /* too many digits? */
580 /* good; drop through to convert the integer to coefficient */
581 status=0; /* syntax is OK */
582 bits=dn->bits; /* for copy-back */
583 } /* last==NULL */
585 else if (*c!='\0') { /* more to process... */
586 /* had some digits; exponent is only valid sequence now */
587 Flag nege; /* 1=negative exponent */
588 const char *firstexp; /* -> first significant exponent digit */
589 status=DEC_Conversion_syntax;/* assume the worst */
590 if (*c!='e' && *c!='E') break;
591 /* Found 'e' or 'E' -- now process explicit exponent */
592 /* 1998.07.11: sign no longer required */
593 nege=0;
594 c++; /* to (possible) sign */
595 if (*c=='-') {nege=1; c++;}
596 else if (*c=='+') c++;
597 if (*c=='\0') break;
599 for (; *c=='0' && *(c+1)!='\0';) c++; /* strip insignificant zeros */
600 firstexp=c; /* save exponent digit place */
601 for (; ;c++) {
602 if (*c<'0' || *c>'9') break; /* not a digit */
603 exponent=X10(exponent)+(Int)*c-(Int)'0';
604 } /* c */
605 /* if not now on a '\0', *c must not be a digit */
606 if (*c!='\0') break;
608 /* (this next test must be after the syntax checks) */
609 /* if it was too long the exponent may have wrapped, so check */
610 /* carefully and set it to a certain overflow if wrap possible */
611 if (c>=firstexp+9+1) {
612 if (c>firstexp+9+1 || *firstexp>'1') exponent=DECNUMMAXE*2;
613 /* [up to 1999999999 is OK, for example 1E-1000000998] */
615 if (nege) exponent=-exponent; /* was negative */
616 status=0; /* is OK */
617 } /* stuff after digits */
619 /* Here when whole string has been inspected; syntax is good */
620 /* cfirst->first digit (never dot), last->last digit (ditto) */
622 /* strip leading zeros/dot [leave final 0 if all 0's] */
623 if (*cfirst=='0') { /* [cfirst has stepped over .] */
624 for (c=cfirst; c<last; c++, cfirst++) {
625 if (*c=='.') continue; /* ignore dots */
626 if (*c!='0') break; /* non-zero found */
627 d--; /* 0 stripped */
628 } /* c */
629 #if DECSUBSET
630 /* make a rapid exit for easy zeros if !extended */
631 if (*cfirst=='0' && !set->extended) {
632 decNumberZero(dn); /* clean result */
633 break; /* [could be return] */
635 #endif
636 } /* at least one leading 0 */
638 /* Handle decimal point... */
639 if (dotchar!=NULL && dotchar<last) /* non-trailing '.' found? */
640 exponent-=(last-dotchar); /* adjust exponent */
641 /* [we can now ignore the .] */
643 /* OK, the digits string is good. Assemble in the decNumber, or in */
644 /* a temporary units array if rounding is needed */
645 if (d<=set->digits) res=dn->lsu; /* fits into supplied decNumber */
646 else { /* rounding needed */
647 Int needbytes=D2U(d)*sizeof(Unit);/* bytes needed */
648 res=resbuff; /* assume use local buffer */
649 if (needbytes>(Int)sizeof(resbuff)) { /* too big for local */
650 allocres=(Unit *)malloc(needbytes);
651 if (allocres==NULL) {status|=DEC_Insufficient_storage; break;}
652 res=allocres;
655 /* res now -> number lsu, buffer, or allocated storage for Unit array */
657 /* Place the coefficient into the selected Unit array */
658 /* [this is often 70% of the cost of this function when DECDPUN>1] */
659 #if DECDPUN>1
660 out=0; /* accumulator */
661 up=res+D2U(d)-1; /* -> msu */
662 cut=d-(up-res)*DECDPUN; /* digits in top unit */
663 for (c=cfirst;; c++) { /* along the digits */
664 if (*c=='.') continue; /* ignore '.' [don't decrement cut] */
665 out=X10(out)+(Int)*c-(Int)'0';
666 if (c==last) break; /* done [never get to trailing '.'] */
667 cut--;
668 if (cut>0) continue; /* more for this unit */
669 *up=(Unit)out; /* write unit */
670 up--; /* prepare for unit below.. */
671 cut=DECDPUN; /* .. */
672 out=0; /* .. */
673 } /* c */
674 *up=(Unit)out; /* write lsu */
676 #else
677 /* DECDPUN==1 */
678 up=res; /* -> lsu */
679 for (c=last; c>=cfirst; c--) { /* over each character, from least */
680 if (*c=='.') continue; /* ignore . [don't step up] */
681 *up=(Unit)((Int)*c-(Int)'0');
682 up++;
683 } /* c */
684 #endif
686 dn->bits=bits;
687 dn->exponent=exponent;
688 dn->digits=d;
690 /* if not in number (too long) shorten into the number */
691 if (d>set->digits) {
692 residue=0;
693 decSetCoeff(dn, set, res, d, &residue, &status);
694 /* always check for overflow or subnormal and round as needed */
695 decFinalize(dn, set, &residue, &status);
697 else { /* no rounding, but may still have overflow or subnormal */
698 /* [these tests are just for performance; finalize repeats them] */
699 if ((dn->exponent-1<set->emin-dn->digits)
700 || (dn->exponent-1>set->emax-set->digits)) {
701 residue=0;
702 decFinalize(dn, set, &residue, &status);
705 /* decNumberShow(dn); */
706 } while(0); /* [for break] */
708 if (allocres!=NULL) free(allocres); /* drop any storage used */
709 if (status!=0) decStatus(dn, status, set);
710 return dn;
711 } /* decNumberFromString */
713 /* ================================================================== */
714 /* Operators */
715 /* ================================================================== */
717 /* ------------------------------------------------------------------ */
718 /* decNumberAbs -- absolute value operator */
719 /* */
720 /* This computes C = abs(A) */
721 /* */
722 /* res is C, the result. C may be A */
723 /* rhs is A */
724 /* set is the context */
725 /* */
726 /* See also decNumberCopyAbs for a quiet bitwise version of this. */
727 /* C must have space for set->digits digits. */
728 /* ------------------------------------------------------------------ */
729 /* This has the same effect as decNumberPlus unless A is negative, */
730 /* in which case it has the same effect as decNumberMinus. */
731 /* ------------------------------------------------------------------ */
732 decNumber * decNumberAbs(decNumber *res, const decNumber *rhs,
733 decContext *set) {
734 decNumber dzero; /* for 0 */
735 uInt status=0; /* accumulator */
737 #if DECCHECK
738 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
739 #endif
741 decNumberZero(&dzero); /* set 0 */
742 dzero.exponent=rhs->exponent; /* [no coefficient expansion] */
743 decAddOp(res, &dzero, rhs, set, (uByte)(rhs->bits & DECNEG), &status);
744 if (status!=0) decStatus(res, status, set);
745 #if DECCHECK
746 decCheckInexact(res, set);
747 #endif
748 return res;
749 } /* decNumberAbs */
751 /* ------------------------------------------------------------------ */
752 /* decNumberAdd -- add two Numbers */
753 /* */
754 /* This computes C = A + B */
755 /* */
756 /* res is C, the result. C may be A and/or B (e.g., X=X+X) */
757 /* lhs is A */
758 /* rhs is B */
759 /* set is the context */
760 /* */
761 /* C must have space for set->digits digits. */
762 /* ------------------------------------------------------------------ */
763 /* This just calls the routine shared with Subtract */
764 decNumber * decNumberAdd(decNumber *res, const decNumber *lhs,
765 const decNumber *rhs, decContext *set) {
766 uInt status=0; /* accumulator */
767 decAddOp(res, lhs, rhs, set, 0, &status);
768 if (status!=0) decStatus(res, status, set);
769 #if DECCHECK
770 decCheckInexact(res, set);
771 #endif
772 return res;
773 } /* decNumberAdd */
775 /* ------------------------------------------------------------------ */
776 /* decNumberAnd -- AND two Numbers, digitwise */
777 /* */
778 /* This computes C = A & B */
779 /* */
780 /* res is C, the result. C may be A and/or B (e.g., X=X&X) */
781 /* lhs is A */
782 /* rhs is B */
783 /* set is the context (used for result length and error report) */
784 /* */
785 /* C must have space for set->digits digits. */
786 /* */
787 /* Logical function restrictions apply (see above); a NaN is */
788 /* returned with Invalid_operation if a restriction is violated. */
789 /* ------------------------------------------------------------------ */
790 decNumber * decNumberAnd(decNumber *res, const decNumber *lhs,
791 const decNumber *rhs, decContext *set) {
792 const Unit *ua, *ub; /* -> operands */
793 const Unit *msua, *msub; /* -> operand msus */
794 Unit *uc, *msuc; /* -> result and its msu */
795 Int msudigs; /* digits in res msu */
796 #if DECCHECK
797 if (decCheckOperands(res, lhs, rhs, set)) return res;
798 #endif
800 if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
801 || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
802 decStatus(res, DEC_Invalid_operation, set);
803 return res;
806 /* operands are valid */
807 ua=lhs->lsu; /* bottom-up */
808 ub=rhs->lsu; /* .. */
809 uc=res->lsu; /* .. */
810 msua=ua+D2U(lhs->digits)-1; /* -> msu of lhs */
811 msub=ub+D2U(rhs->digits)-1; /* -> msu of rhs */
812 msuc=uc+D2U(set->digits)-1; /* -> msu of result */
813 msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */
814 for (; uc<=msuc; ua++, ub++, uc++) { /* Unit loop */
815 Unit a, b; /* extract units */
816 if (ua>msua) a=0;
817 else a=*ua;
818 if (ub>msub) b=0;
819 else b=*ub;
820 *uc=0; /* can now write back */
821 if (a|b) { /* maybe 1 bits to examine */
822 Int i, j;
823 *uc=0; /* can now write back */
824 /* This loop could be unrolled and/or use BIN2BCD tables */
825 for (i=0; i<DECDPUN; i++) {
826 if (a&b&1) *uc=*uc+(Unit)powers[i]; /* effect AND */
827 j=a%10;
828 a=a/10;
829 j|=b%10;
830 b=b/10;
831 if (j>1) {
832 decStatus(res, DEC_Invalid_operation, set);
833 return res;
835 if (uc==msuc && i==msudigs-1) break; /* just did final digit */
836 } /* each digit */
837 } /* both OK */
838 } /* each unit */
839 /* [here uc-1 is the msu of the result] */
840 res->digits=decGetDigits(res->lsu, uc-res->lsu);
841 res->exponent=0; /* integer */
842 res->bits=0; /* sign=0 */
843 return res; /* [no status to set] */
844 } /* decNumberAnd */
846 /* ------------------------------------------------------------------ */
847 /* decNumberCompare -- compare two Numbers */
848 /* */
849 /* This computes C = A ? B */
850 /* */
851 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
852 /* lhs is A */
853 /* rhs is B */
854 /* set is the context */
855 /* */
856 /* C must have space for one digit (or NaN). */
857 /* ------------------------------------------------------------------ */
858 decNumber * decNumberCompare(decNumber *res, const decNumber *lhs,
859 const decNumber *rhs, decContext *set) {
860 uInt status=0; /* accumulator */
861 decCompareOp(res, lhs, rhs, set, COMPARE, &status);
862 if (status!=0) decStatus(res, status, set);
863 return res;
864 } /* decNumberCompare */
866 /* ------------------------------------------------------------------ */
867 /* decNumberCompareSignal -- compare, signalling on all NaNs */
868 /* */
869 /* This computes C = A ? B */
870 /* */
871 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
872 /* lhs is A */
873 /* rhs is B */
874 /* set is the context */
875 /* */
876 /* C must have space for one digit (or NaN). */
877 /* ------------------------------------------------------------------ */
878 decNumber * decNumberCompareSignal(decNumber *res, const decNumber *lhs,
879 const decNumber *rhs, decContext *set) {
880 uInt status=0; /* accumulator */
881 decCompareOp(res, lhs, rhs, set, COMPSIG, &status);
882 if (status!=0) decStatus(res, status, set);
883 return res;
884 } /* decNumberCompareSignal */
886 /* ------------------------------------------------------------------ */
887 /* decNumberCompareTotal -- compare two Numbers, using total ordering */
888 /* */
889 /* This computes C = A ? B, under total ordering */
890 /* */
891 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
892 /* lhs is A */
893 /* rhs is B */
894 /* set is the context */
895 /* */
896 /* C must have space for one digit; the result will always be one of */
897 /* -1, 0, or 1. */
898 /* ------------------------------------------------------------------ */
899 decNumber * decNumberCompareTotal(decNumber *res, const decNumber *lhs,
900 const decNumber *rhs, decContext *set) {
901 uInt status=0; /* accumulator */
902 decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
903 if (status!=0) decStatus(res, status, set);
904 return res;
905 } /* decNumberCompareTotal */
907 /* ------------------------------------------------------------------ */
908 /* decNumberCompareTotalMag -- compare, total ordering of magnitudes */
909 /* */
910 /* This computes C = |A| ? |B|, under total ordering */
911 /* */
912 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
913 /* lhs is A */
914 /* rhs is B */
915 /* set is the context */
916 /* */
917 /* C must have space for one digit; the result will always be one of */
918 /* -1, 0, or 1. */
919 /* ------------------------------------------------------------------ */
920 decNumber * decNumberCompareTotalMag(decNumber *res, const decNumber *lhs,
921 const decNumber *rhs, decContext *set) {
922 uInt status=0; /* accumulator */
923 uInt needbytes; /* for space calculations */
924 decNumber bufa[D2N(DECBUFFER+1)];/* +1 in case DECBUFFER=0 */
925 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
926 decNumber bufb[D2N(DECBUFFER+1)];
927 decNumber *allocbufb=NULL; /* -> allocated bufb, iff allocated */
928 decNumber *a, *b; /* temporary pointers */
930 #if DECCHECK
931 if (decCheckOperands(res, lhs, rhs, set)) return res;
932 #endif
934 do { /* protect allocated storage */
935 /* if either is negative, take a copy and absolute */
936 if (decNumberIsNegative(lhs)) { /* lhs<0 */
937 a=bufa;
938 needbytes=sizeof(decNumber)+(D2U(lhs->digits)-1)*sizeof(Unit);
939 if (needbytes>sizeof(bufa)) { /* need malloc space */
940 allocbufa=(decNumber *)malloc(needbytes);
941 if (allocbufa==NULL) { /* hopeless -- abandon */
942 status|=DEC_Insufficient_storage;
943 break;}
944 a=allocbufa; /* use the allocated space */
946 decNumberCopy(a, lhs); /* copy content */
947 a->bits&=~DECNEG; /* .. and clear the sign */
948 lhs=a; /* use copy from here on */
950 if (decNumberIsNegative(rhs)) { /* rhs<0 */
951 b=bufb;
952 needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
953 if (needbytes>sizeof(bufb)) { /* need malloc space */
954 allocbufb=(decNumber *)malloc(needbytes);
955 if (allocbufb==NULL) { /* hopeless -- abandon */
956 status|=DEC_Insufficient_storage;
957 break;}
958 b=allocbufb; /* use the allocated space */
960 decNumberCopy(b, rhs); /* copy content */
961 b->bits&=~DECNEG; /* .. and clear the sign */
962 rhs=b; /* use copy from here on */
964 decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
965 } while(0); /* end protected */
967 if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */
968 if (allocbufb!=NULL) free(allocbufb); /* .. */
969 if (status!=0) decStatus(res, status, set);
970 return res;
971 } /* decNumberCompareTotalMag */
973 /* ------------------------------------------------------------------ */
974 /* decNumberDivide -- divide one number by another */
975 /* */
976 /* This computes C = A / B */
977 /* */
978 /* res is C, the result. C may be A and/or B (e.g., X=X/X) */
979 /* lhs is A */
980 /* rhs is B */
981 /* set is the context */
982 /* */
983 /* C must have space for set->digits digits. */
984 /* ------------------------------------------------------------------ */
985 decNumber * decNumberDivide(decNumber *res, const decNumber *lhs,
986 const decNumber *rhs, decContext *set) {
987 uInt status=0; /* accumulator */
988 decDivideOp(res, lhs, rhs, set, DIVIDE, &status);
989 if (status!=0) decStatus(res, status, set);
990 #if DECCHECK
991 decCheckInexact(res, set);
992 #endif
993 return res;
994 } /* decNumberDivide */
996 /* ------------------------------------------------------------------ */
997 /* decNumberDivideInteger -- divide and return integer quotient */
998 /* */
999 /* This computes C = A # B, where # is the integer divide operator */
1000 /* */
1001 /* res is C, the result. C may be A and/or B (e.g., X=X#X) */
1002 /* lhs is A */
1003 /* rhs is B */
1004 /* set is the context */
1005 /* */
1006 /* C must have space for set->digits digits. */
1007 /* ------------------------------------------------------------------ */
1008 decNumber * decNumberDivideInteger(decNumber *res, const decNumber *lhs,
1009 const decNumber *rhs, decContext *set) {
1010 uInt status=0; /* accumulator */
1011 decDivideOp(res, lhs, rhs, set, DIVIDEINT, &status);
1012 if (status!=0) decStatus(res, status, set);
1013 return res;
1014 } /* decNumberDivideInteger */
1016 /* ------------------------------------------------------------------ */
1017 /* decNumberExp -- exponentiation */
1018 /* */
1019 /* This computes C = exp(A) */
1020 /* */
1021 /* res is C, the result. C may be A */
1022 /* rhs is A */
1023 /* set is the context; note that rounding mode has no effect */
1024 /* */
1025 /* C must have space for set->digits digits. */
1026 /* */
1027 /* Mathematical function restrictions apply (see above); a NaN is */
1028 /* returned with Invalid_operation if a restriction is violated. */
1029 /* */
1030 /* Finite results will always be full precision and Inexact, except */
1031 /* when A is a zero or -Infinity (giving 1 or 0 respectively). */
1032 /* */
1033 /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */
1034 /* almost always be correctly rounded, but may be up to 1 ulp in */
1035 /* error in rare cases. */
1036 /* ------------------------------------------------------------------ */
1037 /* This is a wrapper for decExpOp which can handle the slightly wider */
1038 /* (double) range needed by Ln (which has to be able to calculate */
1039 /* exp(-a) where a can be the tiniest number (Ntiny). */
1040 /* ------------------------------------------------------------------ */
1041 decNumber * decNumberExp(decNumber *res, const decNumber *rhs,
1042 decContext *set) {
1043 uInt status=0; /* accumulator */
1044 #if DECSUBSET
1045 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */
1046 #endif
1048 #if DECCHECK
1049 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1050 #endif
1052 /* Check restrictions; these restrictions ensure that if h=8 (see */
1053 /* decExpOp) then the result will either overflow or underflow to 0. */
1054 /* Other math functions restrict the input range, too, for inverses. */
1055 /* If not violated then carry out the operation. */
1056 if (!decCheckMath(rhs, set, &status)) do { /* protect allocation */
1057 #if DECSUBSET
1058 if (!set->extended) {
1059 /* reduce operand and set lostDigits status, as needed */
1060 if (rhs->digits>set->digits) {
1061 allocrhs=decRoundOperand(rhs, set, &status);
1062 if (allocrhs==NULL) break;
1063 rhs=allocrhs;
1066 #endif
1067 decExpOp(res, rhs, set, &status);
1068 } while(0); /* end protected */
1070 #if DECSUBSET
1071 if (allocrhs !=NULL) free(allocrhs); /* drop any storage used */
1072 #endif
1073 /* apply significant status */
1074 if (status!=0) decStatus(res, status, set);
1075 #if DECCHECK
1076 decCheckInexact(res, set);
1077 #endif
1078 return res;
1079 } /* decNumberExp */
1081 /* ------------------------------------------------------------------ */
1082 /* decNumberFMA -- fused multiply add */
1083 /* */
1084 /* This computes D = (A * B) + C with only one rounding */
1085 /* */
1086 /* res is D, the result. D may be A or B or C (e.g., X=FMA(X,X,X)) */
1087 /* lhs is A */
1088 /* rhs is B */
1089 /* fhs is C [far hand side] */
1090 /* set is the context */
1091 /* */
1092 /* Mathematical function restrictions apply (see above); a NaN is */
1093 /* returned with Invalid_operation if a restriction is violated. */
1094 /* */
1095 /* C must have space for set->digits digits. */
1096 /* ------------------------------------------------------------------ */
1097 decNumber * decNumberFMA(decNumber *res, const decNumber *lhs,
1098 const decNumber *rhs, const decNumber *fhs,
1099 decContext *set) {
1100 uInt status=0; /* accumulator */
1101 decContext dcmul; /* context for the multiplication */
1102 uInt needbytes; /* for space calculations */
1103 decNumber bufa[D2N(DECBUFFER*2+1)];
1104 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
1105 decNumber *acc; /* accumulator pointer */
1106 decNumber dzero; /* work */
1108 #if DECCHECK
1109 if (decCheckOperands(res, lhs, rhs, set)) return res;
1110 if (decCheckOperands(res, fhs, DECUNUSED, set)) return res;
1111 #endif
1113 do { /* protect allocated storage */
1114 #if DECSUBSET
1115 if (!set->extended) { /* [undefined if subset] */
1116 status|=DEC_Invalid_operation;
1117 break;}
1118 #endif
1119 /* Check math restrictions [these ensure no overflow or underflow] */
1120 if ((!decNumberIsSpecial(lhs) && decCheckMath(lhs, set, &status))
1121 || (!decNumberIsSpecial(rhs) && decCheckMath(rhs, set, &status))
1122 || (!decNumberIsSpecial(fhs) && decCheckMath(fhs, set, &status))) break;
1123 /* set up context for multiply */
1124 dcmul=*set;
1125 dcmul.digits=lhs->digits+rhs->digits; /* just enough */
1126 /* [The above may be an over-estimate for subset arithmetic, but that's OK] */
1127 dcmul.emax=DEC_MAX_EMAX; /* effectively unbounded .. */
1128 dcmul.emin=DEC_MIN_EMIN; /* [thanks to Math restrictions] */
1129 /* set up decNumber space to receive the result of the multiply */
1130 acc=bufa; /* may fit */
1131 needbytes=sizeof(decNumber)+(D2U(dcmul.digits)-1)*sizeof(Unit);
1132 if (needbytes>sizeof(bufa)) { /* need malloc space */
1133 allocbufa=(decNumber *)malloc(needbytes);
1134 if (allocbufa==NULL) { /* hopeless -- abandon */
1135 status|=DEC_Insufficient_storage;
1136 break;}
1137 acc=allocbufa; /* use the allocated space */
1139 /* multiply with extended range and necessary precision */
1140 /*printf("emin=%ld\n", dcmul.emin); */
1141 decMultiplyOp(acc, lhs, rhs, &dcmul, &status);
1142 /* Only Invalid operation (from sNaN or Inf * 0) is possible in */
1143 /* status; if either is seen than ignore fhs (in case it is */
1144 /* another sNaN) and set acc to NaN unless we had an sNaN */
1145 /* [decMultiplyOp leaves that to caller] */
1146 /* Note sNaN has to go through addOp to shorten payload if */
1147 /* necessary */
1148 if ((status&DEC_Invalid_operation)!=0) {
1149 if (!(status&DEC_sNaN)) { /* but be true invalid */
1150 decNumberZero(res); /* acc not yet set */
1151 res->bits=DECNAN;
1152 break;
1154 decNumberZero(&dzero); /* make 0 (any non-NaN would do) */
1155 fhs=&dzero; /* use that */
1157 #if DECCHECK
1158 else { /* multiply was OK */
1159 if (status!=0) printf("Status=%08lx after FMA multiply\n", status);
1161 #endif
1162 /* add the third operand and result -> res, and all is done */
1163 decAddOp(res, acc, fhs, set, 0, &status);
1164 } while(0); /* end protected */
1166 if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */
1167 if (status!=0) decStatus(res, status, set);
1168 #if DECCHECK
1169 decCheckInexact(res, set);
1170 #endif
1171 return res;
1172 } /* decNumberFMA */
1174 /* ------------------------------------------------------------------ */
1175 /* decNumberInvert -- invert a Number, digitwise */
1176 /* */
1177 /* This computes C = ~A */
1178 /* */
1179 /* res is C, the result. C may be A (e.g., X=~X) */
1180 /* rhs is A */
1181 /* set is the context (used for result length and error report) */
1182 /* */
1183 /* C must have space for set->digits digits. */
1184 /* */
1185 /* Logical function restrictions apply (see above); a NaN is */
1186 /* returned with Invalid_operation if a restriction is violated. */
1187 /* ------------------------------------------------------------------ */
1188 decNumber * decNumberInvert(decNumber *res, const decNumber *rhs,
1189 decContext *set) {
1190 const Unit *ua, *msua; /* -> operand and its msu */
1191 Unit *uc, *msuc; /* -> result and its msu */
1192 Int msudigs; /* digits in res msu */
1193 #if DECCHECK
1194 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1195 #endif
1197 if (rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
1198 decStatus(res, DEC_Invalid_operation, set);
1199 return res;
1201 /* operand is valid */
1202 ua=rhs->lsu; /* bottom-up */
1203 uc=res->lsu; /* .. */
1204 msua=ua+D2U(rhs->digits)-1; /* -> msu of rhs */
1205 msuc=uc+D2U(set->digits)-1; /* -> msu of result */
1206 msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */
1207 for (; uc<=msuc; ua++, uc++) { /* Unit loop */
1208 Unit a; /* extract unit */
1209 Int i, j; /* work */
1210 if (ua>msua) a=0;
1211 else a=*ua;
1212 *uc=0; /* can now write back */
1213 /* always need to examine all bits in rhs */
1214 /* This loop could be unrolled and/or use BIN2BCD tables */
1215 for (i=0; i<DECDPUN; i++) {
1216 if ((~a)&1) *uc=*uc+(Unit)powers[i]; /* effect INVERT */
1217 j=a%10;
1218 a=a/10;
1219 if (j>1) {
1220 decStatus(res, DEC_Invalid_operation, set);
1221 return res;
1223 if (uc==msuc && i==msudigs-1) break; /* just did final digit */
1224 } /* each digit */
1225 } /* each unit */
1226 /* [here uc-1 is the msu of the result] */
1227 res->digits=decGetDigits(res->lsu, uc-res->lsu);
1228 res->exponent=0; /* integer */
1229 res->bits=0; /* sign=0 */
1230 return res; /* [no status to set] */
1231 } /* decNumberInvert */
1233 /* ------------------------------------------------------------------ */
1234 /* decNumberLn -- natural logarithm */
1235 /* */
1236 /* This computes C = ln(A) */
1237 /* */
1238 /* res is C, the result. C may be A */
1239 /* rhs is A */
1240 /* set is the context; note that rounding mode has no effect */
1241 /* */
1242 /* C must have space for set->digits digits. */
1243 /* */
1244 /* Notable cases: */
1245 /* A<0 -> Invalid */
1246 /* A=0 -> -Infinity (Exact) */
1247 /* A=+Infinity -> +Infinity (Exact) */
1248 /* A=1 exactly -> 0 (Exact) */
1249 /* */
1250 /* Mathematical function restrictions apply (see above); a NaN is */
1251 /* returned with Invalid_operation if a restriction is violated. */
1252 /* */
1253 /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */
1254 /* almost always be correctly rounded, but may be up to 1 ulp in */
1255 /* error in rare cases. */
1256 /* ------------------------------------------------------------------ */
1257 /* This is a wrapper for decLnOp which can handle the slightly wider */
1258 /* (+11) range needed by Ln, Log10, etc. (which may have to be able */
1259 /* to calculate at p+e+2). */
1260 /* ------------------------------------------------------------------ */
1261 decNumber * decNumberLn(decNumber *res, const decNumber *rhs,
1262 decContext *set) {
1263 uInt status=0; /* accumulator */
1264 #if DECSUBSET
1265 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */
1266 #endif
1268 #if DECCHECK
1269 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1270 #endif
1272 /* Check restrictions; this is a math function; if not violated */
1273 /* then carry out the operation. */
1274 if (!decCheckMath(rhs, set, &status)) do { /* protect allocation */
1275 #if DECSUBSET
1276 if (!set->extended) {
1277 /* reduce operand and set lostDigits status, as needed */
1278 if (rhs->digits>set->digits) {
1279 allocrhs=decRoundOperand(rhs, set, &status);
1280 if (allocrhs==NULL) break;
1281 rhs=allocrhs;
1283 /* special check in subset for rhs=0 */
1284 if (ISZERO(rhs)) { /* +/- zeros -> error */
1285 status|=DEC_Invalid_operation;
1286 break;}
1287 } /* extended=0 */
1288 #endif
1289 decLnOp(res, rhs, set, &status);
1290 } while(0); /* end protected */
1292 #if DECSUBSET
1293 if (allocrhs !=NULL) free(allocrhs); /* drop any storage used */
1294 #endif
1295 /* apply significant status */
1296 if (status!=0) decStatus(res, status, set);
1297 #if DECCHECK
1298 decCheckInexact(res, set);
1299 #endif
1300 return res;
1301 } /* decNumberLn */
1303 /* ------------------------------------------------------------------ */
1304 /* decNumberLogB - get adjusted exponent, by 754r rules */
1305 /* */
1306 /* This computes C = adjustedexponent(A) */
1307 /* */
1308 /* res is C, the result. C may be A */
1309 /* rhs is A */
1310 /* set is the context, used only for digits and status */
1311 /* */
1312 /* C must have space for 10 digits (A might have 10**9 digits and */
1313 /* an exponent of +999999999, or one digit and an exponent of */
1314 /* -1999999999). */
1315 /* */
1316 /* This returns the adjusted exponent of A after (in theory) padding */
1317 /* with zeros on the right to set->digits digits while keeping the */
1318 /* same value. The exponent is not limited by emin/emax. */
1319 /* */
1320 /* Notable cases: */
1321 /* A<0 -> Use |A| */
1322 /* A=0 -> -Infinity (Division by zero) */
1323 /* A=Infinite -> +Infinity (Exact) */
1324 /* A=1 exactly -> 0 (Exact) */
1325 /* NaNs are propagated as usual */
1326 /* ------------------------------------------------------------------ */
1327 decNumber * decNumberLogB(decNumber *res, const decNumber *rhs,
1328 decContext *set) {
1329 uInt status=0; /* accumulator */
1331 #if DECCHECK
1332 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1333 #endif
1335 /* NaNs as usual; Infinities return +Infinity; 0->oops */
1336 if (decNumberIsNaN(rhs)) decNaNs(res, rhs, NULL, set, &status);
1337 else if (decNumberIsInfinite(rhs)) decNumberCopyAbs(res, rhs);
1338 else if (decNumberIsZero(rhs)) {
1339 decNumberZero(res); /* prepare for Infinity */
1340 res->bits=DECNEG|DECINF; /* -Infinity */
1341 status|=DEC_Division_by_zero; /* as per 754r */
1343 else { /* finite non-zero */
1344 Int ae=rhs->exponent+rhs->digits-1; /* adjusted exponent */
1345 decNumberFromInt32(res, ae); /* lay it out */
1348 if (status!=0) decStatus(res, status, set);
1349 return res;
1350 } /* decNumberLogB */
1352 /* ------------------------------------------------------------------ */
1353 /* decNumberLog10 -- logarithm in base 10 */
1354 /* */
1355 /* This computes C = log10(A) */
1356 /* */
1357 /* res is C, the result. C may be A */
1358 /* rhs is A */
1359 /* set is the context; note that rounding mode has no effect */
1360 /* */
1361 /* C must have space for set->digits digits. */
1362 /* */
1363 /* Notable cases: */
1364 /* A<0 -> Invalid */
1365 /* A=0 -> -Infinity (Exact) */
1366 /* A=+Infinity -> +Infinity (Exact) */
1367 /* A=10**n (if n is an integer) -> n (Exact) */
1368 /* */
1369 /* Mathematical function restrictions apply (see above); a NaN is */
1370 /* returned with Invalid_operation if a restriction is violated. */
1371 /* */
1372 /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */
1373 /* almost always be correctly rounded, but may be up to 1 ulp in */
1374 /* error in rare cases. */
1375 /* ------------------------------------------------------------------ */
1376 /* This calculates ln(A)/ln(10) using appropriate precision. For */
1377 /* ln(A) this is the max(p, rhs->digits + t) + 3, where p is the */
1378 /* requested digits and t is the number of digits in the exponent */
1379 /* (maximum 6). For ln(10) it is p + 3; this is often handled by the */
1380 /* fastpath in decLnOp. The final division is done to the requested */
1381 /* precision. */
1382 /* ------------------------------------------------------------------ */
1383 decNumber * decNumberLog10(decNumber *res, const decNumber *rhs,
1384 decContext *set) {
1385 uInt status=0, ignore=0; /* status accumulators */
1386 uInt needbytes; /* for space calculations */
1387 Int p; /* working precision */
1388 Int t; /* digits in exponent of A */
1390 /* buffers for a and b working decimals */
1391 /* (adjustment calculator, same size) */
1392 decNumber bufa[D2N(DECBUFFER+2)];
1393 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
1394 decNumber *a=bufa; /* temporary a */
1395 decNumber bufb[D2N(DECBUFFER+2)];
1396 decNumber *allocbufb=NULL; /* -> allocated bufb, iff allocated */
1397 decNumber *b=bufb; /* temporary b */
1398 decNumber bufw[D2N(10)]; /* working 2-10 digit number */
1399 decNumber *w=bufw; /* .. */
1400 #if DECSUBSET
1401 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */
1402 #endif
1404 decContext aset; /* working context */
1406 #if DECCHECK
1407 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1408 #endif
1410 /* Check restrictions; this is a math function; if not violated */
1411 /* then carry out the operation. */
1412 if (!decCheckMath(rhs, set, &status)) do { /* protect malloc */
1413 #if DECSUBSET
1414 if (!set->extended) {
1415 /* reduce operand and set lostDigits status, as needed */
1416 if (rhs->digits>set->digits) {
1417 allocrhs=decRoundOperand(rhs, set, &status);
1418 if (allocrhs==NULL) break;
1419 rhs=allocrhs;
1421 /* special check in subset for rhs=0 */
1422 if (ISZERO(rhs)) { /* +/- zeros -> error */
1423 status|=DEC_Invalid_operation;
1424 break;}
1425 } /* extended=0 */
1426 #endif
1428 decContextDefault(&aset, DEC_INIT_DECIMAL64); /* clean context */
1430 /* handle exact powers of 10; only check if +ve finite */
1431 if (!(rhs->bits&(DECNEG|DECSPECIAL)) && !ISZERO(rhs)) {
1432 Int residue=0; /* (no residue) */
1433 uInt copystat=0; /* clean status */
1435 /* round to a single digit... */
1436 aset.digits=1;
1437 decCopyFit(w, rhs, &aset, &residue, &copystat); /* copy & shorten */
1438 /* if exact and the digit is 1, rhs is a power of 10 */
1439 if (!(copystat&DEC_Inexact) && w->lsu[0]==1) {
1440 /* the exponent, conveniently, is the power of 10; making */
1441 /* this the result needs a little care as it might not fit, */
1442 /* so first convert it into the working number, and then move */
1443 /* to res */
1444 decNumberFromInt32(w, w->exponent);
1445 residue=0;
1446 decCopyFit(res, w, set, &residue, &status); /* copy & round */
1447 decFinish(res, set, &residue, &status); /* cleanup/set flags */
1448 break;
1449 } /* not a power of 10 */
1450 } /* not a candidate for exact */
1452 /* simplify the information-content calculation to use 'total */
1453 /* number of digits in a, including exponent' as compared to the */
1454 /* requested digits, as increasing this will only rarely cost an */
1455 /* iteration in ln(a) anyway */
1456 t=6; /* it can never be >6 */
1458 /* allocate space when needed... */
1459 p=(rhs->digits+t>set->digits?rhs->digits+t:set->digits)+3;
1460 needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1461 if (needbytes>sizeof(bufa)) { /* need malloc space */
1462 allocbufa=(decNumber *)malloc(needbytes);
1463 if (allocbufa==NULL) { /* hopeless -- abandon */
1464 status|=DEC_Insufficient_storage;
1465 break;}
1466 a=allocbufa; /* use the allocated space */
1468 aset.digits=p; /* as calculated */
1469 aset.emax=DEC_MAX_MATH; /* usual bounds */
1470 aset.emin=-DEC_MAX_MATH; /* .. */
1471 aset.clamp=0; /* and no concrete format */
1472 decLnOp(a, rhs, &aset, &status); /* a=ln(rhs) */
1474 /* skip the division if the result so far is infinite, NaN, or */
1475 /* zero, or there was an error; note NaN from sNaN needs copy */
1476 if (status&DEC_NaNs && !(status&DEC_sNaN)) break;
1477 if (a->bits&DECSPECIAL || ISZERO(a)) {
1478 decNumberCopy(res, a); /* [will fit] */
1479 break;}
1481 /* for ln(10) an extra 3 digits of precision are needed */
1482 p=set->digits+3;
1483 needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1484 if (needbytes>sizeof(bufb)) { /* need malloc space */
1485 allocbufb=(decNumber *)malloc(needbytes);
1486 if (allocbufb==NULL) { /* hopeless -- abandon */
1487 status|=DEC_Insufficient_storage;
1488 break;}
1489 b=allocbufb; /* use the allocated space */
1491 decNumberZero(w); /* set up 10... */
1492 #if DECDPUN==1
1493 w->lsu[1]=1; w->lsu[0]=0; /* .. */
1494 #else
1495 w->lsu[0]=10; /* .. */
1496 #endif
1497 w->digits=2; /* .. */
1499 aset.digits=p;
1500 decLnOp(b, w, &aset, &ignore); /* b=ln(10) */
1502 aset.digits=set->digits; /* for final divide */
1503 decDivideOp(res, a, b, &aset, DIVIDE, &status); /* into result */
1504 } while(0); /* [for break] */
1506 if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */
1507 if (allocbufb!=NULL) free(allocbufb); /* .. */
1508 #if DECSUBSET
1509 if (allocrhs !=NULL) free(allocrhs); /* .. */
1510 #endif
1511 /* apply significant status */
1512 if (status!=0) decStatus(res, status, set);
1513 #if DECCHECK
1514 decCheckInexact(res, set);
1515 #endif
1516 return res;
1517 } /* decNumberLog10 */
1519 /* ------------------------------------------------------------------ */
1520 /* decNumberMax -- compare two Numbers and return the maximum */
1521 /* */
1522 /* This computes C = A ? B, returning the maximum by 754R rules */
1523 /* */
1524 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
1525 /* lhs is A */
1526 /* rhs is B */
1527 /* set is the context */
1528 /* */
1529 /* C must have space for set->digits digits. */
1530 /* ------------------------------------------------------------------ */
1531 decNumber * decNumberMax(decNumber *res, const decNumber *lhs,
1532 const decNumber *rhs, decContext *set) {
1533 uInt status=0; /* accumulator */
1534 decCompareOp(res, lhs, rhs, set, COMPMAX, &status);
1535 if (status!=0) decStatus(res, status, set);
1536 #if DECCHECK
1537 decCheckInexact(res, set);
1538 #endif
1539 return res;
1540 } /* decNumberMax */
1542 /* ------------------------------------------------------------------ */
1543 /* decNumberMaxMag -- compare and return the maximum by magnitude */
1544 /* */
1545 /* This computes C = A ? B, returning the maximum by 754R rules */
1546 /* */
1547 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
1548 /* lhs is A */
1549 /* rhs is B */
1550 /* set is the context */
1551 /* */
1552 /* C must have space for set->digits digits. */
1553 /* ------------------------------------------------------------------ */
1554 decNumber * decNumberMaxMag(decNumber *res, const decNumber *lhs,
1555 const decNumber *rhs, decContext *set) {
1556 uInt status=0; /* accumulator */
1557 decCompareOp(res, lhs, rhs, set, COMPMAXMAG, &status);
1558 if (status!=0) decStatus(res, status, set);
1559 #if DECCHECK
1560 decCheckInexact(res, set);
1561 #endif
1562 return res;
1563 } /* decNumberMaxMag */
1565 /* ------------------------------------------------------------------ */
1566 /* decNumberMin -- compare two Numbers and return the minimum */
1567 /* */
1568 /* This computes C = A ? B, returning the minimum by 754R rules */
1569 /* */
1570 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
1571 /* lhs is A */
1572 /* rhs is B */
1573 /* set is the context */
1574 /* */
1575 /* C must have space for set->digits digits. */
1576 /* ------------------------------------------------------------------ */
1577 decNumber * decNumberMin(decNumber *res, const decNumber *lhs,
1578 const decNumber *rhs, decContext *set) {
1579 uInt status=0; /* accumulator */
1580 decCompareOp(res, lhs, rhs, set, COMPMIN, &status);
1581 if (status!=0) decStatus(res, status, set);
1582 #if DECCHECK
1583 decCheckInexact(res, set);
1584 #endif
1585 return res;
1586 } /* decNumberMin */
1588 /* ------------------------------------------------------------------ */
1589 /* decNumberMinMag -- compare and return the minimum by magnitude */
1590 /* */
1591 /* This computes C = A ? B, returning the minimum by 754R rules */
1592 /* */
1593 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
1594 /* lhs is A */
1595 /* rhs is B */
1596 /* set is the context */
1597 /* */
1598 /* C must have space for set->digits digits. */
1599 /* ------------------------------------------------------------------ */
1600 decNumber * decNumberMinMag(decNumber *res, const decNumber *lhs,
1601 const decNumber *rhs, decContext *set) {
1602 uInt status=0; /* accumulator */
1603 decCompareOp(res, lhs, rhs, set, COMPMINMAG, &status);
1604 if (status!=0) decStatus(res, status, set);
1605 #if DECCHECK
1606 decCheckInexact(res, set);
1607 #endif
1608 return res;
1609 } /* decNumberMinMag */
1611 /* ------------------------------------------------------------------ */
1612 /* decNumberMinus -- prefix minus operator */
1613 /* */
1614 /* This computes C = 0 - A */
1615 /* */
1616 /* res is C, the result. C may be A */
1617 /* rhs is A */
1618 /* set is the context */
1619 /* */
1620 /* See also decNumberCopyNegate for a quiet bitwise version of this. */
1621 /* C must have space for set->digits digits. */
1622 /* ------------------------------------------------------------------ */
1623 /* Simply use AddOp for the subtract, which will do the necessary. */
1624 /* ------------------------------------------------------------------ */
1625 decNumber * decNumberMinus(decNumber *res, const decNumber *rhs,
1626 decContext *set) {
1627 decNumber dzero;
1628 uInt status=0; /* accumulator */
1630 #if DECCHECK
1631 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1632 #endif
1634 decNumberZero(&dzero); /* make 0 */
1635 dzero.exponent=rhs->exponent; /* [no coefficient expansion] */
1636 decAddOp(res, &dzero, rhs, set, DECNEG, &status);
1637 if (status!=0) decStatus(res, status, set);
1638 #if DECCHECK
1639 decCheckInexact(res, set);
1640 #endif
1641 return res;
1642 } /* decNumberMinus */
1644 /* ------------------------------------------------------------------ */
1645 /* decNumberNextMinus -- next towards -Infinity */
1646 /* */
1647 /* This computes C = A - infinitesimal, rounded towards -Infinity */
1648 /* */
1649 /* res is C, the result. C may be A */
1650 /* rhs is A */
1651 /* set is the context */
1652 /* */
1653 /* This is a generalization of 754r NextDown. */
1654 /* ------------------------------------------------------------------ */
1655 decNumber * decNumberNextMinus(decNumber *res, const decNumber *rhs,
1656 decContext *set) {
1657 decNumber dtiny; /* constant */
1658 decContext workset=*set; /* work */
1659 uInt status=0; /* accumulator */
1660 #if DECCHECK
1661 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1662 #endif
1664 /* +Infinity is the special case */
1665 if ((rhs->bits&(DECINF|DECNEG))==DECINF) {
1666 decSetMaxValue(res, set); /* is +ve */
1667 /* there is no status to set */
1668 return res;
1670 decNumberZero(&dtiny); /* start with 0 */
1671 dtiny.lsu[0]=1; /* make number that is .. */
1672 dtiny.exponent=DEC_MIN_EMIN-1; /* .. smaller than tiniest */
1673 workset.round=DEC_ROUND_FLOOR;
1674 decAddOp(res, rhs, &dtiny, &workset, DECNEG, &status);
1675 status&=DEC_Invalid_operation|DEC_sNaN; /* only sNaN Invalid please */
1676 if (status!=0) decStatus(res, status, set);
1677 return res;
1678 } /* decNumberNextMinus */
1680 /* ------------------------------------------------------------------ */
1681 /* decNumberNextPlus -- next towards +Infinity */
1682 /* */
1683 /* This computes C = A + infinitesimal, rounded towards +Infinity */
1684 /* */
1685 /* res is C, the result. C may be A */
1686 /* rhs is A */
1687 /* set is the context */
1688 /* */
1689 /* This is a generalization of 754r NextUp. */
1690 /* ------------------------------------------------------------------ */
1691 decNumber * decNumberNextPlus(decNumber *res, const decNumber *rhs,
1692 decContext *set) {
1693 decNumber dtiny; /* constant */
1694 decContext workset=*set; /* work */
1695 uInt status=0; /* accumulator */
1696 #if DECCHECK
1697 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1698 #endif
1700 /* -Infinity is the special case */
1701 if ((rhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1702 decSetMaxValue(res, set);
1703 res->bits=DECNEG; /* negative */
1704 /* there is no status to set */
1705 return res;
1707 decNumberZero(&dtiny); /* start with 0 */
1708 dtiny.lsu[0]=1; /* make number that is .. */
1709 dtiny.exponent=DEC_MIN_EMIN-1; /* .. smaller than tiniest */
1710 workset.round=DEC_ROUND_CEILING;
1711 decAddOp(res, rhs, &dtiny, &workset, 0, &status);
1712 status&=DEC_Invalid_operation|DEC_sNaN; /* only sNaN Invalid please */
1713 if (status!=0) decStatus(res, status, set);
1714 return res;
1715 } /* decNumberNextPlus */
1717 /* ------------------------------------------------------------------ */
1718 /* decNumberNextToward -- next towards rhs */
1719 /* */
1720 /* This computes C = A +/- infinitesimal, rounded towards */
1721 /* +/-Infinity in the direction of B, as per 754r nextafter rules */
1722 /* */
1723 /* res is C, the result. C may be A or B. */
1724 /* lhs is A */
1725 /* rhs is B */
1726 /* set is the context */
1727 /* */
1728 /* This is a generalization of 754r NextAfter. */
1729 /* ------------------------------------------------------------------ */
1730 decNumber * decNumberNextToward(decNumber *res, const decNumber *lhs,
1731 const decNumber *rhs, decContext *set) {
1732 decNumber dtiny; /* constant */
1733 decContext workset=*set; /* work */
1734 Int result; /* .. */
1735 uInt status=0; /* accumulator */
1736 #if DECCHECK
1737 if (decCheckOperands(res, lhs, rhs, set)) return res;
1738 #endif
1740 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) {
1741 decNaNs(res, lhs, rhs, set, &status);
1743 else { /* Is numeric, so no chance of sNaN Invalid, etc. */
1744 result=decCompare(lhs, rhs, 0); /* sign matters */
1745 if (result==BADINT) status|=DEC_Insufficient_storage; /* rare */
1746 else { /* valid compare */
1747 if (result==0) decNumberCopySign(res, lhs, rhs); /* easy */
1748 else { /* differ: need NextPlus or NextMinus */
1749 uByte sub; /* add or subtract */
1750 if (result<0) { /* lhs<rhs, do nextplus */
1751 /* -Infinity is the special case */
1752 if ((lhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1753 decSetMaxValue(res, set);
1754 res->bits=DECNEG; /* negative */
1755 return res; /* there is no status to set */
1757 workset.round=DEC_ROUND_CEILING;
1758 sub=0; /* add, please */
1759 } /* plus */
1760 else { /* lhs>rhs, do nextminus */
1761 /* +Infinity is the special case */
1762 if ((lhs->bits&(DECINF|DECNEG))==DECINF) {
1763 decSetMaxValue(res, set);
1764 return res; /* there is no status to set */
1766 workset.round=DEC_ROUND_FLOOR;
1767 sub=DECNEG; /* subtract, please */
1768 } /* minus */
1769 decNumberZero(&dtiny); /* start with 0 */
1770 dtiny.lsu[0]=1; /* make number that is .. */
1771 dtiny.exponent=DEC_MIN_EMIN-1; /* .. smaller than tiniest */
1772 decAddOp(res, lhs, &dtiny, &workset, sub, &status); /* + or - */
1773 /* turn off exceptions if the result is a normal number */
1774 /* (including Nmin), otherwise let all status through */
1775 if (decNumberIsNormal(res, set)) status=0;
1776 } /* unequal */
1777 } /* compare OK */
1778 } /* numeric */
1779 if (status!=0) decStatus(res, status, set);
1780 return res;
1781 } /* decNumberNextToward */
1783 /* ------------------------------------------------------------------ */
1784 /* decNumberOr -- OR two Numbers, digitwise */
1785 /* */
1786 /* This computes C = A | B */
1787 /* */
1788 /* res is C, the result. C may be A and/or B (e.g., X=X|X) */
1789 /* lhs is A */
1790 /* rhs is B */
1791 /* set is the context (used for result length and error report) */
1792 /* */
1793 /* C must have space for set->digits digits. */
1794 /* */
1795 /* Logical function restrictions apply (see above); a NaN is */
1796 /* returned with Invalid_operation if a restriction is violated. */
1797 /* ------------------------------------------------------------------ */
1798 decNumber * decNumberOr(decNumber *res, const decNumber *lhs,
1799 const decNumber *rhs, decContext *set) {
1800 const Unit *ua, *ub; /* -> operands */
1801 const Unit *msua, *msub; /* -> operand msus */
1802 Unit *uc, *msuc; /* -> result and its msu */
1803 Int msudigs; /* digits in res msu */
1804 #if DECCHECK
1805 if (decCheckOperands(res, lhs, rhs, set)) return res;
1806 #endif
1808 if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
1809 || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
1810 decStatus(res, DEC_Invalid_operation, set);
1811 return res;
1813 /* operands are valid */
1814 ua=lhs->lsu; /* bottom-up */
1815 ub=rhs->lsu; /* .. */
1816 uc=res->lsu; /* .. */
1817 msua=ua+D2U(lhs->digits)-1; /* -> msu of lhs */
1818 msub=ub+D2U(rhs->digits)-1; /* -> msu of rhs */
1819 msuc=uc+D2U(set->digits)-1; /* -> msu of result */
1820 msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */
1821 for (; uc<=msuc; ua++, ub++, uc++) { /* Unit loop */
1822 Unit a, b; /* extract units */
1823 if (ua>msua) a=0;
1824 else a=*ua;
1825 if (ub>msub) b=0;
1826 else b=*ub;
1827 *uc=0; /* can now write back */
1828 if (a|b) { /* maybe 1 bits to examine */
1829 Int i, j;
1830 /* This loop could be unrolled and/or use BIN2BCD tables */
1831 for (i=0; i<DECDPUN; i++) {
1832 if ((a|b)&1) *uc=*uc+(Unit)powers[i]; /* effect OR */
1833 j=a%10;
1834 a=a/10;
1835 j|=b%10;
1836 b=b/10;
1837 if (j>1) {
1838 decStatus(res, DEC_Invalid_operation, set);
1839 return res;
1841 if (uc==msuc && i==msudigs-1) break; /* just did final digit */
1842 } /* each digit */
1843 } /* non-zero */
1844 } /* each unit */
1845 /* [here uc-1 is the msu of the result] */
1846 res->digits=decGetDigits(res->lsu, uc-res->lsu);
1847 res->exponent=0; /* integer */
1848 res->bits=0; /* sign=0 */
1849 return res; /* [no status to set] */
1850 } /* decNumberOr */
1852 /* ------------------------------------------------------------------ */
1853 /* decNumberPlus -- prefix plus operator */
1854 /* */
1855 /* This computes C = 0 + A */
1856 /* */
1857 /* res is C, the result. C may be A */
1858 /* rhs is A */
1859 /* set is the context */
1860 /* */
1861 /* See also decNumberCopy for a quiet bitwise version of this. */
1862 /* C must have space for set->digits digits. */
1863 /* ------------------------------------------------------------------ */
1864 /* This simply uses AddOp; Add will take fast path after preparing A. */
1865 /* Performance is a concern here, as this routine is often used to */
1866 /* check operands and apply rounding and overflow/underflow testing. */
1867 /* ------------------------------------------------------------------ */
1868 decNumber * decNumberPlus(decNumber *res, const decNumber *rhs,
1869 decContext *set) {
1870 decNumber dzero;
1871 uInt status=0; /* accumulator */
1872 #if DECCHECK
1873 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1874 #endif
1876 decNumberZero(&dzero); /* make 0 */
1877 dzero.exponent=rhs->exponent; /* [no coefficient expansion] */
1878 decAddOp(res, &dzero, rhs, set, 0, &status);
1879 if (status!=0) decStatus(res, status, set);
1880 #if DECCHECK
1881 decCheckInexact(res, set);
1882 #endif
1883 return res;
1884 } /* decNumberPlus */
1886 /* ------------------------------------------------------------------ */
1887 /* decNumberMultiply -- multiply two Numbers */
1888 /* */
1889 /* This computes C = A x B */
1890 /* */
1891 /* res is C, the result. C may be A and/or B (e.g., X=X+X) */
1892 /* lhs is A */
1893 /* rhs is B */
1894 /* set is the context */
1895 /* */
1896 /* C must have space for set->digits digits. */
1897 /* ------------------------------------------------------------------ */
1898 decNumber * decNumberMultiply(decNumber *res, const decNumber *lhs,
1899 const decNumber *rhs, decContext *set) {
1900 uInt status=0; /* accumulator */
1901 decMultiplyOp(res, lhs, rhs, set, &status);
1902 if (status!=0) decStatus(res, status, set);
1903 #if DECCHECK
1904 decCheckInexact(res, set);
1905 #endif
1906 return res;
1907 } /* decNumberMultiply */
1909 /* ------------------------------------------------------------------ */
1910 /* decNumberPower -- raise a number to a power */
1911 /* */
1912 /* This computes C = A ** B */
1913 /* */
1914 /* res is C, the result. C may be A and/or B (e.g., X=X**X) */
1915 /* lhs is A */
1916 /* rhs is B */
1917 /* set is the context */
1918 /* */
1919 /* C must have space for set->digits digits. */
1920 /* */
1921 /* Mathematical function restrictions apply (see above); a NaN is */
1922 /* returned with Invalid_operation if a restriction is violated. */
1923 /* */
1924 /* However, if 1999999997<=B<=999999999 and B is an integer then the */
1925 /* restrictions on A and the context are relaxed to the usual bounds, */
1926 /* for compatibility with the earlier (integer power only) version */
1927 /* of this function. */
1928 /* */
1929 /* When B is an integer, the result may be exact, even if rounded. */
1930 /* */
1931 /* The final result is rounded according to the context; it will */
1932 /* almost always be correctly rounded, but may be up to 1 ulp in */
1933 /* error in rare cases. */
1934 /* ------------------------------------------------------------------ */
1935 decNumber * decNumberPower(decNumber *res, const decNumber *lhs,
1936 const decNumber *rhs, decContext *set) {
1937 #if DECSUBSET
1938 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */
1939 decNumber *allocrhs=NULL; /* .., rhs */
1940 #endif
1941 decNumber *allocdac=NULL; /* -> allocated acc buffer, iff used */
1942 decNumber *allocinv=NULL; /* -> allocated 1/x buffer, iff used */
1943 Int reqdigits=set->digits; /* requested DIGITS */
1944 Int n; /* rhs in binary */
1945 Flag rhsint=0; /* 1 if rhs is an integer */
1946 Flag useint=0; /* 1 if can use integer calculation */
1947 Flag isoddint=0; /* 1 if rhs is an integer and odd */
1948 Int i; /* work */
1949 #if DECSUBSET
1950 Int dropped; /* .. */
1951 #endif
1952 uInt needbytes; /* buffer size needed */
1953 Flag seenbit; /* seen a bit while powering */
1954 Int residue=0; /* rounding residue */
1955 uInt status=0; /* accumulators */
1956 uByte bits=0; /* result sign if errors */
1957 decContext aset; /* working context */
1958 decNumber dnOne; /* work value 1... */
1959 /* local accumulator buffer [a decNumber, with digits+elength+1 digits] */
1960 decNumber dacbuff[D2N(DECBUFFER+9)];
1961 decNumber *dac=dacbuff; /* -> result accumulator */
1962 /* same again for possible 1/lhs calculation */
1963 decNumber invbuff[D2N(DECBUFFER+9)];
1965 #if DECCHECK
1966 if (decCheckOperands(res, lhs, rhs, set)) return res;
1967 #endif
1969 do { /* protect allocated storage */
1970 #if DECSUBSET
1971 if (!set->extended) { /* reduce operands and set status, as needed */
1972 if (lhs->digits>reqdigits) {
1973 alloclhs=decRoundOperand(lhs, set, &status);
1974 if (alloclhs==NULL) break;
1975 lhs=alloclhs;
1977 if (rhs->digits>reqdigits) {
1978 allocrhs=decRoundOperand(rhs, set, &status);
1979 if (allocrhs==NULL) break;
1980 rhs=allocrhs;
1983 #endif
1984 /* [following code does not require input rounding] */
1986 /* handle NaNs and rhs Infinity (lhs infinity is harder) */
1987 if (SPECIALARGS) {
1988 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) { /* NaNs */
1989 decNaNs(res, lhs, rhs, set, &status);
1990 break;}
1991 if (decNumberIsInfinite(rhs)) { /* rhs Infinity */
1992 Flag rhsneg=rhs->bits&DECNEG; /* save rhs sign */
1993 if (decNumberIsNegative(lhs) /* lhs<0 */
1994 && !decNumberIsZero(lhs)) /* .. */
1995 status|=DEC_Invalid_operation;
1996 else { /* lhs >=0 */
1997 decNumberZero(&dnOne); /* set up 1 */
1998 dnOne.lsu[0]=1;
1999 decNumberCompare(dac, lhs, &dnOne, set); /* lhs ? 1 */
2000 decNumberZero(res); /* prepare for 0/1/Infinity */
2001 if (decNumberIsNegative(dac)) { /* lhs<1 */
2002 if (rhsneg) res->bits|=DECINF; /* +Infinity [else is +0] */
2004 else if (dac->lsu[0]==0) { /* lhs=1 */
2005 /* 1**Infinity is inexact, so return fully-padded 1.0000 */
2006 Int shift=set->digits-1;
2007 *res->lsu=1; /* was 0, make int 1 */
2008 res->digits=decShiftToMost(res->lsu, 1, shift);
2009 res->exponent=-shift; /* make 1.0000... */
2010 status|=DEC_Inexact|DEC_Rounded; /* deemed inexact */
2012 else { /* lhs>1 */
2013 if (!rhsneg) res->bits|=DECINF; /* +Infinity [else is +0] */
2015 } /* lhs>=0 */
2016 break;}
2017 /* [lhs infinity drops through] */
2018 } /* specials */
2020 /* Original rhs may be an integer that fits and is in range */
2021 n=decGetInt(rhs);
2022 if (n!=BADINT) { /* it is an integer */
2023 rhsint=1; /* record the fact for 1**n */
2024 isoddint=(Flag)n&1; /* [works even if big] */
2025 if (n!=BIGEVEN && n!=BIGODD) /* can use integer path? */
2026 useint=1; /* looks good */
2029 if (decNumberIsNegative(lhs) /* -x .. */
2030 && isoddint) bits=DECNEG; /* .. to an odd power */
2032 /* handle LHS infinity */
2033 if (decNumberIsInfinite(lhs)) { /* [NaNs already handled] */
2034 uByte rbits=rhs->bits; /* save */
2035 decNumberZero(res); /* prepare */
2036 if (n==0) *res->lsu=1; /* [-]Inf**0 => 1 */
2037 else {
2038 /* -Inf**nonint -> error */
2039 if (!rhsint && decNumberIsNegative(lhs)) {
2040 status|=DEC_Invalid_operation; /* -Inf**nonint is error */
2041 break;}
2042 if (!(rbits & DECNEG)) bits|=DECINF; /* was not a **-n */
2043 /* [otherwise will be 0 or -0] */
2044 res->bits=bits;
2046 break;}
2048 /* similarly handle LHS zero */
2049 if (decNumberIsZero(lhs)) {
2050 if (n==0) { /* 0**0 => Error */
2051 #if DECSUBSET
2052 if (!set->extended) { /* [unless subset] */
2053 decNumberZero(res);
2054 *res->lsu=1; /* return 1 */
2055 break;}
2056 #endif
2057 status|=DEC_Invalid_operation;
2059 else { /* 0**x */
2060 uByte rbits=rhs->bits; /* save */
2061 if (rbits & DECNEG) { /* was a 0**(-n) */
2062 #if DECSUBSET
2063 if (!set->extended) { /* [bad if subset] */
2064 status|=DEC_Invalid_operation;
2065 break;}
2066 #endif
2067 bits|=DECINF;
2069 decNumberZero(res); /* prepare */
2070 /* [otherwise will be 0 or -0] */
2071 res->bits=bits;
2073 break;}
2075 /* here both lhs and rhs are finite; rhs==0 is handled in the */
2076 /* integer path. Next handle the non-integer cases */
2077 if (!useint) { /* non-integral rhs */
2078 /* any -ve lhs is bad, as is either operand or context out of */
2079 /* bounds */
2080 if (decNumberIsNegative(lhs)) {
2081 status|=DEC_Invalid_operation;
2082 break;}
2083 if (decCheckMath(lhs, set, &status)
2084 || decCheckMath(rhs, set, &status)) break; /* variable status */
2086 decContextDefault(&aset, DEC_INIT_DECIMAL64); /* clean context */
2087 aset.emax=DEC_MAX_MATH; /* usual bounds */
2088 aset.emin=-DEC_MAX_MATH; /* .. */
2089 aset.clamp=0; /* and no concrete format */
2091 /* calculate the result using exp(ln(lhs)*rhs), which can */
2092 /* all be done into the accumulator, dac. The precision needed */
2093 /* is enough to contain the full information in the lhs (which */
2094 /* is the total digits, including exponent), or the requested */
2095 /* precision, if larger, + 4; 6 is used for the exponent */
2096 /* maximum length, and this is also used when it is shorter */
2097 /* than the requested digits as it greatly reduces the >0.5 ulp */
2098 /* cases at little cost (because Ln doubles digits each */
2099 /* iteration so a few extra digits rarely causes an extra */
2100 /* iteration) */
2101 aset.digits=MAXI(lhs->digits, set->digits)+6+4;
2102 } /* non-integer rhs */
2104 else { /* rhs is in-range integer */
2105 if (n==0) { /* x**0 = 1 */
2106 /* (0**0 was handled above) */
2107 decNumberZero(res); /* result=1 */
2108 *res->lsu=1; /* .. */
2109 break;}
2110 /* rhs is a non-zero integer */
2111 if (n<0) n=-n; /* use abs(n) */
2113 aset=*set; /* clone the context */
2114 aset.round=DEC_ROUND_HALF_EVEN; /* internally use balanced */
2115 /* calculate the working DIGITS */
2116 aset.digits=reqdigits+(rhs->digits+rhs->exponent)+2;
2117 #if DECSUBSET
2118 if (!set->extended) aset.digits--; /* use classic precision */
2119 #endif
2120 /* it's an error if this is more than can be handled */
2121 if (aset.digits>DECNUMMAXP) {status|=DEC_Invalid_operation; break;}
2122 } /* integer path */
2124 /* aset.digits is the count of digits for the accumulator needed */
2125 /* if accumulator is too long for local storage, then allocate */
2126 needbytes=sizeof(decNumber)+(D2U(aset.digits)-1)*sizeof(Unit);
2127 /* [needbytes also used below if 1/lhs needed] */
2128 if (needbytes>sizeof(dacbuff)) {
2129 allocdac=(decNumber *)malloc(needbytes);
2130 if (allocdac==NULL) { /* hopeless -- abandon */
2131 status|=DEC_Insufficient_storage;
2132 break;}
2133 dac=allocdac; /* use the allocated space */
2135 /* here, aset is set up and accumulator is ready for use */
2137 if (!useint) { /* non-integral rhs */
2138 /* x ** y; special-case x=1 here as it will otherwise always */
2139 /* reduce to integer 1; decLnOp has a fastpath which detects */
2140 /* the case of x=1 */
2141 decLnOp(dac, lhs, &aset, &status); /* dac=ln(lhs) */
2142 /* [no error possible, as lhs 0 already handled] */
2143 if (ISZERO(dac)) { /* x==1, 1.0, etc. */
2144 /* need to return fully-padded 1.0000 etc., but rhsint->1 */
2145 *dac->lsu=1; /* was 0, make int 1 */
2146 if (!rhsint) { /* add padding */
2147 Int shift=set->digits-1;
2148 dac->digits=decShiftToMost(dac->lsu, 1, shift);
2149 dac->exponent=-shift; /* make 1.0000... */
2150 status|=DEC_Inexact|DEC_Rounded; /* deemed inexact */
2153 else {
2154 decMultiplyOp(dac, dac, rhs, &aset, &status); /* dac=dac*rhs */
2155 decExpOp(dac, dac, &aset, &status); /* dac=exp(dac) */
2157 /* and drop through for final rounding */
2158 } /* non-integer rhs */
2160 else { /* carry on with integer */
2161 decNumberZero(dac); /* acc=1 */
2162 *dac->lsu=1; /* .. */
2164 /* if a negative power the constant 1 is needed, and if not subset */
2165 /* invert the lhs now rather than inverting the result later */
2166 if (decNumberIsNegative(rhs)) { /* was a **-n [hence digits>0] */
2167 decNumber *inv=invbuff; /* asssume use fixed buffer */
2168 decNumberCopy(&dnOne, dac); /* dnOne=1; [needed now or later] */
2169 #if DECSUBSET
2170 if (set->extended) { /* need to calculate 1/lhs */
2171 #endif
2172 /* divide lhs into 1, putting result in dac [dac=1/dac] */
2173 decDivideOp(dac, &dnOne, lhs, &aset, DIVIDE, &status);
2174 /* now locate or allocate space for the inverted lhs */
2175 if (needbytes>sizeof(invbuff)) {
2176 allocinv=(decNumber *)malloc(needbytes);
2177 if (allocinv==NULL) { /* hopeless -- abandon */
2178 status|=DEC_Insufficient_storage;
2179 break;}
2180 inv=allocinv; /* use the allocated space */
2182 /* [inv now points to big-enough buffer or allocated storage] */
2183 decNumberCopy(inv, dac); /* copy the 1/lhs */
2184 decNumberCopy(dac, &dnOne); /* restore acc=1 */
2185 lhs=inv; /* .. and go forward with new lhs */
2186 #if DECSUBSET
2188 #endif
2191 /* Raise-to-the-power loop... */
2192 seenbit=0; /* set once a 1-bit is encountered */
2193 for (i=1;;i++){ /* for each bit [top bit ignored] */
2194 /* abandon if had overflow or terminal underflow */
2195 if (status & (DEC_Overflow|DEC_Underflow)) { /* interesting? */
2196 if (status&DEC_Overflow || ISZERO(dac)) break;
2198 /* [the following two lines revealed an optimizer bug in a C++ */
2199 /* compiler, with symptom: 5**3 -> 25, when n=n+n was used] */
2200 n=n<<1; /* move next bit to testable position */
2201 if (n<0) { /* top bit is set */
2202 seenbit=1; /* OK, significant bit seen */
2203 decMultiplyOp(dac, dac, lhs, &aset, &status); /* dac=dac*x */
2205 if (i==31) break; /* that was the last bit */
2206 if (!seenbit) continue; /* no need to square 1 */
2207 decMultiplyOp(dac, dac, dac, &aset, &status); /* dac=dac*dac [square] */
2208 } /*i*/ /* 32 bits */
2210 /* complete internal overflow or underflow processing */
2211 if (status & (DEC_Overflow|DEC_Underflow)) {
2212 #if DECSUBSET
2213 /* If subset, and power was negative, reverse the kind of -erflow */
2214 /* [1/x not yet done] */
2215 if (!set->extended && decNumberIsNegative(rhs)) {
2216 if (status & DEC_Overflow)
2217 status^=DEC_Overflow | DEC_Underflow | DEC_Subnormal;
2218 else { /* trickier -- Underflow may or may not be set */
2219 status&=~(DEC_Underflow | DEC_Subnormal); /* [one or both] */
2220 status|=DEC_Overflow;
2223 #endif
2224 dac->bits=(dac->bits & ~DECNEG) | bits; /* force correct sign */
2225 /* round subnormals [to set.digits rather than aset.digits] */
2226 /* or set overflow result similarly as required */
2227 decFinalize(dac, set, &residue, &status);
2228 decNumberCopy(res, dac); /* copy to result (is now OK length) */
2229 break;
2232 #if DECSUBSET
2233 if (!set->extended && /* subset math */
2234 decNumberIsNegative(rhs)) { /* was a **-n [hence digits>0] */
2235 /* so divide result into 1 [dac=1/dac] */
2236 decDivideOp(dac, &dnOne, dac, &aset, DIVIDE, &status);
2238 #endif
2239 } /* rhs integer path */
2241 /* reduce result to the requested length and copy to result */
2242 decCopyFit(res, dac, set, &residue, &status);
2243 decFinish(res, set, &residue, &status); /* final cleanup */
2244 #if DECSUBSET
2245 if (!set->extended) decTrim(res, set, 0, &dropped); /* trailing zeros */
2246 #endif
2247 } while(0); /* end protected */
2249 if (allocdac!=NULL) free(allocdac); /* drop any storage used */
2250 if (allocinv!=NULL) free(allocinv); /* .. */
2251 #if DECSUBSET
2252 if (alloclhs!=NULL) free(alloclhs); /* .. */
2253 if (allocrhs!=NULL) free(allocrhs); /* .. */
2254 #endif
2255 if (status!=0) decStatus(res, status, set);
2256 #if DECCHECK
2257 decCheckInexact(res, set);
2258 #endif
2259 return res;
2260 } /* decNumberPower */
2262 /* ------------------------------------------------------------------ */
2263 /* decNumberQuantize -- force exponent to requested value */
2264 /* */
2265 /* This computes C = op(A, B), where op adjusts the coefficient */
2266 /* of C (by rounding or shifting) such that the exponent (-scale) */
2267 /* of C has exponent of B. The numerical value of C will equal A, */
2268 /* except for the effects of any rounding that occurred. */
2269 /* */
2270 /* res is C, the result. C may be A or B */
2271 /* lhs is A, the number to adjust */
2272 /* rhs is B, the number with exponent to match */
2273 /* set is the context */
2274 /* */
2275 /* C must have space for set->digits digits. */
2276 /* */
2277 /* Unless there is an error or the result is infinite, the exponent */
2278 /* after the operation is guaranteed to be equal to that of B. */
2279 /* ------------------------------------------------------------------ */
2280 decNumber * decNumberQuantize(decNumber *res, const decNumber *lhs,
2281 const decNumber *rhs, decContext *set) {
2282 uInt status=0; /* accumulator */
2283 decQuantizeOp(res, lhs, rhs, set, 1, &status);
2284 if (status!=0) decStatus(res, status, set);
2285 return res;
2286 } /* decNumberQuantize */
2288 /* ------------------------------------------------------------------ */
2289 /* decNumberReduce -- remove trailing zeros */
2290 /* */
2291 /* This computes C = 0 + A, and normalizes the result */
2292 /* */
2293 /* res is C, the result. C may be A */
2294 /* rhs is A */
2295 /* set is the context */
2296 /* */
2297 /* C must have space for set->digits digits. */
2298 /* ------------------------------------------------------------------ */
2299 /* Previously known as Normalize */
2300 decNumber * decNumberNormalize(decNumber *res, const decNumber *rhs,
2301 decContext *set) {
2302 return decNumberReduce(res, rhs, set);
2303 } /* decNumberNormalize */
2305 decNumber * decNumberReduce(decNumber *res, const decNumber *rhs,
2306 decContext *set) {
2307 #if DECSUBSET
2308 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */
2309 #endif
2310 uInt status=0; /* as usual */
2311 Int residue=0; /* as usual */
2312 Int dropped; /* work */
2314 #if DECCHECK
2315 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
2316 #endif
2318 do { /* protect allocated storage */
2319 #if DECSUBSET
2320 if (!set->extended) {
2321 /* reduce operand and set lostDigits status, as needed */
2322 if (rhs->digits>set->digits) {
2323 allocrhs=decRoundOperand(rhs, set, &status);
2324 if (allocrhs==NULL) break;
2325 rhs=allocrhs;
2328 #endif
2329 /* [following code does not require input rounding] */
2331 /* Infinities copy through; NaNs need usual treatment */
2332 if (decNumberIsNaN(rhs)) {
2333 decNaNs(res, rhs, NULL, set, &status);
2334 break;
2337 /* reduce result to the requested length and copy to result */
2338 decCopyFit(res, rhs, set, &residue, &status); /* copy & round */
2339 decFinish(res, set, &residue, &status); /* cleanup/set flags */
2340 decTrim(res, set, 1, &dropped); /* normalize in place */
2341 } while(0); /* end protected */
2343 #if DECSUBSET
2344 if (allocrhs !=NULL) free(allocrhs); /* .. */
2345 #endif
2346 if (status!=0) decStatus(res, status, set);/* then report status */
2347 return res;
2348 } /* decNumberReduce */
2350 /* ------------------------------------------------------------------ */
2351 /* decNumberRescale -- force exponent to requested value */
2352 /* */
2353 /* This computes C = op(A, B), where op adjusts the coefficient */
2354 /* of C (by rounding or shifting) such that the exponent (-scale) */
2355 /* of C has the value B. The numerical value of C will equal A, */
2356 /* except for the effects of any rounding that occurred. */
2357 /* */
2358 /* res is C, the result. C may be A or B */
2359 /* lhs is A, the number to adjust */
2360 /* rhs is B, the requested exponent */
2361 /* set is the context */
2362 /* */
2363 /* C must have space for set->digits digits. */
2364 /* */
2365 /* Unless there is an error or the result is infinite, the exponent */
2366 /* after the operation is guaranteed to be equal to B. */
2367 /* ------------------------------------------------------------------ */
2368 decNumber * decNumberRescale(decNumber *res, const decNumber *lhs,
2369 const decNumber *rhs, decContext *set) {
2370 uInt status=0; /* accumulator */
2371 decQuantizeOp(res, lhs, rhs, set, 0, &status);
2372 if (status!=0) decStatus(res, status, set);
2373 return res;
2374 } /* decNumberRescale */
2376 /* ------------------------------------------------------------------ */
2377 /* decNumberRemainder -- divide and return remainder */
2378 /* */
2379 /* This computes C = A % B */
2380 /* */
2381 /* res is C, the result. C may be A and/or B (e.g., X=X%X) */
2382 /* lhs is A */
2383 /* rhs is B */
2384 /* set is the context */
2385 /* */
2386 /* C must have space for set->digits digits. */
2387 /* ------------------------------------------------------------------ */
2388 decNumber * decNumberRemainder(decNumber *res, const decNumber *lhs,
2389 const decNumber *rhs, decContext *set) {
2390 uInt status=0; /* accumulator */
2391 decDivideOp(res, lhs, rhs, set, REMAINDER, &status);
2392 if (status!=0) decStatus(res, status, set);
2393 #if DECCHECK
2394 decCheckInexact(res, set);
2395 #endif
2396 return res;
2397 } /* decNumberRemainder */
2399 /* ------------------------------------------------------------------ */
2400 /* decNumberRemainderNear -- divide and return remainder from nearest */
2401 /* */
2402 /* This computes C = A % B, where % is the IEEE remainder operator */
2403 /* */
2404 /* res is C, the result. C may be A and/or B (e.g., X=X%X) */
2405 /* lhs is A */
2406 /* rhs is B */
2407 /* set is the context */
2408 /* */
2409 /* C must have space for set->digits digits. */
2410 /* ------------------------------------------------------------------ */
2411 decNumber * decNumberRemainderNear(decNumber *res, const decNumber *lhs,
2412 const decNumber *rhs, decContext *set) {
2413 uInt status=0; /* accumulator */
2414 decDivideOp(res, lhs, rhs, set, REMNEAR, &status);
2415 if (status!=0) decStatus(res, status, set);
2416 #if DECCHECK
2417 decCheckInexact(res, set);
2418 #endif
2419 return res;
2420 } /* decNumberRemainderNear */
2422 /* ------------------------------------------------------------------ */
2423 /* decNumberRotate -- rotate the coefficient of a Number left/right */
2424 /* */
2425 /* This computes C = A rot B (in base ten and rotating set->digits */
2426 /* digits). */
2427 /* */
2428 /* res is C, the result. C may be A and/or B (e.g., X=XrotX) */
2429 /* lhs is A */
2430 /* rhs is B, the number of digits to rotate (-ve to right) */
2431 /* set is the context */
2432 /* */
2433 /* The digits of the coefficient of A are rotated to the left (if B */
2434 /* is positive) or to the right (if B is negative) without adjusting */
2435 /* the exponent or the sign of A. If lhs->digits is less than */
2436 /* set->digits the coefficient is padded with zeros on the left */
2437 /* before the rotate. Any leading zeros in the result are removed */
2438 /* as usual. */
2439 /* */
2440 /* B must be an integer (q=0) and in the range -set->digits through */
2441 /* +set->digits. */
2442 /* C must have space for set->digits digits. */
2443 /* NaNs are propagated as usual. Infinities are unaffected (but */
2444 /* B must be valid). No status is set unless B is invalid or an */
2445 /* operand is an sNaN. */
2446 /* ------------------------------------------------------------------ */
2447 decNumber * decNumberRotate(decNumber *res, const decNumber *lhs,
2448 const decNumber *rhs, decContext *set) {
2449 uInt status=0; /* accumulator */
2450 Int rotate; /* rhs as an Int */
2452 #if DECCHECK
2453 if (decCheckOperands(res, lhs, rhs, set)) return res;
2454 #endif
2456 /* NaNs propagate as normal */
2457 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2458 decNaNs(res, lhs, rhs, set, &status);
2459 /* rhs must be an integer */
2460 else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2461 status=DEC_Invalid_operation;
2462 else { /* both numeric, rhs is an integer */
2463 rotate=decGetInt(rhs); /* [cannot fail] */
2464 if (rotate==BADINT /* something bad .. */
2465 || rotate==BIGODD || rotate==BIGEVEN /* .. very big .. */
2466 || abs(rotate)>set->digits) /* .. or out of range */
2467 status=DEC_Invalid_operation;
2468 else { /* rhs is OK */
2469 decNumberCopy(res, lhs);
2470 /* convert -ve rotate to equivalent positive rotation */
2471 if (rotate<0) rotate=set->digits+rotate;
2472 if (rotate!=0 && rotate!=set->digits /* zero or full rotation */
2473 && !decNumberIsInfinite(res)) { /* lhs was infinite */
2474 /* left-rotate to do; 0 < rotate < set->digits */
2475 uInt units, shift; /* work */
2476 uInt msudigits; /* digits in result msu */
2477 Unit *msu=res->lsu+D2U(res->digits)-1; /* current msu */
2478 Unit *msumax=res->lsu+D2U(set->digits)-1; /* rotation msu */
2479 for (msu++; msu<=msumax; msu++) *msu=0; /* ensure high units=0 */
2480 res->digits=set->digits; /* now full-length */
2481 msudigits=MSUDIGITS(res->digits); /* actual digits in msu */
2483 /* rotation here is done in-place, in three steps */
2484 /* 1. shift all to least up to one unit to unit-align final */
2485 /* lsd [any digits shifted out are rotated to the left, */
2486 /* abutted to the original msd (which may require split)] */
2487 /* */
2488 /* [if there are no whole units left to rotate, the */
2489 /* rotation is now complete] */
2490 /* */
2491 /* 2. shift to least, from below the split point only, so that */
2492 /* the final msd is in the right place in its Unit [any */
2493 /* digits shifted out will fit exactly in the current msu, */
2494 /* left aligned, no split required] */
2495 /* */
2496 /* 3. rotate all the units by reversing left part, right */
2497 /* part, and then whole */
2498 /* */
2499 /* example: rotate right 8 digits (2 units + 2), DECDPUN=3. */
2500 /* */
2501 /* start: 00a bcd efg hij klm npq */
2502 /* */
2503 /* 1a 000 0ab cde fgh|ijk lmn [pq saved] */
2504 /* 1b 00p qab cde fgh|ijk lmn */
2505 /* */
2506 /* 2a 00p qab cde fgh|00i jkl [mn saved] */
2507 /* 2b mnp qab cde fgh|00i jkl */
2508 /* */
2509 /* 3a fgh cde qab mnp|00i jkl */
2510 /* 3b fgh cde qab mnp|jkl 00i */
2511 /* 3c 00i jkl mnp qab cde fgh */
2513 /* Step 1: amount to shift is the partial right-rotate count */
2514 rotate=set->digits-rotate; /* make it right-rotate */
2515 units=rotate/DECDPUN; /* whole units to rotate */
2516 shift=rotate%DECDPUN; /* left-over digits count */
2517 if (shift>0) { /* not an exact number of units */
2518 uInt save=res->lsu[0]%powers[shift]; /* save low digit(s) */
2519 decShiftToLeast(res->lsu, D2U(res->digits), shift);
2520 if (shift>msudigits) { /* msumax-1 needs >0 digits */
2521 uInt rem=save%powers[shift-msudigits];/* split save */
2522 *msumax=(Unit)(save/powers[shift-msudigits]); /* and insert */
2523 *(msumax-1)=*(msumax-1)
2524 +(Unit)(rem*powers[DECDPUN-(shift-msudigits)]); /* .. */
2526 else { /* all fits in msumax */
2527 *msumax=*msumax+(Unit)(save*powers[msudigits-shift]); /* [maybe *1] */
2529 } /* digits shift needed */
2531 /* If whole units to rotate... */
2532 if (units>0) { /* some to do */
2533 /* Step 2: the units to touch are the whole ones in rotate, */
2534 /* if any, and the shift is DECDPUN-msudigits (which may be */
2535 /* 0, again) */
2536 shift=DECDPUN-msudigits;
2537 if (shift>0) { /* not an exact number of units */
2538 uInt save=res->lsu[0]%powers[shift]; /* save low digit(s) */
2539 decShiftToLeast(res->lsu, units, shift);
2540 *msumax=*msumax+(Unit)(save*powers[msudigits]);
2541 } /* partial shift needed */
2543 /* Step 3: rotate the units array using triple reverse */
2544 /* (reversing is easy and fast) */
2545 decReverse(res->lsu+units, msumax); /* left part */
2546 decReverse(res->lsu, res->lsu+units-1); /* right part */
2547 decReverse(res->lsu, msumax); /* whole */
2548 } /* whole units to rotate */
2549 /* the rotation may have left an undetermined number of zeros */
2550 /* on the left, so true length needs to be calculated */
2551 res->digits=decGetDigits(res->lsu, msumax-res->lsu+1);
2552 } /* rotate needed */
2553 } /* rhs OK */
2554 } /* numerics */
2555 if (status!=0) decStatus(res, status, set);
2556 return res;
2557 } /* decNumberRotate */
2559 /* ------------------------------------------------------------------ */
2560 /* decNumberSameQuantum -- test for equal exponents */
2561 /* */
2562 /* res is the result number, which will contain either 0 or 1 */
2563 /* lhs is a number to test */
2564 /* rhs is the second (usually a pattern) */
2565 /* */
2566 /* No errors are possible and no context is needed. */
2567 /* ------------------------------------------------------------------ */
2568 decNumber * decNumberSameQuantum(decNumber *res, const decNumber *lhs,
2569 const decNumber *rhs) {
2570 Unit ret=0; /* return value */
2572 #if DECCHECK
2573 if (decCheckOperands(res, lhs, rhs, DECUNCONT)) return res;
2574 #endif
2576 if (SPECIALARGS) {
2577 if (decNumberIsNaN(lhs) && decNumberIsNaN(rhs)) ret=1;
2578 else if (decNumberIsInfinite(lhs) && decNumberIsInfinite(rhs)) ret=1;
2579 /* [anything else with a special gives 0] */
2581 else if (lhs->exponent==rhs->exponent) ret=1;
2583 decNumberZero(res); /* OK to overwrite an operand now */
2584 *res->lsu=ret;
2585 return res;
2586 } /* decNumberSameQuantum */
2588 /* ------------------------------------------------------------------ */
2589 /* decNumberScaleB -- multiply by a power of 10 */
2590 /* */
2591 /* This computes C = A x 10**B where B is an integer (q=0) with */
2592 /* maximum magnitude 2*(emax+digits) */
2593 /* */
2594 /* res is C, the result. C may be A or B */
2595 /* lhs is A, the number to adjust */
2596 /* rhs is B, the requested power of ten to use */
2597 /* set is the context */
2598 /* */
2599 /* C must have space for set->digits digits. */
2600 /* */
2601 /* The result may underflow or overflow. */
2602 /* ------------------------------------------------------------------ */
2603 decNumber * decNumberScaleB(decNumber *res, const decNumber *lhs,
2604 const decNumber *rhs, decContext *set) {
2605 Int reqexp; /* requested exponent change [B] */
2606 uInt status=0; /* accumulator */
2607 Int residue; /* work */
2609 #if DECCHECK
2610 if (decCheckOperands(res, lhs, rhs, set)) return res;
2611 #endif
2613 /* Handle special values except lhs infinite */
2614 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2615 decNaNs(res, lhs, rhs, set, &status);
2616 /* rhs must be an integer */
2617 else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2618 status=DEC_Invalid_operation;
2619 else {
2620 /* lhs is a number; rhs is a finite with q==0 */
2621 reqexp=decGetInt(rhs); /* [cannot fail] */
2622 if (reqexp==BADINT /* something bad .. */
2623 || reqexp==BIGODD || reqexp==BIGEVEN /* .. very big .. */
2624 || abs(reqexp)>(2*(set->digits+set->emax))) /* .. or out of range */
2625 status=DEC_Invalid_operation;
2626 else { /* rhs is OK */
2627 decNumberCopy(res, lhs); /* all done if infinite lhs */
2628 if (!decNumberIsInfinite(res)) { /* prepare to scale */
2629 res->exponent+=reqexp; /* adjust the exponent */
2630 residue=0;
2631 decFinalize(res, set, &residue, &status); /* .. and check */
2632 } /* finite LHS */
2633 } /* rhs OK */
2634 } /* rhs finite */
2635 if (status!=0) decStatus(res, status, set);
2636 return res;
2637 } /* decNumberScaleB */
2639 /* ------------------------------------------------------------------ */
2640 /* decNumberShift -- shift the coefficient of a Number left or right */
2641 /* */
2642 /* This computes C = A << B or C = A >> -B (in base ten). */
2643 /* */
2644 /* res is C, the result. C may be A and/or B (e.g., X=X<<X) */
2645 /* lhs is A */
2646 /* rhs is B, the number of digits to shift (-ve to right) */
2647 /* set is the context */
2648 /* */
2649 /* The digits of the coefficient of A are shifted to the left (if B */
2650 /* is positive) or to the right (if B is negative) without adjusting */
2651 /* the exponent or the sign of A. */
2652 /* */
2653 /* B must be an integer (q=0) and in the range -set->digits through */
2654 /* +set->digits. */
2655 /* C must have space for set->digits digits. */
2656 /* NaNs are propagated as usual. Infinities are unaffected (but */
2657 /* B must be valid). No status is set unless B is invalid or an */
2658 /* operand is an sNaN. */
2659 /* ------------------------------------------------------------------ */
2660 decNumber * decNumberShift(decNumber *res, const decNumber *lhs,
2661 const decNumber *rhs, decContext *set) {
2662 uInt status=0; /* accumulator */
2663 Int shift; /* rhs as an Int */
2665 #if DECCHECK
2666 if (decCheckOperands(res, lhs, rhs, set)) return res;
2667 #endif
2669 /* NaNs propagate as normal */
2670 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2671 decNaNs(res, lhs, rhs, set, &status);
2672 /* rhs must be an integer */
2673 else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2674 status=DEC_Invalid_operation;
2675 else { /* both numeric, rhs is an integer */
2676 shift=decGetInt(rhs); /* [cannot fail] */
2677 if (shift==BADINT /* something bad .. */
2678 || shift==BIGODD || shift==BIGEVEN /* .. very big .. */
2679 || abs(shift)>set->digits) /* .. or out of range */
2680 status=DEC_Invalid_operation;
2681 else { /* rhs is OK */
2682 decNumberCopy(res, lhs);
2683 if (shift!=0 && !decNumberIsInfinite(res)) { /* something to do */
2684 if (shift>0) { /* to left */
2685 if (shift==set->digits) { /* removing all */
2686 *res->lsu=0; /* so place 0 */
2687 res->digits=1; /* .. */
2689 else { /* */
2690 /* first remove leading digits if necessary */
2691 if (res->digits+shift>set->digits) {
2692 decDecap(res, res->digits+shift-set->digits);
2693 /* that updated res->digits; may have gone to 1 (for a */
2694 /* single digit or for zero */
2696 if (res->digits>1 || *res->lsu) /* if non-zero.. */
2697 res->digits=decShiftToMost(res->lsu, res->digits, shift);
2698 } /* partial left */
2699 } /* left */
2700 else { /* to right */
2701 if (-shift>=res->digits) { /* discarding all */
2702 *res->lsu=0; /* so place 0 */
2703 res->digits=1; /* .. */
2705 else {
2706 decShiftToLeast(res->lsu, D2U(res->digits), -shift);
2707 res->digits-=(-shift);
2709 } /* to right */
2710 } /* non-0 non-Inf shift */
2711 } /* rhs OK */
2712 } /* numerics */
2713 if (status!=0) decStatus(res, status, set);
2714 return res;
2715 } /* decNumberShift */
2717 /* ------------------------------------------------------------------ */
2718 /* decNumberSquareRoot -- square root operator */
2719 /* */
2720 /* This computes C = squareroot(A) */
2721 /* */
2722 /* res is C, the result. C may be A */
2723 /* rhs is A */
2724 /* set is the context; note that rounding mode has no effect */
2725 /* */
2726 /* C must have space for set->digits digits. */
2727 /* ------------------------------------------------------------------ */
2728 /* This uses the following varying-precision algorithm in: */
2729 /* */
2730 /* Properly Rounded Variable Precision Square Root, T. E. Hull and */
2731 /* A. Abrham, ACM Transactions on Mathematical Software, Vol 11 #3, */
2732 /* pp229-237, ACM, September 1985. */
2733 /* */
2734 /* The square-root is calculated using Newton's method, after which */
2735 /* a check is made to ensure the result is correctly rounded. */
2736 /* */
2737 /* % [Reformatted original Numerical Turing source code follows.] */
2738 /* function sqrt(x : real) : real */
2739 /* % sqrt(x) returns the properly rounded approximation to the square */
2740 /* % root of x, in the precision of the calling environment, or it */
2741 /* % fails if x < 0. */
2742 /* % t e hull and a abrham, august, 1984 */
2743 /* if x <= 0 then */
2744 /* if x < 0 then */
2745 /* assert false */
2746 /* else */
2747 /* result 0 */
2748 /* end if */
2749 /* end if */
2750 /* var f := setexp(x, 0) % fraction part of x [0.1 <= x < 1] */
2751 /* var e := getexp(x) % exponent part of x */
2752 /* var approx : real */
2753 /* if e mod 2 = 0 then */
2754 /* approx := .259 + .819 * f % approx to root of f */
2755 /* else */
2756 /* f := f/l0 % adjustments */
2757 /* e := e + 1 % for odd */
2758 /* approx := .0819 + 2.59 * f % exponent */
2759 /* end if */
2760 /* */
2761 /* var p:= 3 */
2762 /* const maxp := currentprecision + 2 */
2763 /* loop */
2764 /* p := min(2*p - 2, maxp) % p = 4,6,10, . . . , maxp */
2765 /* precision p */
2766 /* approx := .5 * (approx + f/approx) */
2767 /* exit when p = maxp */
2768 /* end loop */
2769 /* */
2770 /* % approx is now within 1 ulp of the properly rounded square root */
2771 /* % of f; to ensure proper rounding, compare squares of (approx - */
2772 /* % l/2 ulp) and (approx + l/2 ulp) with f. */
2773 /* p := currentprecision */
2774 /* begin */
2775 /* precision p + 2 */
2776 /* const approxsubhalf := approx - setexp(.5, -p) */
2777 /* if mulru(approxsubhalf, approxsubhalf) > f then */
2778 /* approx := approx - setexp(.l, -p + 1) */
2779 /* else */
2780 /* const approxaddhalf := approx + setexp(.5, -p) */
2781 /* if mulrd(approxaddhalf, approxaddhalf) < f then */
2782 /* approx := approx + setexp(.l, -p + 1) */
2783 /* end if */
2784 /* end if */
2785 /* end */
2786 /* result setexp(approx, e div 2) % fix exponent */
2787 /* end sqrt */
2788 /* ------------------------------------------------------------------ */
2789 decNumber * decNumberSquareRoot(decNumber *res, const decNumber *rhs,
2790 decContext *set) {
2791 decContext workset, approxset; /* work contexts */
2792 decNumber dzero; /* used for constant zero */
2793 Int maxp; /* largest working precision */
2794 Int workp; /* working precision */
2795 Int residue=0; /* rounding residue */
2796 uInt status=0, ignore=0; /* status accumulators */
2797 uInt rstatus; /* .. */
2798 Int exp; /* working exponent */
2799 Int ideal; /* ideal (preferred) exponent */
2800 Int needbytes; /* work */
2801 Int dropped; /* .. */
2803 #if DECSUBSET
2804 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */
2805 #endif
2806 /* buffer for f [needs +1 in case DECBUFFER 0] */
2807 decNumber buff[D2N(DECBUFFER+1)];
2808 /* buffer for a [needs +2 to match likely maxp] */
2809 decNumber bufa[D2N(DECBUFFER+2)];
2810 /* buffer for temporary, b [must be same size as a] */
2811 decNumber bufb[D2N(DECBUFFER+2)];
2812 decNumber *allocbuff=NULL; /* -> allocated buff, iff allocated */
2813 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
2814 decNumber *allocbufb=NULL; /* -> allocated bufb, iff allocated */
2815 decNumber *f=buff; /* reduced fraction */
2816 decNumber *a=bufa; /* approximation to result */
2817 decNumber *b=bufb; /* intermediate result */
2818 /* buffer for temporary variable, up to 3 digits */
2819 decNumber buft[D2N(3)];
2820 decNumber *t=buft; /* up-to-3-digit constant or work */
2822 #if DECCHECK
2823 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
2824 #endif
2826 do { /* protect allocated storage */
2827 #if DECSUBSET
2828 if (!set->extended) {
2829 /* reduce operand and set lostDigits status, as needed */
2830 if (rhs->digits>set->digits) {
2831 allocrhs=decRoundOperand(rhs, set, &status);
2832 if (allocrhs==NULL) break;
2833 /* [Note: 'f' allocation below could reuse this buffer if */
2834 /* used, but as this is rare they are kept separate for clarity.] */
2835 rhs=allocrhs;
2838 #endif
2839 /* [following code does not require input rounding] */
2841 /* handle infinities and NaNs */
2842 if (SPECIALARG) {
2843 if (decNumberIsInfinite(rhs)) { /* an infinity */
2844 if (decNumberIsNegative(rhs)) status|=DEC_Invalid_operation;
2845 else decNumberCopy(res, rhs); /* +Infinity */
2847 else decNaNs(res, rhs, NULL, set, &status); /* a NaN */
2848 break;
2851 /* calculate the ideal (preferred) exponent [floor(exp/2)] */
2852 /* [We would like to write: ideal=rhs->exponent>>1, but this */
2853 /* generates a compiler warning. Generated code is the same.] */
2854 ideal=(rhs->exponent&~1)/2; /* target */
2856 /* handle zeros */
2857 if (ISZERO(rhs)) {
2858 decNumberCopy(res, rhs); /* could be 0 or -0 */
2859 res->exponent=ideal; /* use the ideal [safe] */
2860 /* use decFinish to clamp any out-of-range exponent, etc. */
2861 decFinish(res, set, &residue, &status);
2862 break;
2865 /* any other -x is an oops */
2866 if (decNumberIsNegative(rhs)) {
2867 status|=DEC_Invalid_operation;
2868 break;
2871 /* space is needed for three working variables */
2872 /* f -- the same precision as the RHS, reduced to 0.01->0.99... */
2873 /* a -- Hull's approximation -- precision, when assigned, is */
2874 /* currentprecision+1 or the input argument precision, */
2875 /* whichever is larger (+2 for use as temporary) */
2876 /* b -- intermediate temporary result (same size as a) */
2877 /* if any is too long for local storage, then allocate */
2878 workp=MAXI(set->digits+1, rhs->digits); /* actual rounding precision */
2879 maxp=workp+2; /* largest working precision */
2881 needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
2882 if (needbytes>(Int)sizeof(buff)) {
2883 allocbuff=(decNumber *)malloc(needbytes);
2884 if (allocbuff==NULL) { /* hopeless -- abandon */
2885 status|=DEC_Insufficient_storage;
2886 break;}
2887 f=allocbuff; /* use the allocated space */
2889 /* a and b both need to be able to hold a maxp-length number */
2890 needbytes=sizeof(decNumber)+(D2U(maxp)-1)*sizeof(Unit);
2891 if (needbytes>(Int)sizeof(bufa)) { /* [same applies to b] */
2892 allocbufa=(decNumber *)malloc(needbytes);
2893 allocbufb=(decNumber *)malloc(needbytes);
2894 if (allocbufa==NULL || allocbufb==NULL) { /* hopeless */
2895 status|=DEC_Insufficient_storage;
2896 break;}
2897 a=allocbufa; /* use the allocated spaces */
2898 b=allocbufb; /* .. */
2901 /* copy rhs -> f, save exponent, and reduce so 0.1 <= f < 1 */
2902 decNumberCopy(f, rhs);
2903 exp=f->exponent+f->digits; /* adjusted to Hull rules */
2904 f->exponent=-(f->digits); /* to range */
2906 /* set up working context */
2907 decContextDefault(&workset, DEC_INIT_DECIMAL64);
2909 /* [Until further notice, no error is possible and status bits */
2910 /* (Rounded, etc.) should be ignored, not accumulated.] */
2912 /* Calculate initial approximation, and allow for odd exponent */
2913 workset.digits=workp; /* p for initial calculation */
2914 t->bits=0; t->digits=3;
2915 a->bits=0; a->digits=3;
2916 if ((exp & 1)==0) { /* even exponent */
2917 /* Set t=0.259, a=0.819 */
2918 t->exponent=-3;
2919 a->exponent=-3;
2920 #if DECDPUN>=3
2921 t->lsu[0]=259;
2922 a->lsu[0]=819;
2923 #elif DECDPUN==2
2924 t->lsu[0]=59; t->lsu[1]=2;
2925 a->lsu[0]=19; a->lsu[1]=8;
2926 #else
2927 t->lsu[0]=9; t->lsu[1]=5; t->lsu[2]=2;
2928 a->lsu[0]=9; a->lsu[1]=1; a->lsu[2]=8;
2929 #endif
2931 else { /* odd exponent */
2932 /* Set t=0.0819, a=2.59 */
2933 f->exponent--; /* f=f/10 */
2934 exp++; /* e=e+1 */
2935 t->exponent=-4;
2936 a->exponent=-2;
2937 #if DECDPUN>=3
2938 t->lsu[0]=819;
2939 a->lsu[0]=259;
2940 #elif DECDPUN==2
2941 t->lsu[0]=19; t->lsu[1]=8;
2942 a->lsu[0]=59; a->lsu[1]=2;
2943 #else
2944 t->lsu[0]=9; t->lsu[1]=1; t->lsu[2]=8;
2945 a->lsu[0]=9; a->lsu[1]=5; a->lsu[2]=2;
2946 #endif
2948 decMultiplyOp(a, a, f, &workset, &ignore); /* a=a*f */
2949 decAddOp(a, a, t, &workset, 0, &ignore); /* ..+t */
2950 /* [a is now the initial approximation for sqrt(f), calculated with */
2951 /* currentprecision, which is also a's precision.] */
2953 /* the main calculation loop */
2954 decNumberZero(&dzero); /* make 0 */
2955 decNumberZero(t); /* set t = 0.5 */
2956 t->lsu[0]=5; /* .. */
2957 t->exponent=-1; /* .. */
2958 workset.digits=3; /* initial p */
2959 for (;;) {
2960 /* set p to min(2*p - 2, maxp) [hence 3; or: 4, 6, 10, ... , maxp] */
2961 workset.digits=workset.digits*2-2;
2962 if (workset.digits>maxp) workset.digits=maxp;
2963 /* a = 0.5 * (a + f/a) */
2964 /* [calculated at p then rounded to currentprecision] */
2965 decDivideOp(b, f, a, &workset, DIVIDE, &ignore); /* b=f/a */
2966 decAddOp(b, b, a, &workset, 0, &ignore); /* b=b+a */
2967 decMultiplyOp(a, b, t, &workset, &ignore); /* a=b*0.5 */
2968 if (a->digits==maxp) break; /* have required digits */
2969 } /* loop */
2971 /* Here, 0.1 <= a < 1 [Hull], and a has maxp digits */
2972 /* now reduce to length, etc.; this needs to be done with a */
2973 /* having the correct exponent so as to handle subnormals */
2974 /* correctly */
2975 approxset=*set; /* get emin, emax, etc. */
2976 approxset.round=DEC_ROUND_HALF_EVEN;
2977 a->exponent+=exp/2; /* set correct exponent */
2979 rstatus=0; /* clear status */
2980 residue=0; /* .. and accumulator */
2981 decCopyFit(a, a, &approxset, &residue, &rstatus); /* reduce (if needed) */
2982 decFinish(a, &approxset, &residue, &rstatus); /* clean and finalize */
2984 /* Overflow was possible if the input exponent was out-of-range, */
2985 /* in which case quit */
2986 if (rstatus&DEC_Overflow) {
2987 status=rstatus; /* use the status as-is */
2988 decNumberCopy(res, a); /* copy to result */
2989 break;
2992 /* Preserve status except Inexact/Rounded */
2993 status|=(rstatus & ~(DEC_Rounded|DEC_Inexact));
2995 /* Carry out the Hull correction */
2996 a->exponent-=exp/2; /* back to 0.1->1 */
2998 /* a is now at final precision and within 1 ulp of the properly */
2999 /* rounded square root of f; to ensure proper rounding, compare */
3000 /* squares of (a - l/2 ulp) and (a + l/2 ulp) with f. */
3001 /* Here workset.digits=maxp and t=0.5, and a->digits determines */
3002 /* the ulp */
3003 workset.digits--; /* maxp-1 is OK now */
3004 t->exponent=-a->digits-1; /* make 0.5 ulp */
3005 decAddOp(b, a, t, &workset, DECNEG, &ignore); /* b = a - 0.5 ulp */
3006 workset.round=DEC_ROUND_UP;
3007 decMultiplyOp(b, b, b, &workset, &ignore); /* b = mulru(b, b) */
3008 decCompareOp(b, f, b, &workset, COMPARE, &ignore); /* b ? f, reversed */
3009 if (decNumberIsNegative(b)) { /* f < b [i.e., b > f] */
3010 /* this is the more common adjustment, though both are rare */
3011 t->exponent++; /* make 1.0 ulp */
3012 t->lsu[0]=1; /* .. */
3013 decAddOp(a, a, t, &workset, DECNEG, &ignore); /* a = a - 1 ulp */
3014 /* assign to approx [round to length] */
3015 approxset.emin-=exp/2; /* adjust to match a */
3016 approxset.emax-=exp/2;
3017 decAddOp(a, &dzero, a, &approxset, 0, &ignore);
3019 else {
3020 decAddOp(b, a, t, &workset, 0, &ignore); /* b = a + 0.5 ulp */
3021 workset.round=DEC_ROUND_DOWN;
3022 decMultiplyOp(b, b, b, &workset, &ignore); /* b = mulrd(b, b) */
3023 decCompareOp(b, b, f, &workset, COMPARE, &ignore); /* b ? f */
3024 if (decNumberIsNegative(b)) { /* b < f */
3025 t->exponent++; /* make 1.0 ulp */
3026 t->lsu[0]=1; /* .. */
3027 decAddOp(a, a, t, &workset, 0, &ignore); /* a = a + 1 ulp */
3028 /* assign to approx [round to length] */
3029 approxset.emin-=exp/2; /* adjust to match a */
3030 approxset.emax-=exp/2;
3031 decAddOp(a, &dzero, a, &approxset, 0, &ignore);
3034 /* [no errors are possible in the above, and rounding/inexact during */
3035 /* estimation are irrelevant, so status was not accumulated] */
3037 /* Here, 0.1 <= a < 1 (still), so adjust back */
3038 a->exponent+=exp/2; /* set correct exponent */
3040 /* count droppable zeros [after any subnormal rounding] by */
3041 /* trimming a copy */
3042 decNumberCopy(b, a);
3043 decTrim(b, set, 1, &dropped); /* [drops trailing zeros] */
3045 /* Set Inexact and Rounded. The answer can only be exact if */
3046 /* it is short enough so that squaring it could fit in workp digits, */
3047 /* and it cannot have trailing zeros due to clamping, so these are */
3048 /* the only (relatively rare) conditions a careful check is needed */
3049 if (b->digits*2-1 > workp && !set->clamp) { /* cannot fit */
3050 status|=DEC_Inexact|DEC_Rounded;
3052 else { /* could be exact/unrounded */
3053 uInt mstatus=0; /* local status */
3054 decMultiplyOp(b, b, b, &workset, &mstatus); /* try the multiply */
3055 if (mstatus&DEC_Overflow) { /* result just won't fit */
3056 status|=DEC_Inexact|DEC_Rounded;
3058 else { /* plausible */
3059 decCompareOp(t, b, rhs, &workset, COMPARE, &mstatus); /* b ? rhs */
3060 if (!ISZERO(t)) status|=DEC_Inexact|DEC_Rounded; /* not equal */
3061 else { /* is Exact */
3062 /* here, dropped is the count of trailing zeros in 'a' */
3063 /* use closest exponent to ideal... */
3064 Int todrop=ideal-a->exponent; /* most that can be dropped */
3065 if (todrop<0) status|=DEC_Rounded; /* ideally would add 0s */
3066 else { /* unrounded */
3067 if (dropped<todrop) { /* clamp to those available */
3068 todrop=dropped;
3069 status|=DEC_Clamped;
3071 if (todrop>0) { /* have some to drop */
3072 decShiftToLeast(a->lsu, D2U(a->digits), todrop);
3073 a->exponent+=todrop; /* maintain numerical value */
3074 a->digits-=todrop; /* new length */
3081 /* double-check Underflow, as perhaps the result could not have */
3082 /* been subnormal (initial argument too big), or it is now Exact */
3083 if (status&DEC_Underflow) {
3084 Int ae=rhs->exponent+rhs->digits-1; /* adjusted exponent */
3085 /* check if truly subnormal */
3086 #if DECEXTFLAG /* DEC_Subnormal too */
3087 if (ae>=set->emin*2) status&=~(DEC_Subnormal|DEC_Underflow);
3088 #else
3089 if (ae>=set->emin*2) status&=~DEC_Underflow;
3090 #endif
3091 /* check if truly inexact */
3092 if (!(status&DEC_Inexact)) status&=~DEC_Underflow;
3095 decNumberCopy(res, a); /* a is now the result */
3096 } while(0); /* end protected */
3098 if (allocbuff!=NULL) free(allocbuff); /* drop any storage used */
3099 if (allocbufa!=NULL) free(allocbufa); /* .. */
3100 if (allocbufb!=NULL) free(allocbufb); /* .. */
3101 #if DECSUBSET
3102 if (allocrhs !=NULL) free(allocrhs); /* .. */
3103 #endif
3104 if (status!=0) decStatus(res, status, set);/* then report status */
3105 #if DECCHECK
3106 decCheckInexact(res, set);
3107 #endif
3108 return res;
3109 } /* decNumberSquareRoot */
3111 /* ------------------------------------------------------------------ */
3112 /* decNumberSubtract -- subtract two Numbers */
3113 /* */
3114 /* This computes C = A - B */
3115 /* */
3116 /* res is C, the result. C may be A and/or B (e.g., X=X-X) */
3117 /* lhs is A */
3118 /* rhs is B */
3119 /* set is the context */
3120 /* */
3121 /* C must have space for set->digits digits. */
3122 /* ------------------------------------------------------------------ */
3123 decNumber * decNumberSubtract(decNumber *res, const decNumber *lhs,
3124 const decNumber *rhs, decContext *set) {
3125 uInt status=0; /* accumulator */
3127 decAddOp(res, lhs, rhs, set, DECNEG, &status);
3128 if (status!=0) decStatus(res, status, set);
3129 #if DECCHECK
3130 decCheckInexact(res, set);
3131 #endif
3132 return res;
3133 } /* decNumberSubtract */
3135 /* ------------------------------------------------------------------ */
3136 /* decNumberToIntegralExact -- round-to-integral-value with InExact */
3137 /* decNumberToIntegralValue -- round-to-integral-value */
3138 /* */
3139 /* res is the result */
3140 /* rhs is input number */
3141 /* set is the context */
3142 /* */
3143 /* res must have space for any value of rhs. */
3144 /* */
3145 /* This implements the IEEE special operators and therefore treats */
3146 /* special values as valid. For finite numbers it returns */
3147 /* rescale(rhs, 0) if rhs->exponent is <0. */
3148 /* Otherwise the result is rhs (so no error is possible, except for */
3149 /* sNaN). */
3150 /* */
3151 /* The context is used for rounding mode and status after sNaN, but */
3152 /* the digits setting is ignored. The Exact version will signal */
3153 /* Inexact if the result differs numerically from rhs; the other */
3154 /* never signals Inexact. */
3155 /* ------------------------------------------------------------------ */
3156 decNumber * decNumberToIntegralExact(decNumber *res, const decNumber *rhs,
3157 decContext *set) {
3158 decNumber dn;
3159 decContext workset; /* working context */
3160 uInt status=0; /* accumulator */
3162 #if DECCHECK
3163 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
3164 #endif
3166 /* handle infinities and NaNs */
3167 if (SPECIALARG) {
3168 if (decNumberIsInfinite(rhs)) decNumberCopy(res, rhs); /* an Infinity */
3169 else decNaNs(res, rhs, NULL, set, &status); /* a NaN */
3171 else { /* finite */
3172 /* have a finite number; no error possible (res must be big enough) */
3173 if (rhs->exponent>=0) return decNumberCopy(res, rhs);
3174 /* that was easy, but if negative exponent there is work to do... */
3175 workset=*set; /* clone rounding, etc. */
3176 workset.digits=rhs->digits; /* no length rounding */
3177 workset.traps=0; /* no traps */
3178 decNumberZero(&dn); /* make a number with exponent 0 */
3179 decNumberQuantize(res, rhs, &dn, &workset);
3180 status|=workset.status;
3182 if (status!=0) decStatus(res, status, set);
3183 return res;
3184 } /* decNumberToIntegralExact */
3186 decNumber * decNumberToIntegralValue(decNumber *res, const decNumber *rhs,
3187 decContext *set) {
3188 decContext workset=*set; /* working context */
3189 workset.traps=0; /* no traps */
3190 decNumberToIntegralExact(res, rhs, &workset);
3191 /* this never affects set, except for sNaNs; NaN will have been set */
3192 /* or propagated already, so no need to call decStatus */
3193 set->status|=workset.status&DEC_Invalid_operation;
3194 return res;
3195 } /* decNumberToIntegralValue */
3197 /* ------------------------------------------------------------------ */
3198 /* decNumberXor -- XOR two Numbers, digitwise */
3199 /* */
3200 /* This computes C = A ^ B */
3201 /* */
3202 /* res is C, the result. C may be A and/or B (e.g., X=X^X) */
3203 /* lhs is A */
3204 /* rhs is B */
3205 /* set is the context (used for result length and error report) */
3206 /* */
3207 /* C must have space for set->digits digits. */
3208 /* */
3209 /* Logical function restrictions apply (see above); a NaN is */
3210 /* returned with Invalid_operation if a restriction is violated. */
3211 /* ------------------------------------------------------------------ */
3212 decNumber * decNumberXor(decNumber *res, const decNumber *lhs,
3213 const decNumber *rhs, decContext *set) {
3214 const Unit *ua, *ub; /* -> operands */
3215 const Unit *msua, *msub; /* -> operand msus */
3216 Unit *uc, *msuc; /* -> result and its msu */
3217 Int msudigs; /* digits in res msu */
3218 #if DECCHECK
3219 if (decCheckOperands(res, lhs, rhs, set)) return res;
3220 #endif
3222 if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
3223 || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
3224 decStatus(res, DEC_Invalid_operation, set);
3225 return res;
3227 /* operands are valid */
3228 ua=lhs->lsu; /* bottom-up */
3229 ub=rhs->lsu; /* .. */
3230 uc=res->lsu; /* .. */
3231 msua=ua+D2U(lhs->digits)-1; /* -> msu of lhs */
3232 msub=ub+D2U(rhs->digits)-1; /* -> msu of rhs */
3233 msuc=uc+D2U(set->digits)-1; /* -> msu of result */
3234 msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */
3235 for (; uc<=msuc; ua++, ub++, uc++) { /* Unit loop */
3236 Unit a, b; /* extract units */
3237 if (ua>msua) a=0;
3238 else a=*ua;
3239 if (ub>msub) b=0;
3240 else b=*ub;
3241 *uc=0; /* can now write back */
3242 if (a|b) { /* maybe 1 bits to examine */
3243 Int i, j;
3244 /* This loop could be unrolled and/or use BIN2BCD tables */
3245 for (i=0; i<DECDPUN; i++) {
3246 if ((a^b)&1) *uc=*uc+(Unit)powers[i]; /* effect XOR */
3247 j=a%10;
3248 a=a/10;
3249 j|=b%10;
3250 b=b/10;
3251 if (j>1) {
3252 decStatus(res, DEC_Invalid_operation, set);
3253 return res;
3255 if (uc==msuc && i==msudigs-1) break; /* just did final digit */
3256 } /* each digit */
3257 } /* non-zero */
3258 } /* each unit */
3259 /* [here uc-1 is the msu of the result] */
3260 res->digits=decGetDigits(res->lsu, uc-res->lsu);
3261 res->exponent=0; /* integer */
3262 res->bits=0; /* sign=0 */
3263 return res; /* [no status to set] */
3264 } /* decNumberXor */
3267 /* ================================================================== */
3268 /* Utility routines */
3269 /* ================================================================== */
3271 /* ------------------------------------------------------------------ */
3272 /* decNumberClass -- return the decClass of a decNumber */
3273 /* dn -- the decNumber to test */
3274 /* set -- the context to use for Emin */
3275 /* returns the decClass enum */
3276 /* ------------------------------------------------------------------ */
3277 enum decClass decNumberClass(const decNumber *dn, decContext *set) {
3278 if (decNumberIsSpecial(dn)) {
3279 if (decNumberIsQNaN(dn)) return DEC_CLASS_QNAN;
3280 if (decNumberIsSNaN(dn)) return DEC_CLASS_SNAN;
3281 /* must be an infinity */
3282 if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_INF;
3283 return DEC_CLASS_POS_INF;
3285 /* is finite */
3286 if (decNumberIsNormal(dn, set)) { /* most common */
3287 if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_NORMAL;
3288 return DEC_CLASS_POS_NORMAL;
3290 /* is subnormal or zero */
3291 if (decNumberIsZero(dn)) { /* most common */
3292 if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_ZERO;
3293 return DEC_CLASS_POS_ZERO;
3295 if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_SUBNORMAL;
3296 return DEC_CLASS_POS_SUBNORMAL;
3297 } /* decNumberClass */
3299 /* ------------------------------------------------------------------ */
3300 /* decNumberClassToString -- convert decClass to a string */
3301 /* */
3302 /* eclass is a valid decClass */
3303 /* returns a constant string describing the class (max 13+1 chars) */
3304 /* ------------------------------------------------------------------ */
3305 const char *decNumberClassToString(enum decClass eclass) {
3306 if (eclass==DEC_CLASS_POS_NORMAL) return DEC_ClassString_PN;
3307 if (eclass==DEC_CLASS_NEG_NORMAL) return DEC_ClassString_NN;
3308 if (eclass==DEC_CLASS_POS_ZERO) return DEC_ClassString_PZ;
3309 if (eclass==DEC_CLASS_NEG_ZERO) return DEC_ClassString_NZ;
3310 if (eclass==DEC_CLASS_POS_SUBNORMAL) return DEC_ClassString_PS;
3311 if (eclass==DEC_CLASS_NEG_SUBNORMAL) return DEC_ClassString_NS;
3312 if (eclass==DEC_CLASS_POS_INF) return DEC_ClassString_PI;
3313 if (eclass==DEC_CLASS_NEG_INF) return DEC_ClassString_NI;
3314 if (eclass==DEC_CLASS_QNAN) return DEC_ClassString_QN;
3315 if (eclass==DEC_CLASS_SNAN) return DEC_ClassString_SN;
3316 return DEC_ClassString_UN; /* Unknown */
3317 } /* decNumberClassToString */
3319 /* ------------------------------------------------------------------ */
3320 /* decNumberCopy -- copy a number */
3321 /* */
3322 /* dest is the target decNumber */
3323 /* src is the source decNumber */
3324 /* returns dest */
3325 /* */
3326 /* (dest==src is allowed and is a no-op) */
3327 /* All fields are updated as required. This is a utility operation, */
3328 /* so special values are unchanged and no error is possible. */
3329 /* ------------------------------------------------------------------ */
3330 decNumber * decNumberCopy(decNumber *dest, const decNumber *src) {
3332 #if DECCHECK
3333 if (src==NULL) return decNumberZero(dest);
3334 #endif
3336 if (dest==src) return dest; /* no copy required */
3338 /* Use explicit assignments here as structure assignment could copy */
3339 /* more than just the lsu (for small DECDPUN). This would not affect */
3340 /* the value of the results, but could disturb test harness spill */
3341 /* checking. */
3342 dest->bits=src->bits;
3343 dest->exponent=src->exponent;
3344 dest->digits=src->digits;
3345 dest->lsu[0]=src->lsu[0];
3346 if (src->digits>DECDPUN) { /* more Units to come */
3347 const Unit *smsup, *s; /* work */
3348 Unit *d; /* .. */
3349 /* memcpy for the remaining Units would be safe as they cannot */
3350 /* overlap. However, this explicit loop is faster in short cases. */
3351 d=dest->lsu+1; /* -> first destination */
3352 smsup=src->lsu+D2U(src->digits); /* -> source msu+1 */
3353 for (s=src->lsu+1; s<smsup; s++, d++) *d=*s;
3355 return dest;
3356 } /* decNumberCopy */
3358 /* ------------------------------------------------------------------ */
3359 /* decNumberCopyAbs -- quiet absolute value operator */
3360 /* */
3361 /* This sets C = abs(A) */
3362 /* */
3363 /* res is C, the result. C may be A */
3364 /* rhs is A */
3365 /* */
3366 /* C must have space for set->digits digits. */
3367 /* No exception or error can occur; this is a quiet bitwise operation.*/
3368 /* See also decNumberAbs for a checking version of this. */
3369 /* ------------------------------------------------------------------ */
3370 decNumber * decNumberCopyAbs(decNumber *res, const decNumber *rhs) {
3371 #if DECCHECK
3372 if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3373 #endif
3374 decNumberCopy(res, rhs);
3375 res->bits&=~DECNEG; /* turn off sign */
3376 return res;
3377 } /* decNumberCopyAbs */
3379 /* ------------------------------------------------------------------ */
3380 /* decNumberCopyNegate -- quiet negate value operator */
3381 /* */
3382 /* This sets C = negate(A) */
3383 /* */
3384 /* res is C, the result. C may be A */
3385 /* rhs is A */
3386 /* */
3387 /* C must have space for set->digits digits. */
3388 /* No exception or error can occur; this is a quiet bitwise operation.*/
3389 /* See also decNumberMinus for a checking version of this. */
3390 /* ------------------------------------------------------------------ */
3391 decNumber * decNumberCopyNegate(decNumber *res, const decNumber *rhs) {
3392 #if DECCHECK
3393 if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3394 #endif
3395 decNumberCopy(res, rhs);
3396 res->bits^=DECNEG; /* invert the sign */
3397 return res;
3398 } /* decNumberCopyNegate */
3400 /* ------------------------------------------------------------------ */
3401 /* decNumberCopySign -- quiet copy and set sign operator */
3402 /* */
3403 /* This sets C = A with the sign of B */
3404 /* */
3405 /* res is C, the result. C may be A */
3406 /* lhs is A */
3407 /* rhs is B */
3408 /* */
3409 /* C must have space for set->digits digits. */
3410 /* No exception or error can occur; this is a quiet bitwise operation.*/
3411 /* ------------------------------------------------------------------ */
3412 decNumber * decNumberCopySign(decNumber *res, const decNumber *lhs,
3413 const decNumber *rhs) {
3414 uByte sign; /* rhs sign */
3415 #if DECCHECK
3416 if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3417 #endif
3418 sign=rhs->bits & DECNEG; /* save sign bit */
3419 decNumberCopy(res, lhs);
3420 res->bits&=~DECNEG; /* clear the sign */
3421 res->bits|=sign; /* set from rhs */
3422 return res;
3423 } /* decNumberCopySign */
3425 /* ------------------------------------------------------------------ */
3426 /* decNumberGetBCD -- get the coefficient in BCD8 */
3427 /* dn is the source decNumber */
3428 /* bcd is the uInt array that will receive dn->digits BCD bytes, */
3429 /* most-significant at offset 0 */
3430 /* returns bcd */
3431 /* */
3432 /* bcd must have at least dn->digits bytes. No error is possible; if */
3433 /* dn is a NaN or Infinite, digits must be 1 and the coefficient 0. */
3434 /* ------------------------------------------------------------------ */
3435 uByte * decNumberGetBCD(const decNumber *dn, uint8_t *bcd) {
3436 uByte *ub=bcd+dn->digits-1; /* -> lsd */
3437 const Unit *up=dn->lsu; /* Unit pointer, -> lsu */
3439 #if DECDPUN==1 /* trivial simple copy */
3440 for (; ub>=bcd; ub--, up++) *ub=*up;
3441 #else /* chopping needed */
3442 uInt u=*up; /* work */
3443 uInt cut=DECDPUN; /* downcounter through unit */
3444 for (; ub>=bcd; ub--) {
3445 *ub=(uByte)(u%10); /* [*6554 trick inhibits, here] */
3446 u=u/10;
3447 cut--;
3448 if (cut>0) continue; /* more in this unit */
3449 up++;
3450 u=*up;
3451 cut=DECDPUN;
3453 #endif
3454 return bcd;
3455 } /* decNumberGetBCD */
3457 /* ------------------------------------------------------------------ */
3458 /* decNumberSetBCD -- set (replace) the coefficient from BCD8 */
3459 /* dn is the target decNumber */
3460 /* bcd is the uInt array that will source n BCD bytes, most- */
3461 /* significant at offset 0 */
3462 /* n is the number of digits in the source BCD array (bcd) */
3463 /* returns dn */
3464 /* */
3465 /* dn must have space for at least n digits. No error is possible; */
3466 /* if dn is a NaN, or Infinite, or is to become a zero, n must be 1 */
3467 /* and bcd[0] zero. */
3468 /* ------------------------------------------------------------------ */
3469 decNumber * decNumberSetBCD(decNumber *dn, const uByte *bcd, uInt n) {
3470 Unit *up=dn->lsu+D2U(dn->digits)-1; /* -> msu [target pointer] */
3471 const uByte *ub=bcd; /* -> source msd */
3473 #if DECDPUN==1 /* trivial simple copy */
3474 for (; ub<bcd+n; ub++, up--) *up=*ub;
3475 #else /* some assembly needed */
3476 /* calculate how many digits in msu, and hence first cut */
3477 Int cut=MSUDIGITS(n); /* [faster than remainder] */
3478 for (;up>=dn->lsu; up--) { /* each Unit from msu */
3479 *up=0; /* will take <=DECDPUN digits */
3480 for (; cut>0; ub++, cut--) *up=X10(*up)+*ub;
3481 cut=DECDPUN; /* next Unit has all digits */
3483 #endif
3484 dn->digits=n; /* set digit count */
3485 return dn;
3486 } /* decNumberSetBCD */
3488 /* ------------------------------------------------------------------ */
3489 /* decNumberIsNormal -- test normality of a decNumber */
3490 /* dn is the decNumber to test */
3491 /* set is the context to use for Emin */
3492 /* returns 1 if |dn| is finite and >=Nmin, 0 otherwise */
3493 /* ------------------------------------------------------------------ */
3494 Int decNumberIsNormal(const decNumber *dn, decContext *set) {
3495 Int ae; /* adjusted exponent */
3496 #if DECCHECK
3497 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
3498 #endif
3500 if (decNumberIsSpecial(dn)) return 0; /* not finite */
3501 if (decNumberIsZero(dn)) return 0; /* not non-zero */
3503 ae=dn->exponent+dn->digits-1; /* adjusted exponent */
3504 if (ae<set->emin) return 0; /* is subnormal */
3505 return 1;
3506 } /* decNumberIsNormal */
3508 /* ------------------------------------------------------------------ */
3509 /* decNumberIsSubnormal -- test subnormality of a decNumber */
3510 /* dn is the decNumber to test */
3511 /* set is the context to use for Emin */
3512 /* returns 1 if |dn| is finite, non-zero, and <Nmin, 0 otherwise */
3513 /* ------------------------------------------------------------------ */
3514 Int decNumberIsSubnormal(const decNumber *dn, decContext *set) {
3515 Int ae; /* adjusted exponent */
3516 #if DECCHECK
3517 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
3518 #endif
3520 if (decNumberIsSpecial(dn)) return 0; /* not finite */
3521 if (decNumberIsZero(dn)) return 0; /* not non-zero */
3523 ae=dn->exponent+dn->digits-1; /* adjusted exponent */
3524 if (ae<set->emin) return 1; /* is subnormal */
3525 return 0;
3526 } /* decNumberIsSubnormal */
3528 /* ------------------------------------------------------------------ */
3529 /* decNumberTrim -- remove insignificant zeros */
3530 /* */
3531 /* dn is the number to trim */
3532 /* returns dn */
3533 /* */
3534 /* All fields are updated as required. This is a utility operation, */
3535 /* so special values are unchanged and no error is possible. */
3536 /* ------------------------------------------------------------------ */
3537 decNumber * decNumberTrim(decNumber *dn) {
3538 Int dropped; /* work */
3539 decContext set; /* .. */
3540 #if DECCHECK
3541 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, DECUNCONT)) return dn;
3542 #endif
3543 decContextDefault(&set, DEC_INIT_BASE); /* clamp=0 */
3544 return decTrim(dn, &set, 0, &dropped);
3545 } /* decNumberTrim */
3547 /* ------------------------------------------------------------------ */
3548 /* decNumberVersion -- return the name and version of this module */
3549 /* */
3550 /* No error is possible. */
3551 /* ------------------------------------------------------------------ */
3552 const char * decNumberVersion(void) {
3553 return DECVERSION;
3554 } /* decNumberVersion */
3556 /* ------------------------------------------------------------------ */
3557 /* decNumberZero -- set a number to 0 */
3558 /* */
3559 /* dn is the number to set, with space for one digit */
3560 /* returns dn */
3561 /* */
3562 /* No error is possible. */
3563 /* ------------------------------------------------------------------ */
3564 /* Memset is not used as it is much slower in some environments. */
3565 decNumber * decNumberZero(decNumber *dn) {
3567 #if DECCHECK
3568 if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
3569 #endif
3571 dn->bits=0;
3572 dn->exponent=0;
3573 dn->digits=1;
3574 dn->lsu[0]=0;
3575 return dn;
3576 } /* decNumberZero */
3578 /* ================================================================== */
3579 /* Local routines */
3580 /* ================================================================== */
3582 /* ------------------------------------------------------------------ */
3583 /* decToString -- lay out a number into a string */
3584 /* */
3585 /* dn is the number to lay out */
3586 /* string is where to lay out the number */
3587 /* eng is 1 if Engineering, 0 if Scientific */
3588 /* */
3589 /* string must be at least dn->digits+14 characters long */
3590 /* No error is possible. */
3591 /* */
3592 /* Note that this routine can generate a -0 or 0.000. These are */
3593 /* never generated in subset to-number or arithmetic, but can occur */
3594 /* in non-subset arithmetic (e.g., -1*0 or 1.234-1.234). */
3595 /* ------------------------------------------------------------------ */
3596 /* If DECCHECK is enabled the string "?" is returned if a number is */
3597 /* invalid. */
3598 static void decToString(const decNumber *dn, char *string, Flag eng) {
3599 Int exp=dn->exponent; /* local copy */
3600 Int e; /* E-part value */
3601 Int pre; /* digits before the '.' */
3602 Int cut; /* for counting digits in a Unit */
3603 char *c=string; /* work [output pointer] */
3604 const Unit *up=dn->lsu+D2U(dn->digits)-1; /* -> msu [input pointer] */
3605 uInt u, pow; /* work */
3607 #if DECCHECK
3608 if (decCheckOperands(DECUNRESU, dn, DECUNUSED, DECUNCONT)) {
3609 strcpy(string, "?");
3610 return;}
3611 #endif
3613 if (decNumberIsNegative(dn)) { /* Negatives get a minus */
3614 *c='-';
3615 c++;
3617 if (dn->bits&DECSPECIAL) { /* Is a special value */
3618 if (decNumberIsInfinite(dn)) {
3619 strcpy(c, "Inf");
3620 strcpy(c+3, "inity");
3621 return;}
3622 /* a NaN */
3623 if (dn->bits&DECSNAN) { /* signalling NaN */
3624 *c='s';
3625 c++;
3627 strcpy(c, "NaN");
3628 c+=3; /* step past */
3629 /* if not a clean non-zero coefficient, that's all there is in a */
3630 /* NaN string */
3631 if (exp!=0 || (*dn->lsu==0 && dn->digits==1)) return;
3632 /* [drop through to add integer] */
3635 /* calculate how many digits in msu, and hence first cut */
3636 cut=MSUDIGITS(dn->digits); /* [faster than remainder] */
3637 cut--; /* power of ten for digit */
3639 if (exp==0) { /* simple integer [common fastpath] */
3640 for (;up>=dn->lsu; up--) { /* each Unit from msu */
3641 u=*up; /* contains DECDPUN digits to lay out */
3642 for (; cut>=0; c++, cut--) TODIGIT(u, cut, c, pow);
3643 cut=DECDPUN-1; /* next Unit has all digits */
3645 *c='\0'; /* terminate the string */
3646 return;}
3648 /* non-0 exponent -- assume plain form */
3649 pre=dn->digits+exp; /* digits before '.' */
3650 e=0; /* no E */
3651 if ((exp>0) || (pre<-5)) { /* need exponential form */
3652 e=exp+dn->digits-1; /* calculate E value */
3653 pre=1; /* assume one digit before '.' */
3654 if (eng && (e!=0)) { /* engineering: may need to adjust */
3655 Int adj; /* adjustment */
3656 /* The C remainder operator is undefined for negative numbers, so */
3657 /* a positive remainder calculation must be used here */
3658 if (e<0) {
3659 adj=(-e)%3;
3660 if (adj!=0) adj=3-adj;
3662 else { /* e>0 */
3663 adj=e%3;
3665 e=e-adj;
3666 /* if dealing with zero still produce an exponent which is a */
3667 /* multiple of three, as expected, but there will only be the */
3668 /* one zero before the E, still. Otherwise note the padding. */
3669 if (!ISZERO(dn)) pre+=adj;
3670 else { /* is zero */
3671 if (adj!=0) { /* 0.00Esnn needed */
3672 e=e+3;
3673 pre=-(2-adj);
3675 } /* zero */
3676 } /* eng */
3677 } /* need exponent */
3679 /* lay out the digits of the coefficient, adding 0s and . as needed */
3680 u=*up;
3681 if (pre>0) { /* xxx.xxx or xx00 (engineering) form */
3682 Int n=pre;
3683 for (; pre>0; pre--, c++, cut--) {
3684 if (cut<0) { /* need new Unit */
3685 if (up==dn->lsu) break; /* out of input digits (pre>digits) */
3686 up--;
3687 cut=DECDPUN-1;
3688 u=*up;
3690 TODIGIT(u, cut, c, pow);
3692 if (n<dn->digits) { /* more to come, after '.' */
3693 *c='.'; c++;
3694 for (;; c++, cut--) {
3695 if (cut<0) { /* need new Unit */
3696 if (up==dn->lsu) break; /* out of input digits */
3697 up--;
3698 cut=DECDPUN-1;
3699 u=*up;
3701 TODIGIT(u, cut, c, pow);
3704 else for (; pre>0; pre--, c++) *c='0'; /* 0 padding (for engineering) needed */
3706 else { /* 0.xxx or 0.000xxx form */
3707 *c='0'; c++;
3708 *c='.'; c++;
3709 for (; pre<0; pre++, c++) *c='0'; /* add any 0's after '.' */
3710 for (; ; c++, cut--) {
3711 if (cut<0) { /* need new Unit */
3712 if (up==dn->lsu) break; /* out of input digits */
3713 up--;
3714 cut=DECDPUN-1;
3715 u=*up;
3717 TODIGIT(u, cut, c, pow);
3721 /* Finally add the E-part, if needed. It will never be 0, has a
3722 base maximum and minimum of +999999999 through -999999999, but
3723 could range down to -1999999998 for anormal numbers */
3724 if (e!=0) {
3725 Flag had=0; /* 1=had non-zero */
3726 *c='E'; c++;
3727 *c='+'; c++; /* assume positive */
3728 u=e; /* .. */
3729 if (e<0) {
3730 *(c-1)='-'; /* oops, need - */
3731 u=-e; /* uInt, please */
3733 /* lay out the exponent [_itoa or equivalent is not ANSI C] */
3734 for (cut=9; cut>=0; cut--) {
3735 TODIGIT(u, cut, c, pow);
3736 if (*c=='0' && !had) continue; /* skip leading zeros */
3737 had=1; /* had non-0 */
3738 c++; /* step for next */
3739 } /* cut */
3741 *c='\0'; /* terminate the string (all paths) */
3742 return;
3743 } /* decToString */
3745 /* ------------------------------------------------------------------ */
3746 /* decAddOp -- add/subtract operation */
3747 /* */
3748 /* This computes C = A + B */
3749 /* */
3750 /* res is C, the result. C may be A and/or B (e.g., X=X+X) */
3751 /* lhs is A */
3752 /* rhs is B */
3753 /* set is the context */
3754 /* negate is DECNEG if rhs should be negated, or 0 otherwise */
3755 /* status accumulates status for the caller */
3756 /* */
3757 /* C must have space for set->digits digits. */
3758 /* Inexact in status must be 0 for correct Exact zero sign in result */
3759 /* ------------------------------------------------------------------ */
3760 /* If possible, the coefficient is calculated directly into C. */
3761 /* However, if: */
3762 /* -- a digits+1 calculation is needed because the numbers are */
3763 /* unaligned and span more than set->digits digits */
3764 /* -- a carry to digits+1 digits looks possible */
3765 /* -- C is the same as A or B, and the result would destructively */
3766 /* overlap the A or B coefficient */
3767 /* then the result must be calculated into a temporary buffer. In */
3768 /* this case a local (stack) buffer is used if possible, and only if */
3769 /* too long for that does malloc become the final resort. */
3770 /* */
3771 /* Misalignment is handled as follows: */
3772 /* Apad: (AExp>BExp) Swap operands and proceed as for BExp>AExp. */
3773 /* BPad: Apply the padding by a combination of shifting (whole */
3774 /* units) and multiplication (part units). */
3775 /* */
3776 /* Addition, especially x=x+1, is speed-critical. */
3777 /* The static buffer is larger than might be expected to allow for */
3778 /* calls from higher-level funtions (notable exp). */
3779 /* ------------------------------------------------------------------ */
3780 static decNumber * decAddOp(decNumber *res, const decNumber *lhs,
3781 const decNumber *rhs, decContext *set,
3782 uByte negate, uInt *status) {
3783 #if DECSUBSET
3784 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */
3785 decNumber *allocrhs=NULL; /* .., rhs */
3786 #endif
3787 Int rhsshift; /* working shift (in Units) */
3788 Int maxdigits; /* longest logical length */
3789 Int mult; /* multiplier */
3790 Int residue; /* rounding accumulator */
3791 uByte bits; /* result bits */
3792 Flag diffsign; /* non-0 if arguments have different sign */
3793 Unit *acc; /* accumulator for result */
3794 Unit accbuff[SD2U(DECBUFFER*2+20)]; /* local buffer [*2+20 reduces many */
3795 /* allocations when called from */
3796 /* other operations, notable exp] */
3797 Unit *allocacc=NULL; /* -> allocated acc buffer, iff allocated */
3798 Int reqdigits=set->digits; /* local copy; requested DIGITS */
3799 Int padding; /* work */
3801 #if DECCHECK
3802 if (decCheckOperands(res, lhs, rhs, set)) return res;
3803 #endif
3805 do { /* protect allocated storage */
3806 #if DECSUBSET
3807 if (!set->extended) {
3808 /* reduce operands and set lostDigits status, as needed */
3809 if (lhs->digits>reqdigits) {
3810 alloclhs=decRoundOperand(lhs, set, status);
3811 if (alloclhs==NULL) break;
3812 lhs=alloclhs;
3814 if (rhs->digits>reqdigits) {
3815 allocrhs=decRoundOperand(rhs, set, status);
3816 if (allocrhs==NULL) break;
3817 rhs=allocrhs;
3820 #endif
3821 /* [following code does not require input rounding] */
3823 /* note whether signs differ [used all paths] */
3824 diffsign=(Flag)((lhs->bits^rhs->bits^negate)&DECNEG);
3826 /* handle infinities and NaNs */
3827 if (SPECIALARGS) { /* a special bit set */
3828 if (SPECIALARGS & (DECSNAN | DECNAN)) /* a NaN */
3829 decNaNs(res, lhs, rhs, set, status);
3830 else { /* one or two infinities */
3831 if (decNumberIsInfinite(lhs)) { /* LHS is infinity */
3832 /* two infinities with different signs is invalid */
3833 if (decNumberIsInfinite(rhs) && diffsign) {
3834 *status|=DEC_Invalid_operation;
3835 break;
3837 bits=lhs->bits & DECNEG; /* get sign from LHS */
3839 else bits=(rhs->bits^negate) & DECNEG;/* RHS must be Infinity */
3840 bits|=DECINF;
3841 decNumberZero(res);
3842 res->bits=bits; /* set +/- infinity */
3843 } /* an infinity */
3844 break;
3847 /* Quick exit for add 0s; return the non-0, modified as need be */
3848 if (ISZERO(lhs)) {
3849 Int adjust; /* work */
3850 Int lexp=lhs->exponent; /* save in case LHS==RES */
3851 bits=lhs->bits; /* .. */
3852 residue=0; /* clear accumulator */
3853 decCopyFit(res, rhs, set, &residue, status); /* copy (as needed) */
3854 res->bits^=negate; /* flip if rhs was negated */
3855 #if DECSUBSET
3856 if (set->extended) { /* exponents on zeros count */
3857 #endif
3858 /* exponent will be the lower of the two */
3859 adjust=lexp-res->exponent; /* adjustment needed [if -ve] */
3860 if (ISZERO(res)) { /* both 0: special IEEE 854 rules */
3861 if (adjust<0) res->exponent=lexp; /* set exponent */
3862 /* 0-0 gives +0 unless rounding to -infinity, and -0-0 gives -0 */
3863 if (diffsign) {
3864 if (set->round!=DEC_ROUND_FLOOR) res->bits=0;
3865 else res->bits=DECNEG; /* preserve 0 sign */
3868 else { /* non-0 res */
3869 if (adjust<0) { /* 0-padding needed */
3870 if ((res->digits-adjust)>set->digits) {
3871 adjust=res->digits-set->digits; /* to fit exactly */
3872 *status|=DEC_Rounded; /* [but exact] */
3874 res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
3875 res->exponent+=adjust; /* set the exponent. */
3877 } /* non-0 res */
3878 #if DECSUBSET
3879 } /* extended */
3880 #endif
3881 decFinish(res, set, &residue, status); /* clean and finalize */
3882 break;}
3884 if (ISZERO(rhs)) { /* [lhs is non-zero] */
3885 Int adjust; /* work */
3886 Int rexp=rhs->exponent; /* save in case RHS==RES */
3887 bits=rhs->bits; /* be clean */
3888 residue=0; /* clear accumulator */
3889 decCopyFit(res, lhs, set, &residue, status); /* copy (as needed) */
3890 #if DECSUBSET
3891 if (set->extended) { /* exponents on zeros count */
3892 #endif
3893 /* exponent will be the lower of the two */
3894 /* [0-0 case handled above] */
3895 adjust=rexp-res->exponent; /* adjustment needed [if -ve] */
3896 if (adjust<0) { /* 0-padding needed */
3897 if ((res->digits-adjust)>set->digits) {
3898 adjust=res->digits-set->digits; /* to fit exactly */
3899 *status|=DEC_Rounded; /* [but exact] */
3901 res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
3902 res->exponent+=adjust; /* set the exponent. */
3904 #if DECSUBSET
3905 } /* extended */
3906 #endif
3907 decFinish(res, set, &residue, status); /* clean and finalize */
3908 break;}
3910 /* [NB: both fastpath and mainpath code below assume these cases */
3911 /* (notably 0-0) have already been handled] */
3913 /* calculate the padding needed to align the operands */
3914 padding=rhs->exponent-lhs->exponent;
3916 /* Fastpath cases where the numbers are aligned and normal, the RHS */
3917 /* is all in one unit, no operand rounding is needed, and no carry, */
3918 /* lengthening, or borrow is needed */
3919 if (padding==0
3920 && rhs->digits<=DECDPUN
3921 && rhs->exponent>=set->emin /* [some normals drop through] */
3922 && rhs->exponent<=set->emax-set->digits+1 /* [could clamp] */
3923 && rhs->digits<=reqdigits
3924 && lhs->digits<=reqdigits) {
3925 Int partial=*lhs->lsu;
3926 if (!diffsign) { /* adding */
3927 partial+=*rhs->lsu;
3928 if ((partial<=DECDPUNMAX) /* result fits in unit */
3929 && (lhs->digits>=DECDPUN || /* .. and no digits-count change */
3930 partial<(Int)powers[lhs->digits])) { /* .. */
3931 if (res!=lhs) decNumberCopy(res, lhs); /* not in place */
3932 *res->lsu=(Unit)partial; /* [copy could have overwritten RHS] */
3933 break;
3935 /* else drop out for careful add */
3937 else { /* signs differ */
3938 partial-=*rhs->lsu;
3939 if (partial>0) { /* no borrow needed, and non-0 result */
3940 if (res!=lhs) decNumberCopy(res, lhs); /* not in place */
3941 *res->lsu=(Unit)partial;
3942 /* this could have reduced digits [but result>0] */
3943 res->digits=decGetDigits(res->lsu, D2U(res->digits));
3944 break;
3946 /* else drop out for careful subtract */
3950 /* Now align (pad) the lhs or rhs so they can be added or */
3951 /* subtracted, as necessary. If one number is much larger than */
3952 /* the other (that is, if in plain form there is a least one */
3953 /* digit between the lowest digit of one and the highest of the */
3954 /* other) padding with up to DIGITS-1 trailing zeros may be */
3955 /* needed; then apply rounding (as exotic rounding modes may be */
3956 /* affected by the residue). */
3957 rhsshift=0; /* rhs shift to left (padding) in Units */
3958 bits=lhs->bits; /* assume sign is that of LHS */
3959 mult=1; /* likely multiplier */
3961 /* [if padding==0 the operands are aligned; no padding is needed] */
3962 if (padding!=0) {
3963 /* some padding needed; always pad the RHS, as any required */
3964 /* padding can then be effected by a simple combination of */
3965 /* shifts and a multiply */
3966 Flag swapped=0;
3967 if (padding<0) { /* LHS needs the padding */
3968 const decNumber *t;
3969 padding=-padding; /* will be +ve */
3970 bits=(uByte)(rhs->bits^negate); /* assumed sign is now that of RHS */
3971 t=lhs; lhs=rhs; rhs=t;
3972 swapped=1;
3975 /* If, after pad, rhs would be longer than lhs by digits+1 or */
3976 /* more then lhs cannot affect the answer, except as a residue, */
3977 /* so only need to pad up to a length of DIGITS+1. */
3978 if (rhs->digits+padding > lhs->digits+reqdigits+1) {
3979 /* The RHS is sufficient */
3980 /* for residue use the relative sign indication... */
3981 Int shift=reqdigits-rhs->digits; /* left shift needed */
3982 residue=1; /* residue for rounding */
3983 if (diffsign) residue=-residue; /* signs differ */
3984 /* copy, shortening if necessary */
3985 decCopyFit(res, rhs, set, &residue, status);
3986 /* if it was already shorter, then need to pad with zeros */
3987 if (shift>0) {
3988 res->digits=decShiftToMost(res->lsu, res->digits, shift);
3989 res->exponent-=shift; /* adjust the exponent. */
3991 /* flip the result sign if unswapped and rhs was negated */
3992 if (!swapped) res->bits^=negate;
3993 decFinish(res, set, &residue, status); /* done */
3994 break;}
3996 /* LHS digits may affect result */
3997 rhsshift=D2U(padding+1)-1; /* this much by Unit shift .. */
3998 mult=powers[padding-(rhsshift*DECDPUN)]; /* .. this by multiplication */
3999 } /* padding needed */
4001 if (diffsign) mult=-mult; /* signs differ */
4003 /* determine the longer operand */
4004 maxdigits=rhs->digits+padding; /* virtual length of RHS */
4005 if (lhs->digits>maxdigits) maxdigits=lhs->digits;
4007 /* Decide on the result buffer to use; if possible place directly */
4008 /* into result. */
4009 acc=res->lsu; /* assume add direct to result */
4010 /* If destructive overlap, or the number is too long, or a carry or */
4011 /* borrow to DIGITS+1 might be possible, a buffer must be used. */
4012 /* [Might be worth more sophisticated tests when maxdigits==reqdigits] */
4013 if ((maxdigits>=reqdigits) /* is, or could be, too large */
4014 || (res==rhs && rhsshift>0)) { /* destructive overlap */
4015 /* buffer needed, choose it; units for maxdigits digits will be */
4016 /* needed, +1 Unit for carry or borrow */
4017 Int need=D2U(maxdigits)+1;
4018 acc=accbuff; /* assume use local buffer */
4019 if (need*sizeof(Unit)>sizeof(accbuff)) {
4020 /* printf("malloc add %ld %ld\n", need, sizeof(accbuff)); */
4021 allocacc=(Unit *)malloc(need*sizeof(Unit));
4022 if (allocacc==NULL) { /* hopeless -- abandon */
4023 *status|=DEC_Insufficient_storage;
4024 break;}
4025 acc=allocacc;
4029 res->bits=(uByte)(bits&DECNEG); /* it's now safe to overwrite.. */
4030 res->exponent=lhs->exponent; /* .. operands (even if aliased) */
4032 #if DECTRACE
4033 decDumpAr('A', lhs->lsu, D2U(lhs->digits));
4034 decDumpAr('B', rhs->lsu, D2U(rhs->digits));
4035 printf(" :h: %ld %ld\n", rhsshift, mult);
4036 #endif
4038 /* add [A+B*m] or subtract [A+B*(-m)] */
4039 res->digits=decUnitAddSub(lhs->lsu, D2U(lhs->digits),
4040 rhs->lsu, D2U(rhs->digits),
4041 rhsshift, acc, mult)
4042 *DECDPUN; /* [units -> digits] */
4043 if (res->digits<0) { /* borrowed... */
4044 res->digits=-res->digits;
4045 res->bits^=DECNEG; /* flip the sign */
4047 #if DECTRACE
4048 decDumpAr('+', acc, D2U(res->digits));
4049 #endif
4051 /* If a buffer was used the result must be copied back, possibly */
4052 /* shortening. (If no buffer was used then the result must have */
4053 /* fit, so can't need rounding and residue must be 0.) */
4054 residue=0; /* clear accumulator */
4055 if (acc!=res->lsu) {
4056 #if DECSUBSET
4057 if (set->extended) { /* round from first significant digit */
4058 #endif
4059 /* remove leading zeros that were added due to rounding up to */
4060 /* integral Units -- before the test for rounding. */
4061 if (res->digits>reqdigits)
4062 res->digits=decGetDigits(acc, D2U(res->digits));
4063 decSetCoeff(res, set, acc, res->digits, &residue, status);
4064 #if DECSUBSET
4066 else { /* subset arithmetic rounds from original significant digit */
4067 /* May have an underestimate. This only occurs when both */
4068 /* numbers fit in DECDPUN digits and are padding with a */
4069 /* negative multiple (-10, -100...) and the top digit(s) become */
4070 /* 0. (This only matters when using X3.274 rules where the */
4071 /* leading zero could be included in the rounding.) */
4072 if (res->digits<maxdigits) {
4073 *(acc+D2U(res->digits))=0; /* ensure leading 0 is there */
4074 res->digits=maxdigits;
4076 else {
4077 /* remove leading zeros that added due to rounding up to */
4078 /* integral Units (but only those in excess of the original */
4079 /* maxdigits length, unless extended) before test for rounding. */
4080 if (res->digits>reqdigits) {
4081 res->digits=decGetDigits(acc, D2U(res->digits));
4082 if (res->digits<maxdigits) res->digits=maxdigits;
4085 decSetCoeff(res, set, acc, res->digits, &residue, status);
4086 /* Now apply rounding if needed before removing leading zeros. */
4087 /* This is safe because subnormals are not a possibility */
4088 if (residue!=0) {
4089 decApplyRound(res, set, residue, status);
4090 residue=0; /* did what needed to be done */
4092 } /* subset */
4093 #endif
4094 } /* used buffer */
4096 /* strip leading zeros [these were left on in case of subset subtract] */
4097 res->digits=decGetDigits(res->lsu, D2U(res->digits));
4099 /* apply checks and rounding */
4100 decFinish(res, set, &residue, status);
4102 /* "When the sum of two operands with opposite signs is exactly */
4103 /* zero, the sign of that sum shall be '+' in all rounding modes */
4104 /* except round toward -Infinity, in which mode that sign shall be */
4105 /* '-'." [Subset zeros also never have '-', set by decFinish.] */
4106 if (ISZERO(res) && diffsign
4107 #if DECSUBSET
4108 && set->extended
4109 #endif
4110 && (*status&DEC_Inexact)==0) {
4111 if (set->round==DEC_ROUND_FLOOR) res->bits|=DECNEG; /* sign - */
4112 else res->bits&=~DECNEG; /* sign + */
4114 } while(0); /* end protected */
4116 if (allocacc!=NULL) free(allocacc); /* drop any storage used */
4117 #if DECSUBSET
4118 if (allocrhs!=NULL) free(allocrhs); /* .. */
4119 if (alloclhs!=NULL) free(alloclhs); /* .. */
4120 #endif
4121 return res;
4122 } /* decAddOp */
4124 /* ------------------------------------------------------------------ */
4125 /* decDivideOp -- division operation */
4126 /* */
4127 /* This routine performs the calculations for all four division */
4128 /* operators (divide, divideInteger, remainder, remainderNear). */
4129 /* */
4130 /* C=A op B */
4131 /* */
4132 /* res is C, the result. C may be A and/or B (e.g., X=X/X) */
4133 /* lhs is A */
4134 /* rhs is B */
4135 /* set is the context */
4136 /* op is DIVIDE, DIVIDEINT, REMAINDER, or REMNEAR respectively. */
4137 /* status is the usual accumulator */
4138 /* */
4139 /* C must have space for set->digits digits. */
4140 /* */
4141 /* ------------------------------------------------------------------ */
4142 /* The underlying algorithm of this routine is the same as in the */
4143 /* 1981 S/370 implementation, that is, non-restoring long division */
4144 /* with bi-unit (rather than bi-digit) estimation for each unit */
4145 /* multiplier. In this pseudocode overview, complications for the */
4146 /* Remainder operators and division residues for exact rounding are */
4147 /* omitted for clarity. */
4148 /* */
4149 /* Prepare operands and handle special values */
4150 /* Test for x/0 and then 0/x */
4151 /* Exp =Exp1 - Exp2 */
4152 /* Exp =Exp +len(var1) -len(var2) */
4153 /* Sign=Sign1 * Sign2 */
4154 /* Pad accumulator (Var1) to double-length with 0's (pad1) */
4155 /* Pad Var2 to same length as Var1 */
4156 /* msu2pair/plus=1st 2 or 1 units of var2, +1 to allow for round */
4157 /* have=0 */
4158 /* Do until (have=digits+1 OR residue=0) */
4159 /* if exp<0 then if integer divide/residue then leave */
4160 /* this_unit=0 */
4161 /* Do forever */
4162 /* compare numbers */
4163 /* if <0 then leave inner_loop */
4164 /* if =0 then (* quick exit without subtract *) do */
4165 /* this_unit=this_unit+1; output this_unit */
4166 /* leave outer_loop; end */
4167 /* Compare lengths of numbers (mantissae): */
4168 /* If same then tops2=msu2pair -- {units 1&2 of var2} */
4169 /* else tops2=msu2plus -- {0, unit 1 of var2} */
4170 /* tops1=first_unit_of_Var1*10**DECDPUN +second_unit_of_var1 */
4171 /* mult=tops1/tops2 -- Good and safe guess at divisor */
4172 /* if mult=0 then mult=1 */
4173 /* this_unit=this_unit+mult */
4174 /* subtract */
4175 /* end inner_loop */
4176 /* if have\=0 | this_unit\=0 then do */
4177 /* output this_unit */
4178 /* have=have+1; end */
4179 /* var2=var2/10 */
4180 /* exp=exp-1 */
4181 /* end outer_loop */
4182 /* exp=exp+1 -- set the proper exponent */
4183 /* if have=0 then generate answer=0 */
4184 /* Return (Result is defined by Var1) */
4185 /* */
4186 /* ------------------------------------------------------------------ */
4187 /* Two working buffers are needed during the division; one (digits+ */
4188 /* 1) to accumulate the result, and the other (up to 2*digits+1) for */
4189 /* long subtractions. These are acc and var1 respectively. */
4190 /* var1 is a copy of the lhs coefficient, var2 is the rhs coefficient.*/
4191 /* The static buffers may be larger than might be expected to allow */
4192 /* for calls from higher-level funtions (notable exp). */
4193 /* ------------------------------------------------------------------ */
4194 static decNumber * decDivideOp(decNumber *res,
4195 const decNumber *lhs, const decNumber *rhs,
4196 decContext *set, Flag op, uInt *status) {
4197 #if DECSUBSET
4198 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */
4199 decNumber *allocrhs=NULL; /* .., rhs */
4200 #endif
4201 Unit accbuff[SD2U(DECBUFFER+DECDPUN+10)]; /* local buffer */
4202 Unit *acc=accbuff; /* -> accumulator array for result */
4203 Unit *allocacc=NULL; /* -> allocated buffer, iff allocated */
4204 Unit *accnext; /* -> where next digit will go */
4205 Int acclength; /* length of acc needed [Units] */
4206 Int accunits; /* count of units accumulated */
4207 Int accdigits; /* count of digits accumulated */
4209 Unit varbuff[SD2U(DECBUFFER*2+DECDPUN)*sizeof(Unit)]; /* buffer for var1 */
4210 Unit *var1=varbuff; /* -> var1 array for long subtraction */
4211 Unit *varalloc=NULL; /* -> allocated buffer, iff used */
4212 Unit *msu1; /* -> msu of var1 */
4214 const Unit *var2; /* -> var2 array */
4215 const Unit *msu2; /* -> msu of var2 */
4216 Int msu2plus; /* msu2 plus one [does not vary] */
4217 eInt msu2pair; /* msu2 pair plus one [does not vary] */
4219 Int var1units, var2units; /* actual lengths */
4220 Int var2ulen; /* logical length (units) */
4221 Int var1initpad=0; /* var1 initial padding (digits) */
4222 Int maxdigits; /* longest LHS or required acc length */
4223 Int mult; /* multiplier for subtraction */
4224 Unit thisunit; /* current unit being accumulated */
4225 Int residue; /* for rounding */
4226 Int reqdigits=set->digits; /* requested DIGITS */
4227 Int exponent; /* working exponent */
4228 Int maxexponent=0; /* DIVIDE maximum exponent if unrounded */
4229 uByte bits; /* working sign */
4230 Unit *target; /* work */
4231 const Unit *source; /* .. */
4232 uInt const *pow; /* .. */
4233 Int shift, cut; /* .. */
4234 #if DECSUBSET
4235 Int dropped; /* work */
4236 #endif
4238 #if DECCHECK
4239 if (decCheckOperands(res, lhs, rhs, set)) return res;
4240 #endif
4242 do { /* protect allocated storage */
4243 #if DECSUBSET
4244 if (!set->extended) {
4245 /* reduce operands and set lostDigits status, as needed */
4246 if (lhs->digits>reqdigits) {
4247 alloclhs=decRoundOperand(lhs, set, status);
4248 if (alloclhs==NULL) break;
4249 lhs=alloclhs;
4251 if (rhs->digits>reqdigits) {
4252 allocrhs=decRoundOperand(rhs, set, status);
4253 if (allocrhs==NULL) break;
4254 rhs=allocrhs;
4257 #endif
4258 /* [following code does not require input rounding] */
4260 bits=(lhs->bits^rhs->bits)&DECNEG; /* assumed sign for divisions */
4262 /* handle infinities and NaNs */
4263 if (SPECIALARGS) { /* a special bit set */
4264 if (SPECIALARGS & (DECSNAN | DECNAN)) { /* one or two NaNs */
4265 decNaNs(res, lhs, rhs, set, status);
4266 break;
4268 /* one or two infinities */
4269 if (decNumberIsInfinite(lhs)) { /* LHS (dividend) is infinite */
4270 if (decNumberIsInfinite(rhs) || /* two infinities are invalid .. */
4271 op & (REMAINDER | REMNEAR)) { /* as is remainder of infinity */
4272 *status|=DEC_Invalid_operation;
4273 break;
4275 /* [Note that infinity/0 raises no exceptions] */
4276 decNumberZero(res);
4277 res->bits=bits|DECINF; /* set +/- infinity */
4278 break;
4280 else { /* RHS (divisor) is infinite */
4281 residue=0;
4282 if (op&(REMAINDER|REMNEAR)) {
4283 /* result is [finished clone of] lhs */
4284 decCopyFit(res, lhs, set, &residue, status);
4286 else { /* a division */
4287 decNumberZero(res);
4288 res->bits=bits; /* set +/- zero */
4289 /* for DIVIDEINT the exponent is always 0. For DIVIDE, result */
4290 /* is a 0 with infinitely negative exponent, clamped to minimum */
4291 if (op&DIVIDE) {
4292 res->exponent=set->emin-set->digits+1;
4293 *status|=DEC_Clamped;
4296 decFinish(res, set, &residue, status);
4297 break;
4301 /* handle 0 rhs (x/0) */
4302 if (ISZERO(rhs)) { /* x/0 is always exceptional */
4303 if (ISZERO(lhs)) {
4304 decNumberZero(res); /* [after lhs test] */
4305 *status|=DEC_Division_undefined;/* 0/0 will become NaN */
4307 else {
4308 decNumberZero(res);
4309 if (op&(REMAINDER|REMNEAR)) *status|=DEC_Invalid_operation;
4310 else {
4311 *status|=DEC_Division_by_zero; /* x/0 */
4312 res->bits=bits|DECINF; /* .. is +/- Infinity */
4315 break;}
4317 /* handle 0 lhs (0/x) */
4318 if (ISZERO(lhs)) { /* 0/x [x!=0] */
4319 #if DECSUBSET
4320 if (!set->extended) decNumberZero(res);
4321 else {
4322 #endif
4323 if (op&DIVIDE) {
4324 residue=0;
4325 exponent=lhs->exponent-rhs->exponent; /* ideal exponent */
4326 decNumberCopy(res, lhs); /* [zeros always fit] */
4327 res->bits=bits; /* sign as computed */
4328 res->exponent=exponent; /* exponent, too */
4329 decFinalize(res, set, &residue, status); /* check exponent */
4331 else if (op&DIVIDEINT) {
4332 decNumberZero(res); /* integer 0 */
4333 res->bits=bits; /* sign as computed */
4335 else { /* a remainder */
4336 exponent=rhs->exponent; /* [save in case overwrite] */
4337 decNumberCopy(res, lhs); /* [zeros always fit] */
4338 if (exponent<res->exponent) res->exponent=exponent; /* use lower */
4340 #if DECSUBSET
4342 #endif
4343 break;}
4345 /* Precalculate exponent. This starts off adjusted (and hence fits */
4346 /* in 31 bits) and becomes the usual unadjusted exponent as the */
4347 /* division proceeds. The order of evaluation is important, here, */
4348 /* to avoid wrap. */
4349 exponent=(lhs->exponent+lhs->digits)-(rhs->exponent+rhs->digits);
4351 /* If the working exponent is -ve, then some quick exits are */
4352 /* possible because the quotient is known to be <1 */
4353 /* [for REMNEAR, it needs to be < -1, as -0.5 could need work] */
4354 if (exponent<0 && !(op==DIVIDE)) {
4355 if (op&DIVIDEINT) {
4356 decNumberZero(res); /* integer part is 0 */
4357 #if DECSUBSET
4358 if (set->extended)
4359 #endif
4360 res->bits=bits; /* set +/- zero */
4361 break;}
4362 /* fastpath remainders so long as the lhs has the smaller */
4363 /* (or equal) exponent */
4364 if (lhs->exponent<=rhs->exponent) {
4365 if (op&REMAINDER || exponent<-1) {
4366 /* It is REMAINDER or safe REMNEAR; result is [finished */
4367 /* clone of] lhs (r = x - 0*y) */
4368 residue=0;
4369 decCopyFit(res, lhs, set, &residue, status);
4370 decFinish(res, set, &residue, status);
4371 break;
4373 /* [unsafe REMNEAR drops through] */
4375 } /* fastpaths */
4377 /* Long (slow) division is needed; roll up the sleeves... */
4379 /* The accumulator will hold the quotient of the division. */
4380 /* If it needs to be too long for stack storage, then allocate. */
4381 acclength=D2U(reqdigits+DECDPUN); /* in Units */
4382 if (acclength*sizeof(Unit)>sizeof(accbuff)) {
4383 /* printf("malloc dvacc %ld units\n", acclength); */
4384 allocacc=(Unit *)malloc(acclength*sizeof(Unit));
4385 if (allocacc==NULL) { /* hopeless -- abandon */
4386 *status|=DEC_Insufficient_storage;
4387 break;}
4388 acc=allocacc; /* use the allocated space */
4391 /* var1 is the padded LHS ready for subtractions. */
4392 /* If it needs to be too long for stack storage, then allocate. */
4393 /* The maximum units needed for var1 (long subtraction) is: */
4394 /* Enough for */
4395 /* (rhs->digits+reqdigits-1) -- to allow full slide to right */
4396 /* or (lhs->digits) -- to allow for long lhs */
4397 /* whichever is larger */
4398 /* +1 -- for rounding of slide to right */
4399 /* +1 -- for leading 0s */
4400 /* +1 -- for pre-adjust if a remainder or DIVIDEINT */
4401 /* [Note: unused units do not participate in decUnitAddSub data] */
4402 maxdigits=rhs->digits+reqdigits-1;
4403 if (lhs->digits>maxdigits) maxdigits=lhs->digits;
4404 var1units=D2U(maxdigits)+2;
4405 /* allocate a guard unit above msu1 for REMAINDERNEAR */
4406 if (!(op&DIVIDE)) var1units++;
4407 if ((var1units+1)*sizeof(Unit)>sizeof(varbuff)) {
4408 /* printf("malloc dvvar %ld units\n", var1units+1); */
4409 varalloc=(Unit *)malloc((var1units+1)*sizeof(Unit));
4410 if (varalloc==NULL) { /* hopeless -- abandon */
4411 *status|=DEC_Insufficient_storage;
4412 break;}
4413 var1=varalloc; /* use the allocated space */
4416 /* Extend the lhs and rhs to full long subtraction length. The lhs */
4417 /* is truly extended into the var1 buffer, with 0 padding, so a */
4418 /* subtract in place is always possible. The rhs (var2) has */
4419 /* virtual padding (implemented by decUnitAddSub). */
4420 /* One guard unit was allocated above msu1 for rem=rem+rem in */
4421 /* REMAINDERNEAR. */
4422 msu1=var1+var1units-1; /* msu of var1 */
4423 source=lhs->lsu+D2U(lhs->digits)-1; /* msu of input array */
4424 for (target=msu1; source>=lhs->lsu; source--, target--) *target=*source;
4425 for (; target>=var1; target--) *target=0;
4427 /* rhs (var2) is left-aligned with var1 at the start */
4428 var2ulen=var1units; /* rhs logical length (units) */
4429 var2units=D2U(rhs->digits); /* rhs actual length (units) */
4430 var2=rhs->lsu; /* -> rhs array */
4431 msu2=var2+var2units-1; /* -> msu of var2 [never changes] */
4432 /* now set up the variables which will be used for estimating the */
4433 /* multiplication factor. If these variables are not exact, add */
4434 /* 1 to make sure that the multiplier is never overestimated. */
4435 msu2plus=*msu2; /* it's value .. */
4436 if (var2units>1) msu2plus++; /* .. +1 if any more */
4437 msu2pair=(eInt)*msu2*(DECDPUNMAX+1);/* top two pair .. */
4438 if (var2units>1) { /* .. [else treat 2nd as 0] */
4439 msu2pair+=*(msu2-1); /* .. */
4440 if (var2units>2) msu2pair++; /* .. +1 if any more */
4443 /* The calculation is working in units, which may have leading zeros, */
4444 /* but the exponent was calculated on the assumption that they are */
4445 /* both left-aligned. Adjust the exponent to compensate: add the */
4446 /* number of leading zeros in var1 msu and subtract those in var2 msu. */
4447 /* [This is actually done by counting the digits and negating, as */
4448 /* lead1=DECDPUN-digits1, and similarly for lead2.] */
4449 for (pow=&powers[1]; *msu1>=*pow; pow++) exponent--;
4450 for (pow=&powers[1]; *msu2>=*pow; pow++) exponent++;
4452 /* Now, if doing an integer divide or remainder, ensure that */
4453 /* the result will be Unit-aligned. To do this, shift the var1 */
4454 /* accumulator towards least if need be. (It's much easier to */
4455 /* do this now than to reassemble the residue afterwards, if */
4456 /* doing a remainder.) Also ensure the exponent is not negative. */
4457 if (!(op&DIVIDE)) {
4458 Unit *u; /* work */
4459 /* save the initial 'false' padding of var1, in digits */
4460 var1initpad=(var1units-D2U(lhs->digits))*DECDPUN;
4461 /* Determine the shift to do. */
4462 if (exponent<0) cut=-exponent;
4463 else cut=DECDPUN-exponent%DECDPUN;
4464 decShiftToLeast(var1, var1units, cut);
4465 exponent+=cut; /* maintain numerical value */
4466 var1initpad-=cut; /* .. and reduce padding */
4467 /* clean any most-significant units which were just emptied */
4468 for (u=msu1; cut>=DECDPUN; cut-=DECDPUN, u--) *u=0;
4469 } /* align */
4470 else { /* is DIVIDE */
4471 maxexponent=lhs->exponent-rhs->exponent; /* save */
4472 /* optimization: if the first iteration will just produce 0, */
4473 /* preadjust to skip it [valid for DIVIDE only] */
4474 if (*msu1<*msu2) {
4475 var2ulen--; /* shift down */
4476 exponent-=DECDPUN; /* update the exponent */
4480 /* ---- start the long-division loops ------------------------------ */
4481 accunits=0; /* no units accumulated yet */
4482 accdigits=0; /* .. or digits */
4483 accnext=acc+acclength-1; /* -> msu of acc [NB: allows digits+1] */
4484 for (;;) { /* outer forever loop */
4485 thisunit=0; /* current unit assumed 0 */
4486 /* find the next unit */
4487 for (;;) { /* inner forever loop */
4488 /* strip leading zero units [from either pre-adjust or from */
4489 /* subtract last time around]. Leave at least one unit. */
4490 for (; *msu1==0 && msu1>var1; msu1--) var1units--;
4492 if (var1units<var2ulen) break; /* var1 too low for subtract */
4493 if (var1units==var2ulen) { /* unit-by-unit compare needed */
4494 /* compare the two numbers, from msu */
4495 const Unit *pv1, *pv2;
4496 Unit v2; /* units to compare */
4497 pv2=msu2; /* -> msu */
4498 for (pv1=msu1; ; pv1--, pv2--) {
4499 /* v1=*pv1 -- always OK */
4500 v2=0; /* assume in padding */
4501 if (pv2>=var2) v2=*pv2; /* in range */
4502 if (*pv1!=v2) break; /* no longer the same */
4503 if (pv1==var1) break; /* done; leave pv1 as is */
4505 /* here when all inspected or a difference seen */
4506 if (*pv1<v2) break; /* var1 too low to subtract */
4507 if (*pv1==v2) { /* var1 == var2 */
4508 /* reach here if var1 and var2 are identical; subtraction */
4509 /* would increase digit by one, and the residue will be 0 so */
4510 /* the calculation is done; leave the loop with residue=0. */
4511 thisunit++; /* as though subtracted */
4512 *var1=0; /* set var1 to 0 */
4513 var1units=1; /* .. */
4514 break; /* from inner */
4515 } /* var1 == var2 */
4516 /* *pv1>v2. Prepare for real subtraction; the lengths are equal */
4517 /* Estimate the multiplier (there's always a msu1-1)... */
4518 /* Bring in two units of var2 to provide a good estimate. */
4519 mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2pair);
4520 } /* lengths the same */
4521 else { /* var1units > var2ulen, so subtraction is safe */
4522 /* The var2 msu is one unit towards the lsu of the var1 msu, */
4523 /* so only one unit for var2 can be used. */
4524 mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2plus);
4526 if (mult==0) mult=1; /* must always be at least 1 */
4527 /* subtraction needed; var1 is > var2 */
4528 thisunit=(Unit)(thisunit+mult); /* accumulate */
4529 /* subtract var1-var2, into var1; only the overlap needs */
4530 /* processing, as this is an in-place calculation */
4531 shift=var2ulen-var2units;
4532 #if DECTRACE
4533 decDumpAr('1', &var1[shift], var1units-shift);
4534 decDumpAr('2', var2, var2units);
4535 printf("m=%ld\n", -mult);
4536 #endif
4537 decUnitAddSub(&var1[shift], var1units-shift,
4538 var2, var2units, 0,
4539 &var1[shift], -mult);
4540 #if DECTRACE
4541 decDumpAr('#', &var1[shift], var1units-shift);
4542 #endif
4543 /* var1 now probably has leading zeros; these are removed at the */
4544 /* top of the inner loop. */
4545 } /* inner loop */
4547 /* The next unit has been calculated in full; unless it's a */
4548 /* leading zero, add to acc */
4549 if (accunits!=0 || thisunit!=0) { /* is first or non-zero */
4550 *accnext=thisunit; /* store in accumulator */
4551 /* account exactly for the new digits */
4552 if (accunits==0) {
4553 accdigits++; /* at least one */
4554 for (pow=&powers[1]; thisunit>=*pow; pow++) accdigits++;
4556 else accdigits+=DECDPUN;
4557 accunits++; /* update count */
4558 accnext--; /* ready for next */
4559 if (accdigits>reqdigits) break; /* have enough digits */
4562 /* if the residue is zero, the operation is done (unless divide */
4563 /* or divideInteger and still not enough digits yet) */
4564 if (*var1==0 && var1units==1) { /* residue is 0 */
4565 if (op&(REMAINDER|REMNEAR)) break;
4566 if ((op&DIVIDE) && (exponent<=maxexponent)) break;
4567 /* [drop through if divideInteger] */
4569 /* also done enough if calculating remainder or integer */
4570 /* divide and just did the last ('units') unit */
4571 if (exponent==0 && !(op&DIVIDE)) break;
4573 /* to get here, var1 is less than var2, so divide var2 by the per- */
4574 /* Unit power of ten and go for the next digit */
4575 var2ulen--; /* shift down */
4576 exponent-=DECDPUN; /* update the exponent */
4577 } /* outer loop */
4579 /* ---- division is complete --------------------------------------- */
4580 /* here: acc has at least reqdigits+1 of good results (or fewer */
4581 /* if early stop), starting at accnext+1 (its lsu) */
4582 /* var1 has any residue at the stopping point */
4583 /* accunits is the number of digits collected in acc */
4584 if (accunits==0) { /* acc is 0 */
4585 accunits=1; /* show have a unit .. */
4586 accdigits=1; /* .. */
4587 *accnext=0; /* .. whose value is 0 */
4589 else accnext++; /* back to last placed */
4590 /* accnext now -> lowest unit of result */
4592 residue=0; /* assume no residue */
4593 if (op&DIVIDE) {
4594 /* record the presence of any residue, for rounding */
4595 if (*var1!=0 || var1units>1) residue=1;
4596 else { /* no residue */
4597 /* Had an exact division; clean up spurious trailing 0s. */
4598 /* There will be at most DECDPUN-1, from the final multiply, */
4599 /* and then only if the result is non-0 (and even) and the */
4600 /* exponent is 'loose'. */
4601 #if DECDPUN>1
4602 Unit lsu=*accnext;
4603 if (!(lsu&0x01) && (lsu!=0)) {
4604 /* count the trailing zeros */
4605 Int drop=0;
4606 for (;; drop++) { /* [will terminate because lsu!=0] */
4607 if (exponent>=maxexponent) break; /* don't chop real 0s */
4608 #if DECDPUN<=4
4609 if ((lsu-QUOT10(lsu, drop+1)
4610 *powers[drop+1])!=0) break; /* found non-0 digit */
4611 #else
4612 if (lsu%powers[drop+1]!=0) break; /* found non-0 digit */
4613 #endif
4614 exponent++;
4616 if (drop>0) {
4617 accunits=decShiftToLeast(accnext, accunits, drop);
4618 accdigits=decGetDigits(accnext, accunits);
4619 accunits=D2U(accdigits);
4620 /* [exponent was adjusted in the loop] */
4622 } /* neither odd nor 0 */
4623 #endif
4624 } /* exact divide */
4625 } /* divide */
4626 else /* op!=DIVIDE */ {
4627 /* check for coefficient overflow */
4628 if (accdigits+exponent>reqdigits) {
4629 *status|=DEC_Division_impossible;
4630 break;
4632 if (op & (REMAINDER|REMNEAR)) {
4633 /* [Here, the exponent will be 0, because var1 was adjusted */
4634 /* appropriately.] */
4635 Int postshift; /* work */
4636 Flag wasodd=0; /* integer was odd */
4637 Unit *quotlsu; /* for save */
4638 Int quotdigits; /* .. */
4640 bits=lhs->bits; /* remainder sign is always as lhs */
4642 /* Fastpath when residue is truly 0 is worthwhile [and */
4643 /* simplifies the code below] */
4644 if (*var1==0 && var1units==1) { /* residue is 0 */
4645 Int exp=lhs->exponent; /* save min(exponents) */
4646 if (rhs->exponent<exp) exp=rhs->exponent;
4647 decNumberZero(res); /* 0 coefficient */
4648 #if DECSUBSET
4649 if (set->extended)
4650 #endif
4651 res->exponent=exp; /* .. with proper exponent */
4652 res->bits=(uByte)(bits&DECNEG); /* [cleaned] */
4653 decFinish(res, set, &residue, status); /* might clamp */
4654 break;
4656 /* note if the quotient was odd */
4657 if (*accnext & 0x01) wasodd=1; /* acc is odd */
4658 quotlsu=accnext; /* save in case need to reinspect */
4659 quotdigits=accdigits; /* .. */
4661 /* treat the residue, in var1, as the value to return, via acc */
4662 /* calculate the unused zero digits. This is the smaller of: */
4663 /* var1 initial padding (saved above) */
4664 /* var2 residual padding, which happens to be given by: */
4665 postshift=var1initpad+exponent-lhs->exponent+rhs->exponent;
4666 /* [the 'exponent' term accounts for the shifts during divide] */
4667 if (var1initpad<postshift) postshift=var1initpad;
4669 /* shift var1 the requested amount, and adjust its digits */
4670 var1units=decShiftToLeast(var1, var1units, postshift);
4671 accnext=var1;
4672 accdigits=decGetDigits(var1, var1units);
4673 accunits=D2U(accdigits);
4675 exponent=lhs->exponent; /* exponent is smaller of lhs & rhs */
4676 if (rhs->exponent<exponent) exponent=rhs->exponent;
4678 /* Now correct the result if doing remainderNear; if it */
4679 /* (looking just at coefficients) is > rhs/2, or == rhs/2 and */
4680 /* the integer was odd then the result should be rem-rhs. */
4681 if (op&REMNEAR) {
4682 Int compare, tarunits; /* work */
4683 Unit *up; /* .. */
4684 /* calculate remainder*2 into the var1 buffer (which has */
4685 /* 'headroom' of an extra unit and hence enough space) */
4686 /* [a dedicated 'double' loop would be faster, here] */
4687 tarunits=decUnitAddSub(accnext, accunits, accnext, accunits,
4688 0, accnext, 1);
4689 /* decDumpAr('r', accnext, tarunits); */
4691 /* Here, accnext (var1) holds tarunits Units with twice the */
4692 /* remainder's coefficient, which must now be compared to the */
4693 /* RHS. The remainder's exponent may be smaller than the RHS's. */
4694 compare=decUnitCompare(accnext, tarunits, rhs->lsu, D2U(rhs->digits),
4695 rhs->exponent-exponent);
4696 if (compare==BADINT) { /* deep trouble */
4697 *status|=DEC_Insufficient_storage;
4698 break;}
4700 /* now restore the remainder by dividing by two; the lsu */
4701 /* is known to be even. */
4702 for (up=accnext; up<accnext+tarunits; up++) {
4703 Int half; /* half to add to lower unit */
4704 half=*up & 0x01;
4705 *up/=2; /* [shift] */
4706 if (!half) continue;
4707 *(up-1)+=(DECDPUNMAX+1)/2;
4709 /* [accunits still describes the original remainder length] */
4711 if (compare>0 || (compare==0 && wasodd)) { /* adjustment needed */
4712 Int exp, expunits, exprem; /* work */
4713 /* This is effectively causing round-up of the quotient, */
4714 /* so if it was the rare case where it was full and all */
4715 /* nines, it would overflow and hence division-impossible */
4716 /* should be raised */
4717 Flag allnines=0; /* 1 if quotient all nines */
4718 if (quotdigits==reqdigits) { /* could be borderline */
4719 for (up=quotlsu; ; up++) {
4720 if (quotdigits>DECDPUN) {
4721 if (*up!=DECDPUNMAX) break;/* non-nines */
4723 else { /* this is the last Unit */
4724 if (*up==powers[quotdigits]-1) allnines=1;
4725 break;
4727 quotdigits-=DECDPUN; /* checked those digits */
4728 } /* up */
4729 } /* borderline check */
4730 if (allnines) {
4731 *status|=DEC_Division_impossible;
4732 break;}
4734 /* rem-rhs is needed; the sign will invert. Again, var1 */
4735 /* can safely be used for the working Units array. */
4736 exp=rhs->exponent-exponent; /* RHS padding needed */
4737 /* Calculate units and remainder from exponent. */
4738 expunits=exp/DECDPUN;
4739 exprem=exp%DECDPUN;
4740 /* subtract [A+B*(-m)]; the result will always be negative */
4741 accunits=-decUnitAddSub(accnext, accunits,
4742 rhs->lsu, D2U(rhs->digits),
4743 expunits, accnext, -(Int)powers[exprem]);
4744 accdigits=decGetDigits(accnext, accunits); /* count digits exactly */
4745 accunits=D2U(accdigits); /* and recalculate the units for copy */
4746 /* [exponent is as for original remainder] */
4747 bits^=DECNEG; /* flip the sign */
4749 } /* REMNEAR */
4750 } /* REMAINDER or REMNEAR */
4751 } /* not DIVIDE */
4753 /* Set exponent and bits */
4754 res->exponent=exponent;
4755 res->bits=(uByte)(bits&DECNEG); /* [cleaned] */
4757 /* Now the coefficient. */
4758 decSetCoeff(res, set, accnext, accdigits, &residue, status);
4760 decFinish(res, set, &residue, status); /* final cleanup */
4762 #if DECSUBSET
4763 /* If a divide then strip trailing zeros if subset [after round] */
4764 if (!set->extended && (op==DIVIDE)) decTrim(res, set, 0, &dropped);
4765 #endif
4766 } while(0); /* end protected */
4768 if (varalloc!=NULL) free(varalloc); /* drop any storage used */
4769 if (allocacc!=NULL) free(allocacc); /* .. */
4770 #if DECSUBSET
4771 if (allocrhs!=NULL) free(allocrhs); /* .. */
4772 if (alloclhs!=NULL) free(alloclhs); /* .. */
4773 #endif
4774 return res;
4775 } /* decDivideOp */
4777 /* ------------------------------------------------------------------ */
4778 /* decMultiplyOp -- multiplication operation */
4779 /* */
4780 /* This routine performs the multiplication C=A x B. */
4781 /* */
4782 /* res is C, the result. C may be A and/or B (e.g., X=X*X) */
4783 /* lhs is A */
4784 /* rhs is B */
4785 /* set is the context */
4786 /* status is the usual accumulator */
4787 /* */
4788 /* C must have space for set->digits digits. */
4789 /* */
4790 /* ------------------------------------------------------------------ */
4791 /* 'Classic' multiplication is used rather than Karatsuba, as the */
4792 /* latter would give only a minor improvement for the short numbers */
4793 /* expected to be handled most (and uses much more memory). */
4794 /* */
4795 /* There are two major paths here: the general-purpose ('old code') */
4796 /* path which handles all DECDPUN values, and a fastpath version */
4797 /* which is used if 64-bit ints are available, DECDPUN<=4, and more */
4798 /* than two calls to decUnitAddSub would be made. */
4799 /* */
4800 /* The fastpath version lumps units together into 8-digit or 9-digit */
4801 /* chunks, and also uses a lazy carry strategy to minimise expensive */
4802 /* 64-bit divisions. The chunks are then broken apart again into */
4803 /* units for continuing processing. Despite this overhead, the */
4804 /* fastpath can speed up some 16-digit operations by 10x (and much */
4805 /* more for higher-precision calculations). */
4806 /* */
4807 /* A buffer always has to be used for the accumulator; in the */
4808 /* fastpath, buffers are also always needed for the chunked copies of */
4809 /* of the operand coefficients. */
4810 /* Static buffers are larger than needed just for multiply, to allow */
4811 /* for calls from other operations (notably exp). */
4812 /* ------------------------------------------------------------------ */
4813 #define FASTMUL (DECUSE64 && DECDPUN<5)
4814 static decNumber * decMultiplyOp(decNumber *res, const decNumber *lhs,
4815 const decNumber *rhs, decContext *set,
4816 uInt *status) {
4817 Int accunits; /* Units of accumulator in use */
4818 Int exponent; /* work */
4819 Int residue=0; /* rounding residue */
4820 uByte bits; /* result sign */
4821 Unit *acc; /* -> accumulator Unit array */
4822 Int needbytes; /* size calculator */
4823 void *allocacc=NULL; /* -> allocated accumulator, iff allocated */
4824 Unit accbuff[SD2U(DECBUFFER*4+1)]; /* buffer (+1 for DECBUFFER==0, */
4825 /* *4 for calls from other operations) */
4826 const Unit *mer, *mermsup; /* work */
4827 Int madlength; /* Units in multiplicand */
4828 Int shift; /* Units to shift multiplicand by */
4830 #if FASTMUL
4831 /* if DECDPUN is 1 or 3 work in base 10**9, otherwise */
4832 /* (DECDPUN is 2 or 4) then work in base 10**8 */
4833 #if DECDPUN & 1 /* odd */
4834 #define FASTBASE 1000000000 /* base */
4835 #define FASTDIGS 9 /* digits in base */
4836 #define FASTLAZY 18 /* carry resolution point [1->18] */
4837 #else
4838 #define FASTBASE 100000000
4839 #define FASTDIGS 8
4840 #define FASTLAZY 1844 /* carry resolution point [1->1844] */
4841 #endif
4842 /* three buffers are used, two for chunked copies of the operands */
4843 /* (base 10**8 or base 10**9) and one base 2**64 accumulator with */
4844 /* lazy carry evaluation */
4845 uInt zlhibuff[(DECBUFFER*2+1)/8+1]; /* buffer (+1 for DECBUFFER==0) */
4846 uInt *zlhi=zlhibuff; /* -> lhs array */
4847 uInt *alloclhi=NULL; /* -> allocated buffer, iff allocated */
4848 uInt zrhibuff[(DECBUFFER*2+1)/8+1]; /* buffer (+1 for DECBUFFER==0) */
4849 uInt *zrhi=zrhibuff; /* -> rhs array */
4850 uInt *allocrhi=NULL; /* -> allocated buffer, iff allocated */
4851 uLong zaccbuff[(DECBUFFER*2+1)/4+2]; /* buffer (+1 for DECBUFFER==0) */
4852 /* [allocacc is shared for both paths, as only one will run] */
4853 uLong *zacc=zaccbuff; /* -> accumulator array for exact result */
4854 #if DECDPUN==1
4855 Int zoff; /* accumulator offset */
4856 #endif
4857 uInt *lip, *rip; /* item pointers */
4858 uInt *lmsi, *rmsi; /* most significant items */
4859 Int ilhs, irhs, iacc; /* item counts in the arrays */
4860 Int lazy; /* lazy carry counter */
4861 uLong lcarry; /* uLong carry */
4862 uInt carry; /* carry (NB not uLong) */
4863 Int count; /* work */
4864 const Unit *cup; /* .. */
4865 Unit *up; /* .. */
4866 uLong *lp; /* .. */
4867 Int p; /* .. */
4868 #endif
4870 #if DECSUBSET
4871 decNumber *alloclhs=NULL; /* -> allocated buffer, iff allocated */
4872 decNumber *allocrhs=NULL; /* -> allocated buffer, iff allocated */
4873 #endif
4875 #if DECCHECK
4876 if (decCheckOperands(res, lhs, rhs, set)) return res;
4877 #endif
4879 /* precalculate result sign */
4880 bits=(uByte)((lhs->bits^rhs->bits)&DECNEG);
4882 /* handle infinities and NaNs */
4883 if (SPECIALARGS) { /* a special bit set */
4884 if (SPECIALARGS & (DECSNAN | DECNAN)) { /* one or two NaNs */
4885 decNaNs(res, lhs, rhs, set, status);
4886 return res;}
4887 /* one or two infinities; Infinity * 0 is invalid */
4888 if (((lhs->bits & DECINF)==0 && ISZERO(lhs))
4889 ||((rhs->bits & DECINF)==0 && ISZERO(rhs))) {
4890 *status|=DEC_Invalid_operation;
4891 return res;}
4892 decNumberZero(res);
4893 res->bits=bits|DECINF; /* infinity */
4894 return res;}
4896 /* For best speed, as in DMSRCN [the original Rexx numerics */
4897 /* module], use the shorter number as the multiplier (rhs) and */
4898 /* the longer as the multiplicand (lhs) to minimise the number of */
4899 /* adds (partial products) */
4900 if (lhs->digits<rhs->digits) { /* swap... */
4901 const decNumber *hold=lhs;
4902 lhs=rhs;
4903 rhs=hold;
4906 do { /* protect allocated storage */
4907 #if DECSUBSET
4908 if (!set->extended) {
4909 /* reduce operands and set lostDigits status, as needed */
4910 if (lhs->digits>set->digits) {
4911 alloclhs=decRoundOperand(lhs, set, status);
4912 if (alloclhs==NULL) break;
4913 lhs=alloclhs;
4915 if (rhs->digits>set->digits) {
4916 allocrhs=decRoundOperand(rhs, set, status);
4917 if (allocrhs==NULL) break;
4918 rhs=allocrhs;
4921 #endif
4922 /* [following code does not require input rounding] */
4924 #if FASTMUL /* fastpath can be used */
4925 /* use the fast path if there are enough digits in the shorter */
4926 /* operand to make the setup and takedown worthwhile */
4927 #define NEEDTWO (DECDPUN*2) /* within two decUnitAddSub calls */
4928 if (rhs->digits>NEEDTWO) { /* use fastpath... */
4929 /* calculate the number of elements in each array */
4930 ilhs=(lhs->digits+FASTDIGS-1)/FASTDIGS; /* [ceiling] */
4931 irhs=(rhs->digits+FASTDIGS-1)/FASTDIGS; /* .. */
4932 iacc=ilhs+irhs;
4934 /* allocate buffers if required, as usual */
4935 needbytes=ilhs*sizeof(uInt);
4936 if (needbytes>(Int)sizeof(zlhibuff)) {
4937 alloclhi=(uInt *)malloc(needbytes);
4938 zlhi=alloclhi;}
4939 needbytes=irhs*sizeof(uInt);
4940 if (needbytes>(Int)sizeof(zrhibuff)) {
4941 allocrhi=(uInt *)malloc(needbytes);
4942 zrhi=allocrhi;}
4944 /* Allocating the accumulator space needs a special case when */
4945 /* DECDPUN=1 because when converting the accumulator to Units */
4946 /* after the multiplication each 8-byte item becomes 9 1-byte */
4947 /* units. Therefore iacc extra bytes are needed at the front */
4948 /* (rounded up to a multiple of 8 bytes), and the uLong */
4949 /* accumulator starts offset the appropriate number of units */
4950 /* to the right to avoid overwrite during the unchunking. */
4951 needbytes=iacc*sizeof(uLong);
4952 #if DECDPUN==1
4953 zoff=(iacc+7)/8; /* items to offset by */
4954 needbytes+=zoff*8;
4955 #endif
4956 if (needbytes>(Int)sizeof(zaccbuff)) {
4957 allocacc=(uLong *)malloc(needbytes);
4958 zacc=(uLong *)allocacc;}
4959 if (zlhi==NULL||zrhi==NULL||zacc==NULL) {
4960 *status|=DEC_Insufficient_storage;
4961 break;}
4963 acc=(Unit *)zacc; /* -> target Unit array */
4964 #if DECDPUN==1
4965 zacc+=zoff; /* start uLong accumulator to right */
4966 #endif
4968 /* assemble the chunked copies of the left and right sides */
4969 for (count=lhs->digits, cup=lhs->lsu, lip=zlhi; count>0; lip++)
4970 for (p=0, *lip=0; p<FASTDIGS && count>0;
4971 p+=DECDPUN, cup++, count-=DECDPUN)
4972 *lip+=*cup*powers[p];
4973 lmsi=lip-1; /* save -> msi */
4974 for (count=rhs->digits, cup=rhs->lsu, rip=zrhi; count>0; rip++)
4975 for (p=0, *rip=0; p<FASTDIGS && count>0;
4976 p+=DECDPUN, cup++, count-=DECDPUN)
4977 *rip+=*cup*powers[p];
4978 rmsi=rip-1; /* save -> msi */
4980 /* zero the accumulator */
4981 for (lp=zacc; lp<zacc+iacc; lp++) *lp=0;
4983 /* Start the multiplication */
4984 /* Resolving carries can dominate the cost of accumulating the */
4985 /* partial products, so this is only done when necessary. */
4986 /* Each uLong item in the accumulator can hold values up to */
4987 /* 2**64-1, and each partial product can be as large as */
4988 /* (10**FASTDIGS-1)**2. When FASTDIGS=9, this can be added to */
4989 /* itself 18.4 times in a uLong without overflowing, so during */
4990 /* the main calculation resolution is carried out every 18th */
4991 /* add -- every 162 digits. Similarly, when FASTDIGS=8, the */
4992 /* partial products can be added to themselves 1844.6 times in */
4993 /* a uLong without overflowing, so intermediate carry */
4994 /* resolution occurs only every 14752 digits. Hence for common */
4995 /* short numbers usually only the one final carry resolution */
4996 /* occurs. */
4997 /* (The count is set via FASTLAZY to simplify experiments to */
4998 /* measure the value of this approach: a 35% improvement on a */
4999 /* [34x34] multiply.) */
5000 lazy=FASTLAZY; /* carry delay count */
5001 for (rip=zrhi; rip<=rmsi; rip++) { /* over each item in rhs */
5002 lp=zacc+(rip-zrhi); /* where to add the lhs */
5003 for (lip=zlhi; lip<=lmsi; lip++, lp++) { /* over each item in lhs */
5004 *lp+=(uLong)(*lip)*(*rip); /* [this should in-line] */
5005 } /* lip loop */
5006 lazy--;
5007 if (lazy>0 && rip!=rmsi) continue;
5008 lazy=FASTLAZY; /* reset delay count */
5009 /* spin up the accumulator resolving overflows */
5010 for (lp=zacc; lp<zacc+iacc; lp++) {
5011 if (*lp<FASTBASE) continue; /* it fits */
5012 lcarry=*lp/FASTBASE; /* top part [slow divide] */
5013 /* lcarry can exceed 2**32-1, so check again; this check */
5014 /* and occasional extra divide (slow) is well worth it, as */
5015 /* it allows FASTLAZY to be increased to 18 rather than 4 */
5016 /* in the FASTDIGS=9 case */
5017 if (lcarry<FASTBASE) carry=(uInt)lcarry; /* [usual] */
5018 else { /* two-place carry [fairly rare] */
5019 uInt carry2=(uInt)(lcarry/FASTBASE); /* top top part */
5020 *(lp+2)+=carry2; /* add to item+2 */
5021 *lp-=((uLong)FASTBASE*FASTBASE*carry2); /* [slow] */
5022 carry=(uInt)(lcarry-((uLong)FASTBASE*carry2)); /* [inline] */
5024 *(lp+1)+=carry; /* add to item above [inline] */
5025 *lp-=((uLong)FASTBASE*carry); /* [inline] */
5026 } /* carry resolution */
5027 } /* rip loop */
5029 /* The multiplication is complete; time to convert back into */
5030 /* units. This can be done in-place in the accumulator and in */
5031 /* 32-bit operations, because carries were resolved after the */
5032 /* final add. This needs N-1 divides and multiplies for */
5033 /* each item in the accumulator (which will become up to N */
5034 /* units, where 2<=N<=9). */
5035 for (lp=zacc, up=acc; lp<zacc+iacc; lp++) {
5036 uInt item=(uInt)*lp; /* decapitate to uInt */
5037 for (p=0; p<FASTDIGS-DECDPUN; p+=DECDPUN, up++) {
5038 uInt part=item/(DECDPUNMAX+1);
5039 *up=(Unit)(item-(part*(DECDPUNMAX+1)));
5040 item=part;
5041 } /* p */
5042 *up=(Unit)item; up++; /* [final needs no division] */
5043 } /* lp */
5044 accunits=up-acc; /* count of units */
5046 else { /* here to use units directly, without chunking ['old code'] */
5047 #endif
5049 /* if accumulator will be too long for local storage, then allocate */
5050 acc=accbuff; /* -> assume buffer for accumulator */
5051 needbytes=(D2U(lhs->digits)+D2U(rhs->digits))*sizeof(Unit);
5052 if (needbytes>(Int)sizeof(accbuff)) {
5053 allocacc=(Unit *)malloc(needbytes);
5054 if (allocacc==NULL) {*status|=DEC_Insufficient_storage; break;}
5055 acc=(Unit *)allocacc; /* use the allocated space */
5058 /* Now the main long multiplication loop */
5059 /* Unlike the equivalent in the IBM Java implementation, there */
5060 /* is no advantage in calculating from msu to lsu. So, do it */
5061 /* by the book, as it were. */
5062 /* Each iteration calculates ACC=ACC+MULTAND*MULT */
5063 accunits=1; /* accumulator starts at '0' */
5064 *acc=0; /* .. (lsu=0) */
5065 shift=0; /* no multiplicand shift at first */
5066 madlength=D2U(lhs->digits); /* this won't change */
5067 mermsup=rhs->lsu+D2U(rhs->digits); /* -> msu+1 of multiplier */
5069 for (mer=rhs->lsu; mer<mermsup; mer++) {
5070 /* Here, *mer is the next Unit in the multiplier to use */
5071 /* If non-zero [optimization] add it... */
5072 if (*mer!=0) accunits=decUnitAddSub(&acc[shift], accunits-shift,
5073 lhs->lsu, madlength, 0,
5074 &acc[shift], *mer)
5075 + shift;
5076 else { /* extend acc with a 0; it will be used shortly */
5077 *(acc+accunits)=0; /* [this avoids length of <=0 later] */
5078 accunits++;
5080 /* multiply multiplicand by 10**DECDPUN for next Unit to left */
5081 shift++; /* add this for 'logical length' */
5082 } /* n */
5083 #if FASTMUL
5084 } /* unchunked units */
5085 #endif
5086 /* common end-path */
5087 #if DECTRACE
5088 decDumpAr('*', acc, accunits); /* Show exact result */
5089 #endif
5091 /* acc now contains the exact result of the multiplication, */
5092 /* possibly with a leading zero unit; build the decNumber from */
5093 /* it, noting if any residue */
5094 res->bits=bits; /* set sign */
5095 res->digits=decGetDigits(acc, accunits); /* count digits exactly */
5097 /* There can be a 31-bit wrap in calculating the exponent. */
5098 /* This can only happen if both input exponents are negative and */
5099 /* both their magnitudes are large. If there was a wrap, set a */
5100 /* safe very negative exponent, from which decFinalize() will */
5101 /* raise a hard underflow shortly. */
5102 exponent=lhs->exponent+rhs->exponent; /* calculate exponent */
5103 if (lhs->exponent<0 && rhs->exponent<0 && exponent>0)
5104 exponent=-2*DECNUMMAXE; /* force underflow */
5105 res->exponent=exponent; /* OK to overwrite now */
5108 /* Set the coefficient. If any rounding, residue records */
5109 decSetCoeff(res, set, acc, res->digits, &residue, status);
5110 decFinish(res, set, &residue, status); /* final cleanup */
5111 } while(0); /* end protected */
5113 if (allocacc!=NULL) free(allocacc); /* drop any storage used */
5114 #if DECSUBSET
5115 if (allocrhs!=NULL) free(allocrhs); /* .. */
5116 if (alloclhs!=NULL) free(alloclhs); /* .. */
5117 #endif
5118 #if FASTMUL
5119 if (allocrhi!=NULL) free(allocrhi); /* .. */
5120 if (alloclhi!=NULL) free(alloclhi); /* .. */
5121 #endif
5122 return res;
5123 } /* decMultiplyOp */
5125 /* ------------------------------------------------------------------ */
5126 /* decExpOp -- effect exponentiation */
5127 /* */
5128 /* This computes C = exp(A) */
5129 /* */
5130 /* res is C, the result. C may be A */
5131 /* rhs is A */
5132 /* set is the context; note that rounding mode has no effect */
5133 /* */
5134 /* C must have space for set->digits digits. status is updated but */
5135 /* not set. */
5136 /* */
5137 /* Restrictions: */
5138 /* */
5139 /* digits, emax, and -emin in the context must be less than */
5140 /* 2*DEC_MAX_MATH (1999998), and the rhs must be within these */
5141 /* bounds or a zero. This is an internal routine, so these */
5142 /* restrictions are contractual and not enforced. */
5143 /* */
5144 /* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will */
5145 /* almost always be correctly rounded, but may be up to 1 ulp in */
5146 /* error in rare cases. */
5147 /* */
5148 /* Finite results will always be full precision and Inexact, except */
5149 /* when A is a zero or -Infinity (giving 1 or 0 respectively). */
5150 /* ------------------------------------------------------------------ */
5151 /* This approach used here is similar to the algorithm described in */
5152 /* */
5153 /* Variable Precision Exponential Function, T. E. Hull and */
5154 /* A. Abrham, ACM Transactions on Mathematical Software, Vol 12 #2, */
5155 /* pp79-91, ACM, June 1986. */
5156 /* */
5157 /* with the main difference being that the iterations in the series */
5158 /* evaluation are terminated dynamically (which does not require the */
5159 /* extra variable-precision variables which are expensive in this */
5160 /* context). */
5161 /* */
5162 /* The error analysis in Hull & Abrham's paper applies except for the */
5163 /* round-off error accumulation during the series evaluation. This */
5164 /* code does not precalculate the number of iterations and so cannot */
5165 /* use Horner's scheme. Instead, the accumulation is done at double- */
5166 /* precision, which ensures that the additions of the terms are exact */
5167 /* and do not accumulate round-off (and any round-off errors in the */
5168 /* terms themselves move 'to the right' faster than they can */
5169 /* accumulate). This code also extends the calculation by allowing, */
5170 /* in the spirit of other decNumber operators, the input to be more */
5171 /* precise than the result (the precision used is based on the more */
5172 /* precise of the input or requested result). */
5173 /* */
5174 /* Implementation notes: */
5175 /* */
5176 /* 1. This is separated out as decExpOp so it can be called from */
5177 /* other Mathematical functions (notably Ln) with a wider range */
5178 /* than normal. In particular, it can handle the slightly wider */
5179 /* (double) range needed by Ln (which has to be able to calculate */
5180 /* exp(-x) where x can be the tiniest number (Ntiny). */
5181 /* */
5182 /* 2. Normalizing x to be <=0.1 (instead of <=1) reduces loop */
5183 /* iterations by appoximately a third with additional (although */
5184 /* diminishing) returns as the range is reduced to even smaller */
5185 /* fractions. However, h (the power of 10 used to correct the */
5186 /* result at the end, see below) must be kept <=8 as otherwise */
5187 /* the final result cannot be computed. Hence the leverage is a */
5188 /* sliding value (8-h), where potentially the range is reduced */
5189 /* more for smaller values. */
5190 /* */
5191 /* The leverage that can be applied in this way is severely */
5192 /* limited by the cost of the raise-to-the power at the end, */
5193 /* which dominates when the number of iterations is small (less */
5194 /* than ten) or when rhs is short. As an example, the adjustment */
5195 /* x**10,000,000 needs 31 multiplications, all but one full-width. */
5196 /* */
5197 /* 3. The restrictions (especially precision) could be raised with */
5198 /* care, but the full decNumber range seems very hard within the */
5199 /* 32-bit limits. */
5200 /* */
5201 /* 4. The working precisions for the static buffers are twice the */
5202 /* obvious size to allow for calls from decNumberPower. */
5203 /* ------------------------------------------------------------------ */
5204 decNumber * decExpOp(decNumber *res, const decNumber *rhs,
5205 decContext *set, uInt *status) {
5206 uInt ignore=0; /* working status */
5207 Int h; /* adjusted exponent for 0.xxxx */
5208 Int p; /* working precision */
5209 Int residue; /* rounding residue */
5210 uInt needbytes; /* for space calculations */
5211 const decNumber *x=rhs; /* (may point to safe copy later) */
5212 decContext aset, tset, dset; /* working contexts */
5213 Int comp; /* work */
5215 /* the argument is often copied to normalize it, so (unusually) it */
5216 /* is treated like other buffers, using DECBUFFER, +1 in case */
5217 /* DECBUFFER is 0 */
5218 decNumber bufr[D2N(DECBUFFER*2+1)];
5219 decNumber *allocrhs=NULL; /* non-NULL if rhs buffer allocated */
5221 /* the working precision will be no more than set->digits+8+1 */
5222 /* so for on-stack buffers DECBUFFER+9 is used, +1 in case DECBUFFER */
5223 /* is 0 (and twice that for the accumulator) */
5225 /* buffer for t, term (working precision plus) */
5226 decNumber buft[D2N(DECBUFFER*2+9+1)];
5227 decNumber *allocbuft=NULL; /* -> allocated buft, iff allocated */
5228 decNumber *t=buft; /* term */
5229 /* buffer for a, accumulator (working precision * 2), at least 9 */
5230 decNumber bufa[D2N(DECBUFFER*4+18+1)];
5231 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
5232 decNumber *a=bufa; /* accumulator */
5233 /* decNumber for the divisor term; this needs at most 9 digits */
5234 /* and so can be fixed size [16 so can use standard context] */
5235 decNumber bufd[D2N(16)];
5236 decNumber *d=bufd; /* divisor */
5237 decNumber numone; /* constant 1 */
5239 #if DECCHECK
5240 Int iterations=0; /* for later sanity check */
5241 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
5242 #endif
5244 do { /* protect allocated storage */
5245 if (SPECIALARG) { /* handle infinities and NaNs */
5246 if (decNumberIsInfinite(rhs)) { /* an infinity */
5247 if (decNumberIsNegative(rhs)) /* -Infinity -> +0 */
5248 decNumberZero(res);
5249 else decNumberCopy(res, rhs); /* +Infinity -> self */
5251 else decNaNs(res, rhs, NULL, set, status); /* a NaN */
5252 break;}
5254 if (ISZERO(rhs)) { /* zeros -> exact 1 */
5255 decNumberZero(res); /* make clean 1 */
5256 *res->lsu=1; /* .. */
5257 break;} /* [no status to set] */
5259 /* e**x when 0 < x < 0.66 is < 1+3x/2, hence can fast-path */
5260 /* positive and negative tiny cases which will result in inexact */
5261 /* 1. This also allows the later add-accumulate to always be */
5262 /* exact (because its length will never be more than twice the */
5263 /* working precision). */
5264 /* The comparator (tiny) needs just one digit, so use the */
5265 /* decNumber d for it (reused as the divisor, etc., below); its */
5266 /* exponent is such that if x is positive it will have */
5267 /* set->digits-1 zeros between the decimal point and the digit, */
5268 /* which is 4, and if x is negative one more zero there as the */
5269 /* more precise result will be of the form 0.9999999 rather than */
5270 /* 1.0000001. Hence, tiny will be 0.0000004 if digits=7 and x>0 */
5271 /* or 0.00000004 if digits=7 and x<0. If RHS not larger than */
5272 /* this then the result will be 1.000000 */
5273 decNumberZero(d); /* clean */
5274 *d->lsu=4; /* set 4 .. */
5275 d->exponent=-set->digits; /* * 10**(-d) */
5276 if (decNumberIsNegative(rhs)) d->exponent--; /* negative case */
5277 comp=decCompare(d, rhs, 1); /* signless compare */
5278 if (comp==BADINT) {
5279 *status|=DEC_Insufficient_storage;
5280 break;}
5281 if (comp>=0) { /* rhs < d */
5282 Int shift=set->digits-1;
5283 decNumberZero(res); /* set 1 */
5284 *res->lsu=1; /* .. */
5285 res->digits=decShiftToMost(res->lsu, 1, shift);
5286 res->exponent=-shift; /* make 1.0000... */
5287 *status|=DEC_Inexact | DEC_Rounded; /* .. inexactly */
5288 break;} /* tiny */
5290 /* set up the context to be used for calculating a, as this is */
5291 /* used on both paths below */
5292 decContextDefault(&aset, DEC_INIT_DECIMAL64);
5293 /* accumulator bounds are as requested (could underflow) */
5294 aset.emax=set->emax; /* usual bounds */
5295 aset.emin=set->emin; /* .. */
5296 aset.clamp=0; /* and no concrete format */
5298 /* calculate the adjusted (Hull & Abrham) exponent (where the */
5299 /* decimal point is just to the left of the coefficient msd) */
5300 h=rhs->exponent+rhs->digits;
5301 /* if h>8 then 10**h cannot be calculated safely; however, when */
5302 /* h=8 then exp(|rhs|) will be at least exp(1E+7) which is at */
5303 /* least 6.59E+4342944, so (due to the restriction on Emax/Emin) */
5304 /* overflow (or underflow to 0) is guaranteed -- so this case can */
5305 /* be handled by simply forcing the appropriate excess */
5306 if (h>8) { /* overflow/underflow */
5307 /* set up here so Power call below will over or underflow to */
5308 /* zero; set accumulator to either 2 or 0.02 */
5309 /* [stack buffer for a is always big enough for this] */
5310 decNumberZero(a);
5311 *a->lsu=2; /* not 1 but < exp(1) */
5312 if (decNumberIsNegative(rhs)) a->exponent=-2; /* make 0.02 */
5313 h=8; /* clamp so 10**h computable */
5314 p=9; /* set a working precision */
5316 else { /* h<=8 */
5317 Int maxlever=(rhs->digits>8?1:0);
5318 /* [could/should increase this for precisions >40 or so, too] */
5320 /* if h is 8, cannot normalize to a lower upper limit because */
5321 /* the final result will not be computable (see notes above), */
5322 /* but leverage can be applied whenever h is less than 8. */
5323 /* Apply as much as possible, up to a MAXLEVER digits, which */
5324 /* sets the tradeoff against the cost of the later a**(10**h). */
5325 /* As h is increased, the working precision below also */
5326 /* increases to compensate for the "constant digits at the */
5327 /* front" effect. */
5328 Int lever=MINI(8-h, maxlever); /* leverage attainable */
5329 Int use=-rhs->digits-lever; /* exponent to use for RHS */
5330 h+=lever; /* apply leverage selected */
5331 if (h<0) { /* clamp */
5332 use+=h; /* [may end up subnormal] */
5333 h=0;
5335 /* Take a copy of RHS if it needs normalization (true whenever x>=1) */
5336 if (rhs->exponent!=use) {
5337 decNumber *newrhs=bufr; /* assume will fit on stack */
5338 needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
5339 if (needbytes>sizeof(bufr)) { /* need malloc space */
5340 allocrhs=(decNumber *)malloc(needbytes);
5341 if (allocrhs==NULL) { /* hopeless -- abandon */
5342 *status|=DEC_Insufficient_storage;
5343 break;}
5344 newrhs=allocrhs; /* use the allocated space */
5346 decNumberCopy(newrhs, rhs); /* copy to safe space */
5347 newrhs->exponent=use; /* normalize; now <1 */
5348 x=newrhs; /* ready for use */
5349 /* decNumberShow(x); */
5352 /* Now use the usual power series to evaluate exp(x). The */
5353 /* series starts as 1 + x + x^2/2 ... so prime ready for the */
5354 /* third term by setting the term variable t=x, the accumulator */
5355 /* a=1, and the divisor d=2. */
5357 /* First determine the working precision. From Hull & Abrham */
5358 /* this is set->digits+h+2. However, if x is 'over-precise' we */
5359 /* need to allow for all its digits to potentially participate */
5360 /* (consider an x where all the excess digits are 9s) so in */
5361 /* this case use x->digits+h+2 */
5362 p=MAXI(x->digits, set->digits)+h+2; /* [h<=8] */
5364 /* a and t are variable precision, and depend on p, so space */
5365 /* must be allocated for them if necessary */
5367 /* the accumulator needs to be able to hold 2p digits so that */
5368 /* the additions on the second and subsequent iterations are */
5369 /* sufficiently exact. */
5370 needbytes=sizeof(decNumber)+(D2U(p*2)-1)*sizeof(Unit);
5371 if (needbytes>sizeof(bufa)) { /* need malloc space */
5372 allocbufa=(decNumber *)malloc(needbytes);
5373 if (allocbufa==NULL) { /* hopeless -- abandon */
5374 *status|=DEC_Insufficient_storage;
5375 break;}
5376 a=allocbufa; /* use the allocated space */
5378 /* the term needs to be able to hold p digits (which is */
5379 /* guaranteed to be larger than x->digits, so the initial copy */
5380 /* is safe); it may also be used for the raise-to-power */
5381 /* calculation below, which needs an extra two digits */
5382 needbytes=sizeof(decNumber)+(D2U(p+2)-1)*sizeof(Unit);
5383 if (needbytes>sizeof(buft)) { /* need malloc space */
5384 allocbuft=(decNumber *)malloc(needbytes);
5385 if (allocbuft==NULL) { /* hopeless -- abandon */
5386 *status|=DEC_Insufficient_storage;
5387 break;}
5388 t=allocbuft; /* use the allocated space */
5391 decNumberCopy(t, x); /* term=x */
5392 decNumberZero(a); *a->lsu=1; /* accumulator=1 */
5393 decNumberZero(d); *d->lsu=2; /* divisor=2 */
5394 decNumberZero(&numone); *numone.lsu=1; /* constant 1 for increment */
5396 /* set up the contexts for calculating a, t, and d */
5397 decContextDefault(&tset, DEC_INIT_DECIMAL64);
5398 dset=tset;
5399 /* accumulator bounds are set above, set precision now */
5400 aset.digits=p*2; /* double */
5401 /* term bounds avoid any underflow or overflow */
5402 tset.digits=p;
5403 tset.emin=DEC_MIN_EMIN; /* [emax is plenty] */
5404 /* [dset.digits=16, etc., are sufficient] */
5406 /* finally ready to roll */
5407 for (;;) {
5408 #if DECCHECK
5409 iterations++;
5410 #endif
5411 /* only the status from the accumulation is interesting */
5412 /* [but it should remain unchanged after first add] */
5413 decAddOp(a, a, t, &aset, 0, status); /* a=a+t */
5414 decMultiplyOp(t, t, x, &tset, &ignore); /* t=t*x */
5415 decDivideOp(t, t, d, &tset, DIVIDE, &ignore); /* t=t/d */
5416 /* the iteration ends when the term cannot affect the result, */
5417 /* if rounded to p digits, which is when its value is smaller */
5418 /* than the accumulator by p+1 digits. There must also be */
5419 /* full precision in a. */
5420 if (((a->digits+a->exponent)>=(t->digits+t->exponent+p+1))
5421 && (a->digits>=p)) break;
5422 decAddOp(d, d, &numone, &dset, 0, &ignore); /* d=d+1 */
5423 } /* iterate */
5425 #if DECCHECK
5426 /* just a sanity check; comment out test to show always */
5427 if (iterations>p+3)
5428 printf("Exp iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
5429 iterations, *status, p, x->digits);
5430 #endif
5431 } /* h<=8 */
5433 /* apply postconditioning: a=a**(10**h) -- this is calculated */
5434 /* at a slightly higher precision than Hull & Abrham suggest */
5435 if (h>0) {
5436 Int seenbit=0; /* set once a 1-bit is seen */
5437 Int i; /* counter */
5438 Int n=powers[h]; /* always positive */
5439 aset.digits=p+2; /* sufficient precision */
5440 /* avoid the overhead and many extra digits of decNumberPower */
5441 /* as all that is needed is the short 'multipliers' loop; here */
5442 /* accumulate the answer into t */
5443 decNumberZero(t); *t->lsu=1; /* acc=1 */
5444 for (i=1;;i++){ /* for each bit [top bit ignored] */
5445 /* abandon if have had overflow or terminal underflow */
5446 if (*status & (DEC_Overflow|DEC_Underflow)) { /* interesting? */
5447 if (*status&DEC_Overflow || ISZERO(t)) break;}
5448 n=n<<1; /* move next bit to testable position */
5449 if (n<0) { /* top bit is set */
5450 seenbit=1; /* OK, have a significant bit */
5451 decMultiplyOp(t, t, a, &aset, status); /* acc=acc*x */
5453 if (i==31) break; /* that was the last bit */
5454 if (!seenbit) continue; /* no need to square 1 */
5455 decMultiplyOp(t, t, t, &aset, status); /* acc=acc*acc [square] */
5456 } /*i*/ /* 32 bits */
5457 /* decNumberShow(t); */
5458 a=t; /* and carry on using t instead of a */
5461 /* Copy and round the result to res */
5462 residue=1; /* indicate dirt to right .. */
5463 if (ISZERO(a)) residue=0; /* .. unless underflowed to 0 */
5464 aset.digits=set->digits; /* [use default rounding] */
5465 decCopyFit(res, a, &aset, &residue, status); /* copy & shorten */
5466 decFinish(res, set, &residue, status); /* cleanup/set flags */
5467 } while(0); /* end protected */
5469 if (allocrhs !=NULL) free(allocrhs); /* drop any storage used */
5470 if (allocbufa!=NULL) free(allocbufa); /* .. */
5471 if (allocbuft!=NULL) free(allocbuft); /* .. */
5472 /* [status is handled by caller] */
5473 return res;
5474 } /* decExpOp */
5476 /* ------------------------------------------------------------------ */
5477 /* Initial-estimate natural logarithm table */
5478 /* */
5479 /* LNnn -- 90-entry 16-bit table for values from .10 through .99. */
5480 /* The result is a 4-digit encode of the coefficient (c=the */
5481 /* top 14 bits encoding 0-9999) and a 2-digit encode of the */
5482 /* exponent (e=the bottom 2 bits encoding 0-3) */
5483 /* */
5484 /* The resulting value is given by: */
5485 /* */
5486 /* v = -c * 10**(-e-3) */
5487 /* */
5488 /* where e and c are extracted from entry k = LNnn[x-10] */
5489 /* where x is truncated (NB) into the range 10 through 99, */
5490 /* and then c = k>>2 and e = k&3. */
5491 /* ------------------------------------------------------------------ */
5492 const uShort LNnn[90]={9016, 8652, 8316, 8008, 7724, 7456, 7208,
5493 6972, 6748, 6540, 6340, 6148, 5968, 5792, 5628, 5464, 5312,
5494 5164, 5020, 4884, 4748, 4620, 4496, 4376, 4256, 4144, 4032,
5495 39233, 38181, 37157, 36157, 35181, 34229, 33297, 32389, 31501, 30629,
5496 29777, 28945, 28129, 27329, 26545, 25777, 25021, 24281, 23553, 22837,
5497 22137, 21445, 20769, 20101, 19445, 18801, 18165, 17541, 16925, 16321,
5498 15721, 15133, 14553, 13985, 13421, 12865, 12317, 11777, 11241, 10717,
5499 10197, 9685, 9177, 8677, 8185, 7697, 7213, 6737, 6269, 5801,
5500 5341, 4889, 4437, 39930, 35534, 31186, 26886, 22630, 18418, 14254,
5501 10130, 6046, 20055};
5503 /* ------------------------------------------------------------------ */
5504 /* decLnOp -- effect natural logarithm */
5505 /* */
5506 /* This computes C = ln(A) */
5507 /* */
5508 /* res is C, the result. C may be A */
5509 /* rhs is A */
5510 /* set is the context; note that rounding mode has no effect */
5511 /* */
5512 /* C must have space for set->digits digits. */
5513 /* */
5514 /* Notable cases: */
5515 /* A<0 -> Invalid */
5516 /* A=0 -> -Infinity (Exact) */
5517 /* A=+Infinity -> +Infinity (Exact) */
5518 /* A=1 exactly -> 0 (Exact) */
5519 /* */
5520 /* Restrictions (as for Exp): */
5521 /* */
5522 /* digits, emax, and -emin in the context must be less than */
5523 /* DEC_MAX_MATH+11 (1000010), and the rhs must be within these */
5524 /* bounds or a zero. This is an internal routine, so these */
5525 /* restrictions are contractual and not enforced. */
5526 /* */
5527 /* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will */
5528 /* almost always be correctly rounded, but may be up to 1 ulp in */
5529 /* error in rare cases. */
5530 /* ------------------------------------------------------------------ */
5531 /* The result is calculated using Newton's method, with each */
5532 /* iteration calculating a' = a + x * exp(-a) - 1. See, for example, */
5533 /* Epperson 1989. */
5534 /* */
5535 /* The iteration ends when the adjustment x*exp(-a)-1 is tiny enough. */
5536 /* This has to be calculated at the sum of the precision of x and the */
5537 /* working precision. */
5538 /* */
5539 /* Implementation notes: */
5540 /* */
5541 /* 1. This is separated out as decLnOp so it can be called from */
5542 /* other Mathematical functions (e.g., Log 10) with a wider range */
5543 /* than normal. In particular, it can handle the slightly wider */
5544 /* (+9+2) range needed by a power function. */
5545 /* */
5546 /* 2. The speed of this function is about 10x slower than exp, as */
5547 /* it typically needs 4-6 iterations for short numbers, and the */
5548 /* extra precision needed adds a squaring effect, twice. */
5549 /* */
5550 /* 3. Fastpaths are included for ln(10) and ln(2), up to length 40, */
5551 /* as these are common requests. ln(10) is used by log10(x). */
5552 /* */
5553 /* 4. An iteration might be saved by widening the LNnn table, and */
5554 /* would certainly save at least one if it were made ten times */
5555 /* bigger, too (for truncated fractions 0.100 through 0.999). */
5556 /* However, for most practical evaluations, at least four or five */
5557 /* iterations will be neede -- so this would only speed up by */
5558 /* 20-25% and that probably does not justify increasing the table */
5559 /* size. */
5560 /* */
5561 /* 5. The static buffers are larger than might be expected to allow */
5562 /* for calls from decNumberPower. */
5563 /* ------------------------------------------------------------------ */
5564 decNumber * decLnOp(decNumber *res, const decNumber *rhs,
5565 decContext *set, uInt *status) {
5566 uInt ignore=0; /* working status accumulator */
5567 uInt needbytes; /* for space calculations */
5568 Int residue; /* rounding residue */
5569 Int r; /* rhs=f*10**r [see below] */
5570 Int p; /* working precision */
5571 Int pp; /* precision for iteration */
5572 Int t; /* work */
5574 /* buffers for a (accumulator, typically precision+2) and b */
5575 /* (adjustment calculator, same size) */
5576 decNumber bufa[D2N(DECBUFFER+12)];
5577 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
5578 decNumber *a=bufa; /* accumulator/work */
5579 decNumber bufb[D2N(DECBUFFER*2+2)];
5580 decNumber *allocbufb=NULL; /* -> allocated bufa, iff allocated */
5581 decNumber *b=bufb; /* adjustment/work */
5583 decNumber numone; /* constant 1 */
5584 decNumber cmp; /* work */
5585 decContext aset, bset; /* working contexts */
5587 #if DECCHECK
5588 Int iterations=0; /* for later sanity check */
5589 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
5590 #endif
5592 do { /* protect allocated storage */
5593 if (SPECIALARG) { /* handle infinities and NaNs */
5594 if (decNumberIsInfinite(rhs)) { /* an infinity */
5595 if (decNumberIsNegative(rhs)) /* -Infinity -> error */
5596 *status|=DEC_Invalid_operation;
5597 else decNumberCopy(res, rhs); /* +Infinity -> self */
5599 else decNaNs(res, rhs, NULL, set, status); /* a NaN */
5600 break;}
5602 if (ISZERO(rhs)) { /* +/- zeros -> -Infinity */
5603 decNumberZero(res); /* make clean */
5604 res->bits=DECINF|DECNEG; /* set - infinity */
5605 break;} /* [no status to set] */
5607 /* Non-zero negatives are bad... */
5608 if (decNumberIsNegative(rhs)) { /* -x -> error */
5609 *status|=DEC_Invalid_operation;
5610 break;}
5612 /* Here, rhs is positive, finite, and in range */
5614 /* lookaside fastpath code for ln(2) and ln(10) at common lengths */
5615 if (rhs->exponent==0 && set->digits<=40) {
5616 #if DECDPUN==1
5617 if (rhs->lsu[0]==0 && rhs->lsu[1]==1 && rhs->digits==2) { /* ln(10) */
5618 #else
5619 if (rhs->lsu[0]==10 && rhs->digits==2) { /* ln(10) */
5620 #endif
5621 aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
5622 #define LN10 "2.302585092994045684017991454684364207601"
5623 decNumberFromString(res, LN10, &aset);
5624 *status|=(DEC_Inexact | DEC_Rounded); /* is inexact */
5625 break;}
5626 if (rhs->lsu[0]==2 && rhs->digits==1) { /* ln(2) */
5627 aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
5628 #define LN2 "0.6931471805599453094172321214581765680755"
5629 decNumberFromString(res, LN2, &aset);
5630 *status|=(DEC_Inexact | DEC_Rounded);
5631 break;}
5632 } /* integer and short */
5634 /* Determine the working precision. This is normally the */
5635 /* requested precision + 2, with a minimum of 9. However, if */
5636 /* the rhs is 'over-precise' then allow for all its digits to */
5637 /* potentially participate (consider an rhs where all the excess */
5638 /* digits are 9s) so in this case use rhs->digits+2. */
5639 p=MAXI(rhs->digits, MAXI(set->digits, 7))+2;
5641 /* Allocate space for the accumulator and the high-precision */
5642 /* adjustment calculator, if necessary. The accumulator must */
5643 /* be able to hold p digits, and the adjustment up to */
5644 /* rhs->digits+p digits. They are also made big enough for 16 */
5645 /* digits so that they can be used for calculating the initial */
5646 /* estimate. */
5647 needbytes=sizeof(decNumber)+(D2U(MAXI(p,16))-1)*sizeof(Unit);
5648 if (needbytes>sizeof(bufa)) { /* need malloc space */
5649 allocbufa=(decNumber *)malloc(needbytes);
5650 if (allocbufa==NULL) { /* hopeless -- abandon */
5651 *status|=DEC_Insufficient_storage;
5652 break;}
5653 a=allocbufa; /* use the allocated space */
5655 pp=p+rhs->digits;
5656 needbytes=sizeof(decNumber)+(D2U(MAXI(pp,16))-1)*sizeof(Unit);
5657 if (needbytes>sizeof(bufb)) { /* need malloc space */
5658 allocbufb=(decNumber *)malloc(needbytes);
5659 if (allocbufb==NULL) { /* hopeless -- abandon */
5660 *status|=DEC_Insufficient_storage;
5661 break;}
5662 b=allocbufb; /* use the allocated space */
5665 /* Prepare an initial estimate in acc. Calculate this by */
5666 /* considering the coefficient of x to be a normalized fraction, */
5667 /* f, with the decimal point at far left and multiplied by */
5668 /* 10**r. Then, rhs=f*10**r and 0.1<=f<1, and */
5669 /* ln(x) = ln(f) + ln(10)*r */
5670 /* Get the initial estimate for ln(f) from a small lookup */
5671 /* table (see above) indexed by the first two digits of f, */
5672 /* truncated. */
5674 decContextDefault(&aset, DEC_INIT_DECIMAL64); /* 16-digit extended */
5675 r=rhs->exponent+rhs->digits; /* 'normalised' exponent */
5676 decNumberFromInt32(a, r); /* a=r */
5677 decNumberFromInt32(b, 2302585); /* b=ln(10) (2.302585) */
5678 b->exponent=-6; /* .. */
5679 decMultiplyOp(a, a, b, &aset, &ignore); /* a=a*b */
5680 /* now get top two digits of rhs into b by simple truncate and */
5681 /* force to integer */
5682 residue=0; /* (no residue) */
5683 aset.digits=2; aset.round=DEC_ROUND_DOWN;
5684 decCopyFit(b, rhs, &aset, &residue, &ignore); /* copy & shorten */
5685 b->exponent=0; /* make integer */
5686 t=decGetInt(b); /* [cannot fail] */
5687 if (t<10) t=X10(t); /* adjust single-digit b */
5688 t=LNnn[t-10]; /* look up ln(b) */
5689 decNumberFromInt32(b, t>>2); /* b=ln(b) coefficient */
5690 b->exponent=-(t&3)-3; /* set exponent */
5691 b->bits=DECNEG; /* ln(0.10)->ln(0.99) always -ve */
5692 aset.digits=16; aset.round=DEC_ROUND_HALF_EVEN; /* restore */
5693 decAddOp(a, a, b, &aset, 0, &ignore); /* acc=a+b */
5694 /* the initial estimate is now in a, with up to 4 digits correct. */
5695 /* When rhs is at or near Nmax the estimate will be low, so we */
5696 /* will approach it from below, avoiding overflow when calling exp. */
5698 decNumberZero(&numone); *numone.lsu=1; /* constant 1 for adjustment */
5700 /* accumulator bounds are as requested (could underflow, but */
5701 /* cannot overflow) */
5702 aset.emax=set->emax;
5703 aset.emin=set->emin;
5704 aset.clamp=0; /* no concrete format */
5705 /* set up a context to be used for the multiply and subtract */
5706 bset=aset;
5707 bset.emax=DEC_MAX_MATH*2; /* use double bounds for the */
5708 bset.emin=-DEC_MAX_MATH*2; /* adjustment calculation */
5709 /* [see decExpOp call below] */
5710 /* for each iteration double the number of digits to calculate, */
5711 /* up to a maximum of p */
5712 pp=9; /* initial precision */
5713 /* [initially 9 as then the sequence starts 7+2, 16+2, and */
5714 /* 34+2, which is ideal for standard-sized numbers] */
5715 aset.digits=pp; /* working context */
5716 bset.digits=pp+rhs->digits; /* wider context */
5717 for (;;) { /* iterate */
5718 #if DECCHECK
5719 iterations++;
5720 if (iterations>24) break; /* consider 9 * 2**24 */
5721 #endif
5722 /* calculate the adjustment (exp(-a)*x-1) into b. This is a */
5723 /* catastrophic subtraction but it really is the difference */
5724 /* from 1 that is of interest. */
5725 /* Use the internal entry point to Exp as it allows the double */
5726 /* range for calculating exp(-a) when a is the tiniest subnormal. */
5727 a->bits^=DECNEG; /* make -a */
5728 decExpOp(b, a, &bset, &ignore); /* b=exp(-a) */
5729 a->bits^=DECNEG; /* restore sign of a */
5730 /* now multiply by rhs and subtract 1, at the wider precision */
5731 decMultiplyOp(b, b, rhs, &bset, &ignore); /* b=b*rhs */
5732 decAddOp(b, b, &numone, &bset, DECNEG, &ignore); /* b=b-1 */
5734 /* the iteration ends when the adjustment cannot affect the */
5735 /* result by >=0.5 ulp (at the requested digits), which */
5736 /* is when its value is smaller than the accumulator by */
5737 /* set->digits+1 digits (or it is zero) -- this is a looser */
5738 /* requirement than for Exp because all that happens to the */
5739 /* accumulator after this is the final rounding (but note that */
5740 /* there must also be full precision in a, or a=0). */
5742 if (decNumberIsZero(b) ||
5743 (a->digits+a->exponent)>=(b->digits+b->exponent+set->digits+1)) {
5744 if (a->digits==p) break;
5745 if (decNumberIsZero(a)) {
5746 decCompareOp(&cmp, rhs, &numone, &aset, COMPARE, &ignore); /* rhs=1 ? */
5747 if (cmp.lsu[0]==0) a->exponent=0; /* yes, exact 0 */
5748 else *status|=(DEC_Inexact | DEC_Rounded); /* no, inexact */
5749 break;
5751 /* force padding if adjustment has gone to 0 before full length */
5752 if (decNumberIsZero(b)) b->exponent=a->exponent-p;
5755 /* not done yet ... */
5756 decAddOp(a, a, b, &aset, 0, &ignore); /* a=a+b for next estimate */
5757 if (pp==p) continue; /* precision is at maximum */
5758 /* lengthen the next calculation */
5759 pp=pp*2; /* double precision */
5760 if (pp>p) pp=p; /* clamp to maximum */
5761 aset.digits=pp; /* working context */
5762 bset.digits=pp+rhs->digits; /* wider context */
5763 } /* Newton's iteration */
5765 #if DECCHECK
5766 /* just a sanity check; remove the test to show always */
5767 if (iterations>24)
5768 printf("Ln iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
5769 iterations, *status, p, rhs->digits);
5770 #endif
5772 /* Copy and round the result to res */
5773 residue=1; /* indicate dirt to right */
5774 if (ISZERO(a)) residue=0; /* .. unless underflowed to 0 */
5775 aset.digits=set->digits; /* [use default rounding] */
5776 decCopyFit(res, a, &aset, &residue, status); /* copy & shorten */
5777 decFinish(res, set, &residue, status); /* cleanup/set flags */
5778 } while(0); /* end protected */
5780 if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */
5781 if (allocbufb!=NULL) free(allocbufb); /* .. */
5782 /* [status is handled by caller] */
5783 return res;
5784 } /* decLnOp */
5786 /* ------------------------------------------------------------------ */
5787 /* decQuantizeOp -- force exponent to requested value */
5788 /* */
5789 /* This computes C = op(A, B), where op adjusts the coefficient */
5790 /* of C (by rounding or shifting) such that the exponent (-scale) */
5791 /* of C has the value B or matches the exponent of B. */
5792 /* The numerical value of C will equal A, except for the effects of */
5793 /* any rounding that occurred. */
5794 /* */
5795 /* res is C, the result. C may be A or B */
5796 /* lhs is A, the number to adjust */
5797 /* rhs is B, the requested exponent */
5798 /* set is the context */
5799 /* quant is 1 for quantize or 0 for rescale */
5800 /* status is the status accumulator (this can be called without */
5801 /* risk of control loss) */
5802 /* */
5803 /* C must have space for set->digits digits. */
5804 /* */
5805 /* Unless there is an error or the result is infinite, the exponent */
5806 /* after the operation is guaranteed to be that requested. */
5807 /* ------------------------------------------------------------------ */
5808 static decNumber * decQuantizeOp(decNumber *res, const decNumber *lhs,
5809 const decNumber *rhs, decContext *set,
5810 Flag quant, uInt *status) {
5811 #if DECSUBSET
5812 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */
5813 decNumber *allocrhs=NULL; /* .., rhs */
5814 #endif
5815 const decNumber *inrhs=rhs; /* save original rhs */
5816 Int reqdigits=set->digits; /* requested DIGITS */
5817 Int reqexp; /* requested exponent [-scale] */
5818 Int residue=0; /* rounding residue */
5819 Int etiny=set->emin-(reqdigits-1);
5821 #if DECCHECK
5822 if (decCheckOperands(res, lhs, rhs, set)) return res;
5823 #endif
5825 do { /* protect allocated storage */
5826 #if DECSUBSET
5827 if (!set->extended) {
5828 /* reduce operands and set lostDigits status, as needed */
5829 if (lhs->digits>reqdigits) {
5830 alloclhs=decRoundOperand(lhs, set, status);
5831 if (alloclhs==NULL) break;
5832 lhs=alloclhs;
5834 if (rhs->digits>reqdigits) { /* [this only checks lostDigits] */
5835 allocrhs=decRoundOperand(rhs, set, status);
5836 if (allocrhs==NULL) break;
5837 rhs=allocrhs;
5840 #endif
5841 /* [following code does not require input rounding] */
5843 /* Handle special values */
5844 if (SPECIALARGS) {
5845 /* NaNs get usual processing */
5846 if (SPECIALARGS & (DECSNAN | DECNAN))
5847 decNaNs(res, lhs, rhs, set, status);
5848 /* one infinity but not both is bad */
5849 else if ((lhs->bits ^ rhs->bits) & DECINF)
5850 *status|=DEC_Invalid_operation;
5851 /* both infinity: return lhs */
5852 else decNumberCopy(res, lhs); /* [nop if in place] */
5853 break;
5856 /* set requested exponent */
5857 if (quant) reqexp=inrhs->exponent; /* quantize -- match exponents */
5858 else { /* rescale -- use value of rhs */
5859 /* Original rhs must be an integer that fits and is in range, */
5860 /* which could be from -1999999997 to +999999999, thanks to */
5861 /* subnormals */
5862 reqexp=decGetInt(inrhs); /* [cannot fail] */
5865 #if DECSUBSET
5866 if (!set->extended) etiny=set->emin; /* no subnormals */
5867 #endif
5869 if (reqexp==BADINT /* bad (rescale only) or .. */
5870 || reqexp==BIGODD || reqexp==BIGEVEN /* very big (ditto) or .. */
5871 || (reqexp<etiny) /* < lowest */
5872 || (reqexp>set->emax)) { /* > emax */
5873 *status|=DEC_Invalid_operation;
5874 break;}
5876 /* the RHS has been processed, so it can be overwritten now if necessary */
5877 if (ISZERO(lhs)) { /* zero coefficient unchanged */
5878 decNumberCopy(res, lhs); /* [nop if in place] */
5879 res->exponent=reqexp; /* .. just set exponent */
5880 #if DECSUBSET
5881 if (!set->extended) res->bits=0; /* subset specification; no -0 */
5882 #endif
5884 else { /* non-zero lhs */
5885 Int adjust=reqexp-lhs->exponent; /* digit adjustment needed */
5886 /* if adjusted coefficient will definitely not fit, give up now */
5887 if ((lhs->digits-adjust)>reqdigits) {
5888 *status|=DEC_Invalid_operation;
5889 break;
5892 if (adjust>0) { /* increasing exponent */
5893 /* this will decrease the length of the coefficient by adjust */
5894 /* digits, and must round as it does so */
5895 decContext workset; /* work */
5896 workset=*set; /* clone rounding, etc. */
5897 workset.digits=lhs->digits-adjust; /* set requested length */
5898 /* [note that the latter can be <1, here] */
5899 decCopyFit(res, lhs, &workset, &residue, status); /* fit to result */
5900 decApplyRound(res, &workset, residue, status); /* .. and round */
5901 residue=0; /* [used] */
5902 /* If just rounded a 999s case, exponent will be off by one; */
5903 /* adjust back (after checking space), if so. */
5904 if (res->exponent>reqexp) {
5905 /* re-check needed, e.g., for quantize(0.9999, 0.001) under */
5906 /* set->digits==3 */
5907 if (res->digits==reqdigits) { /* cannot shift by 1 */
5908 *status&=~(DEC_Inexact | DEC_Rounded); /* [clean these] */
5909 *status|=DEC_Invalid_operation;
5910 break;
5912 res->digits=decShiftToMost(res->lsu, res->digits, 1); /* shift */
5913 res->exponent--; /* (re)adjust the exponent. */
5915 #if DECSUBSET
5916 if (ISZERO(res) && !set->extended) res->bits=0; /* subset; no -0 */
5917 #endif
5918 } /* increase */
5919 else /* adjust<=0 */ { /* decreasing or = exponent */
5920 /* this will increase the length of the coefficient by -adjust */
5921 /* digits, by adding zero or more trailing zeros; this is */
5922 /* already checked for fit, above */
5923 decNumberCopy(res, lhs); /* [it will fit] */
5924 /* if padding needed (adjust<0), add it now... */
5925 if (adjust<0) {
5926 res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
5927 res->exponent+=adjust; /* adjust the exponent */
5929 } /* decrease */
5930 } /* non-zero */
5932 /* Check for overflow [do not use Finalize in this case, as an */
5933 /* overflow here is a "don't fit" situation] */
5934 if (res->exponent>set->emax-res->digits+1) { /* too big */
5935 *status|=DEC_Invalid_operation;
5936 break;
5938 else {
5939 decFinalize(res, set, &residue, status); /* set subnormal flags */
5940 *status&=~DEC_Underflow; /* suppress Underflow [754r] */
5942 } while(0); /* end protected */
5944 #if DECSUBSET
5945 if (allocrhs!=NULL) free(allocrhs); /* drop any storage used */
5946 if (alloclhs!=NULL) free(alloclhs); /* .. */
5947 #endif
5948 return res;
5949 } /* decQuantizeOp */
5951 /* ------------------------------------------------------------------ */
5952 /* decCompareOp -- compare, min, or max two Numbers */
5953 /* */
5954 /* This computes C = A ? B and carries out one of four operations: */
5955 /* COMPARE -- returns the signum (as a number) giving the */
5956 /* result of a comparison unless one or both */
5957 /* operands is a NaN (in which case a NaN results) */
5958 /* COMPSIG -- as COMPARE except that a quiet NaN raises */
5959 /* Invalid operation. */
5960 /* COMPMAX -- returns the larger of the operands, using the */
5961 /* 754r maxnum operation */
5962 /* COMPMAXMAG -- ditto, comparing absolute values */
5963 /* COMPMIN -- the 754r minnum operation */
5964 /* COMPMINMAG -- ditto, comparing absolute values */
5965 /* COMTOTAL -- returns the signum (as a number) giving the */
5966 /* result of a comparison using 754r total ordering */
5967 /* */
5968 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
5969 /* lhs is A */
5970 /* rhs is B */
5971 /* set is the context */
5972 /* op is the operation flag */
5973 /* status is the usual accumulator */
5974 /* */
5975 /* C must have space for one digit for COMPARE or set->digits for */
5976 /* COMPMAX, COMPMIN, COMPMAXMAG, or COMPMINMAG. */
5977 /* ------------------------------------------------------------------ */
5978 /* The emphasis here is on speed for common cases, and avoiding */
5979 /* coefficient comparison if possible. */
5980 /* ------------------------------------------------------------------ */
5981 decNumber * decCompareOp(decNumber *res, const decNumber *lhs,
5982 const decNumber *rhs, decContext *set,
5983 Flag op, uInt *status) {
5984 #if DECSUBSET
5985 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */
5986 decNumber *allocrhs=NULL; /* .., rhs */
5987 #endif
5988 Int result=0; /* default result value */
5989 uByte merged; /* work */
5991 #if DECCHECK
5992 if (decCheckOperands(res, lhs, rhs, set)) return res;
5993 #endif
5995 do { /* protect allocated storage */
5996 #if DECSUBSET
5997 if (!set->extended) {
5998 /* reduce operands and set lostDigits status, as needed */
5999 if (lhs->digits>set->digits) {
6000 alloclhs=decRoundOperand(lhs, set, status);
6001 if (alloclhs==NULL) {result=BADINT; break;}
6002 lhs=alloclhs;
6004 if (rhs->digits>set->digits) {
6005 allocrhs=decRoundOperand(rhs, set, status);
6006 if (allocrhs==NULL) {result=BADINT; break;}
6007 rhs=allocrhs;
6010 #endif
6011 /* [following code does not require input rounding] */
6013 /* If total ordering then handle differing signs 'up front' */
6014 if (op==COMPTOTAL) { /* total ordering */
6015 if (decNumberIsNegative(lhs) & !decNumberIsNegative(rhs)) {
6016 result=-1;
6017 break;
6019 if (!decNumberIsNegative(lhs) & decNumberIsNegative(rhs)) {
6020 result=+1;
6021 break;
6025 /* handle NaNs specially; let infinities drop through */
6026 /* This assumes sNaN (even just one) leads to NaN. */
6027 merged=(lhs->bits | rhs->bits) & (DECSNAN | DECNAN);
6028 if (merged) { /* a NaN bit set */
6029 if (op==COMPARE); /* result will be NaN */
6030 else if (op==COMPSIG) /* treat qNaN as sNaN */
6031 *status|=DEC_Invalid_operation | DEC_sNaN;
6032 else if (op==COMPTOTAL) { /* total ordering, always finite */
6033 /* signs are known to be the same; compute the ordering here */
6034 /* as if the signs are both positive, then invert for negatives */
6035 if (!decNumberIsNaN(lhs)) result=-1;
6036 else if (!decNumberIsNaN(rhs)) result=+1;
6037 /* here if both NaNs */
6038 else if (decNumberIsSNaN(lhs) && decNumberIsQNaN(rhs)) result=-1;
6039 else if (decNumberIsQNaN(lhs) && decNumberIsSNaN(rhs)) result=+1;
6040 else { /* both NaN or both sNaN */
6041 /* now it just depends on the payload */
6042 result=decUnitCompare(lhs->lsu, D2U(lhs->digits),
6043 rhs->lsu, D2U(rhs->digits), 0);
6044 /* [Error not possible, as these are 'aligned'] */
6045 } /* both same NaNs */
6046 if (decNumberIsNegative(lhs)) result=-result;
6047 break;
6048 } /* total order */
6050 else if (merged & DECSNAN); /* sNaN -> qNaN */
6051 else { /* here if MIN or MAX and one or two quiet NaNs */
6052 /* min or max -- 754r rules ignore single NaN */
6053 if (!decNumberIsNaN(lhs) || !decNumberIsNaN(rhs)) {
6054 /* just one NaN; force choice to be the non-NaN operand */
6055 op=COMPMAX;
6056 if (lhs->bits & DECNAN) result=-1; /* pick rhs */
6057 else result=+1; /* pick lhs */
6058 break;
6060 } /* max or min */
6061 op=COMPNAN; /* use special path */
6062 decNaNs(res, lhs, rhs, set, status); /* propagate NaN */
6063 break;
6065 /* have numbers */
6066 if (op==COMPMAXMAG || op==COMPMINMAG) result=decCompare(lhs, rhs, 1);
6067 else result=decCompare(lhs, rhs, 0); /* sign matters */
6068 } while(0); /* end protected */
6070 if (result==BADINT) *status|=DEC_Insufficient_storage; /* rare */
6071 else {
6072 if (op==COMPARE || op==COMPSIG ||op==COMPTOTAL) { /* returning signum */
6073 if (op==COMPTOTAL && result==0) {
6074 /* operands are numerically equal or same NaN (and same sign, */
6075 /* tested first); if identical, leave result 0 */
6076 if (lhs->exponent!=rhs->exponent) {
6077 if (lhs->exponent<rhs->exponent) result=-1;
6078 else result=+1;
6079 if (decNumberIsNegative(lhs)) result=-result;
6080 } /* lexp!=rexp */
6081 } /* total-order by exponent */
6082 decNumberZero(res); /* [always a valid result] */
6083 if (result!=0) { /* must be -1 or +1 */
6084 *res->lsu=1;
6085 if (result<0) res->bits=DECNEG;
6088 else if (op==COMPNAN); /* special, drop through */
6089 else { /* MAX or MIN, non-NaN result */
6090 Int residue=0; /* rounding accumulator */
6091 /* choose the operand for the result */
6092 const decNumber *choice;
6093 if (result==0) { /* operands are numerically equal */
6094 /* choose according to sign then exponent (see 754r) */
6095 uByte slhs=(lhs->bits & DECNEG);
6096 uByte srhs=(rhs->bits & DECNEG);
6097 #if DECSUBSET
6098 if (!set->extended) { /* subset: force left-hand */
6099 op=COMPMAX;
6100 result=+1;
6102 else
6103 #endif
6104 if (slhs!=srhs) { /* signs differ */
6105 if (slhs) result=-1; /* rhs is max */
6106 else result=+1; /* lhs is max */
6108 else if (slhs && srhs) { /* both negative */
6109 if (lhs->exponent<rhs->exponent) result=+1;
6110 else result=-1;
6111 /* [if equal, use lhs, technically identical] */
6113 else { /* both positive */
6114 if (lhs->exponent>rhs->exponent) result=+1;
6115 else result=-1;
6116 /* [ditto] */
6118 } /* numerically equal */
6119 /* here result will be non-0; reverse if looking for MIN */
6120 if (op==COMPMIN || op==COMPMINMAG) result=-result;
6121 choice=(result>0 ? lhs : rhs); /* choose */
6122 /* copy chosen to result, rounding if need be */
6123 decCopyFit(res, choice, set, &residue, status);
6124 decFinish(res, set, &residue, status);
6127 #if DECSUBSET
6128 if (allocrhs!=NULL) free(allocrhs); /* free any storage used */
6129 if (alloclhs!=NULL) free(alloclhs); /* .. */
6130 #endif
6131 return res;
6132 } /* decCompareOp */
6134 /* ------------------------------------------------------------------ */
6135 /* decCompare -- compare two decNumbers by numerical value */
6136 /* */
6137 /* This routine compares A ? B without altering them. */
6138 /* */
6139 /* Arg1 is A, a decNumber which is not a NaN */
6140 /* Arg2 is B, a decNumber which is not a NaN */
6141 /* Arg3 is 1 for a sign-independent compare, 0 otherwise */
6142 /* */
6143 /* returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure */
6144 /* (the only possible failure is an allocation error) */
6145 /* ------------------------------------------------------------------ */
6146 static Int decCompare(const decNumber *lhs, const decNumber *rhs,
6147 Flag abs) {
6148 Int result; /* result value */
6149 Int sigr; /* rhs signum */
6150 Int compare; /* work */
6152 result=1; /* assume signum(lhs) */
6153 if (ISZERO(lhs)) result=0;
6154 if (abs) {
6155 if (ISZERO(rhs)) return result; /* LHS wins or both 0 */
6156 /* RHS is non-zero */
6157 if (result==0) return -1; /* LHS is 0; RHS wins */
6158 /* [here, both non-zero, result=1] */
6160 else { /* signs matter */
6161 if (result && decNumberIsNegative(lhs)) result=-1;
6162 sigr=1; /* compute signum(rhs) */
6163 if (ISZERO(rhs)) sigr=0;
6164 else if (decNumberIsNegative(rhs)) sigr=-1;
6165 if (result > sigr) return +1; /* L > R, return 1 */
6166 if (result < sigr) return -1; /* L < R, return -1 */
6167 if (result==0) return 0; /* both 0 */
6170 /* signums are the same; both are non-zero */
6171 if ((lhs->bits | rhs->bits) & DECINF) { /* one or more infinities */
6172 if (decNumberIsInfinite(rhs)) {
6173 if (decNumberIsInfinite(lhs)) result=0;/* both infinite */
6174 else result=-result; /* only rhs infinite */
6176 return result;
6178 /* must compare the coefficients, allowing for exponents */
6179 if (lhs->exponent>rhs->exponent) { /* LHS exponent larger */
6180 /* swap sides, and sign */
6181 const decNumber *temp=lhs;
6182 lhs=rhs;
6183 rhs=temp;
6184 result=-result;
6186 compare=decUnitCompare(lhs->lsu, D2U(lhs->digits),
6187 rhs->lsu, D2U(rhs->digits),
6188 rhs->exponent-lhs->exponent);
6189 if (compare!=BADINT) compare*=result; /* comparison succeeded */
6190 return compare;
6191 } /* decCompare */
6193 /* ------------------------------------------------------------------ */
6194 /* decUnitCompare -- compare two >=0 integers in Unit arrays */
6195 /* */
6196 /* This routine compares A ? B*10**E where A and B are unit arrays */
6197 /* A is a plain integer */
6198 /* B has an exponent of E (which must be non-negative) */
6199 /* */
6200 /* Arg1 is A first Unit (lsu) */
6201 /* Arg2 is A length in Units */
6202 /* Arg3 is B first Unit (lsu) */
6203 /* Arg4 is B length in Units */
6204 /* Arg5 is E (0 if the units are aligned) */
6205 /* */
6206 /* returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure */
6207 /* (the only possible failure is an allocation error, which can */
6208 /* only occur if E!=0) */
6209 /* ------------------------------------------------------------------ */
6210 static Int decUnitCompare(const Unit *a, Int alength,
6211 const Unit *b, Int blength, Int exp) {
6212 Unit *acc; /* accumulator for result */
6213 Unit accbuff[SD2U(DECBUFFER*2+1)]; /* local buffer */
6214 Unit *allocacc=NULL; /* -> allocated acc buffer, iff allocated */
6215 Int accunits, need; /* units in use or needed for acc */
6216 const Unit *l, *r, *u; /* work */
6217 Int expunits, exprem, result; /* .. */
6219 if (exp==0) { /* aligned; fastpath */
6220 if (alength>blength) return 1;
6221 if (alength<blength) return -1;
6222 /* same number of units in both -- need unit-by-unit compare */
6223 l=a+alength-1;
6224 r=b+alength-1;
6225 for (;l>=a; l--, r--) {
6226 if (*l>*r) return 1;
6227 if (*l<*r) return -1;
6229 return 0; /* all units match */
6230 } /* aligned */
6232 /* Unaligned. If one is >1 unit longer than the other, padded */
6233 /* approximately, then can return easily */
6234 if (alength>blength+(Int)D2U(exp)) return 1;
6235 if (alength+1<blength+(Int)D2U(exp)) return -1;
6237 /* Need to do a real subtract. For this, a result buffer is needed */
6238 /* even though only the sign is of interest. Its length needs */
6239 /* to be the larger of alength and padded blength, +2 */
6240 need=blength+D2U(exp); /* maximum real length of B */
6241 if (need<alength) need=alength;
6242 need+=2;
6243 acc=accbuff; /* assume use local buffer */
6244 if (need*sizeof(Unit)>sizeof(accbuff)) {
6245 allocacc=(Unit *)malloc(need*sizeof(Unit));
6246 if (allocacc==NULL) return BADINT; /* hopeless -- abandon */
6247 acc=allocacc;
6249 /* Calculate units and remainder from exponent. */
6250 expunits=exp/DECDPUN;
6251 exprem=exp%DECDPUN;
6252 /* subtract [A+B*(-m)] */
6253 accunits=decUnitAddSub(a, alength, b, blength, expunits, acc,
6254 -(Int)powers[exprem]);
6255 /* [UnitAddSub result may have leading zeros, even on zero] */
6256 if (accunits<0) result=-1; /* negative result */
6257 else { /* non-negative result */
6258 /* check units of the result before freeing any storage */
6259 for (u=acc; u<acc+accunits-1 && *u==0;) u++;
6260 result=(*u==0 ? 0 : +1);
6262 /* clean up and return the result */
6263 if (allocacc!=NULL) free(allocacc); /* drop any storage used */
6264 return result;
6265 } /* decUnitCompare */
6267 /* ------------------------------------------------------------------ */
6268 /* decUnitAddSub -- add or subtract two >=0 integers in Unit arrays */
6269 /* */
6270 /* This routine performs the calculation: */
6271 /* */
6272 /* C=A+(B*M) */
6273 /* */
6274 /* Where M is in the range -DECDPUNMAX through +DECDPUNMAX. */
6275 /* */
6276 /* A may be shorter or longer than B. */
6277 /* */
6278 /* Leading zeros are not removed after a calculation. The result is */
6279 /* either the same length as the longer of A and B (adding any */
6280 /* shift), or one Unit longer than that (if a Unit carry occurred). */
6281 /* */
6282 /* A and B content are not altered unless C is also A or B. */
6283 /* C may be the same array as A or B, but only if no zero padding is */
6284 /* requested (that is, C may be B only if bshift==0). */
6285 /* C is filled from the lsu; only those units necessary to complete */
6286 /* the calculation are referenced. */
6287 /* */
6288 /* Arg1 is A first Unit (lsu) */
6289 /* Arg2 is A length in Units */
6290 /* Arg3 is B first Unit (lsu) */
6291 /* Arg4 is B length in Units */
6292 /* Arg5 is B shift in Units (>=0; pads with 0 units if positive) */
6293 /* Arg6 is C first Unit (lsu) */
6294 /* Arg7 is M, the multiplier */
6295 /* */
6296 /* returns the count of Units written to C, which will be non-zero */
6297 /* and negated if the result is negative. That is, the sign of the */
6298 /* returned Int is the sign of the result (positive for zero) and */
6299 /* the absolute value of the Int is the count of Units. */
6300 /* */
6301 /* It is the caller's responsibility to make sure that C size is */
6302 /* safe, allowing space if necessary for a one-Unit carry. */
6303 /* */
6304 /* This routine is severely performance-critical; *any* change here */
6305 /* must be measured (timed) to assure no performance degradation. */
6306 /* In particular, trickery here tends to be counter-productive, as */
6307 /* increased complexity of code hurts register optimizations on */
6308 /* register-poor architectures. Avoiding divisions is nearly */
6309 /* always a Good Idea, however. */
6310 /* */
6311 /* Special thanks to Rick McGuire (IBM Cambridge, MA) and Dave Clark */
6312 /* (IBM Warwick, UK) for some of the ideas used in this routine. */
6313 /* ------------------------------------------------------------------ */
6314 static Int decUnitAddSub(const Unit *a, Int alength,
6315 const Unit *b, Int blength, Int bshift,
6316 Unit *c, Int m) {
6317 const Unit *alsu=a; /* A lsu [need to remember it] */
6318 Unit *clsu=c; /* C ditto */
6319 Unit *minC; /* low water mark for C */
6320 Unit *maxC; /* high water mark for C */
6321 eInt carry=0; /* carry integer (could be Long) */
6322 Int add; /* work */
6323 #if DECDPUN<=4 /* myriadal, millenary, etc. */
6324 Int est; /* estimated quotient */
6325 #endif
6327 #if DECTRACE
6328 if (alength<1 || blength<1)
6329 printf("decUnitAddSub: alen blen m %ld %ld [%ld]\n", alength, blength, m);
6330 #endif
6332 maxC=c+alength; /* A is usually the longer */
6333 minC=c+blength; /* .. and B the shorter */
6334 if (bshift!=0) { /* B is shifted; low As copy across */
6335 minC+=bshift;
6336 /* if in place [common], skip copy unless there's a gap [rare] */
6337 if (a==c && bshift<=alength) {
6338 c+=bshift;
6339 a+=bshift;
6341 else for (; c<clsu+bshift; a++, c++) { /* copy needed */
6342 if (a<alsu+alength) *c=*a;
6343 else *c=0;
6346 if (minC>maxC) { /* swap */
6347 Unit *hold=minC;
6348 minC=maxC;
6349 maxC=hold;
6352 /* For speed, do the addition as two loops; the first where both A */
6353 /* and B contribute, and the second (if necessary) where only one or */
6354 /* other of the numbers contribute. */
6355 /* Carry handling is the same (i.e., duplicated) in each case. */
6356 for (; c<minC; c++) {
6357 carry+=*a;
6358 a++;
6359 carry+=((eInt)*b)*m; /* [special-casing m=1/-1 */
6360 b++; /* here is not a win] */
6361 /* here carry is new Unit of digits; it could be +ve or -ve */
6362 if ((ueInt)carry<=DECDPUNMAX) { /* fastpath 0-DECDPUNMAX */
6363 *c=(Unit)carry;
6364 carry=0;
6365 continue;
6367 #if DECDPUN==4 /* use divide-by-multiply */
6368 if (carry>=0) {
6369 est=(((ueInt)carry>>11)*53687)>>18;
6370 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6371 carry=est; /* likely quotient [89%] */
6372 if (*c<DECDPUNMAX+1) continue; /* estimate was correct */
6373 carry++;
6374 *c-=DECDPUNMAX+1;
6375 continue;
6377 /* negative case */
6378 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6379 est=(((ueInt)carry>>11)*53687)>>18;
6380 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6381 carry=est-(DECDPUNMAX+1); /* correctly negative */
6382 if (*c<DECDPUNMAX+1) continue; /* was OK */
6383 carry++;
6384 *c-=DECDPUNMAX+1;
6385 #elif DECDPUN==3
6386 if (carry>=0) {
6387 est=(((ueInt)carry>>3)*16777)>>21;
6388 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6389 carry=est; /* likely quotient [99%] */
6390 if (*c<DECDPUNMAX+1) continue; /* estimate was correct */
6391 carry++;
6392 *c-=DECDPUNMAX+1;
6393 continue;
6395 /* negative case */
6396 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6397 est=(((ueInt)carry>>3)*16777)>>21;
6398 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6399 carry=est-(DECDPUNMAX+1); /* correctly negative */
6400 if (*c<DECDPUNMAX+1) continue; /* was OK */
6401 carry++;
6402 *c-=DECDPUNMAX+1;
6403 #elif DECDPUN<=2
6404 /* Can use QUOT10 as carry <= 4 digits */
6405 if (carry>=0) {
6406 est=QUOT10(carry, DECDPUN);
6407 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6408 carry=est; /* quotient */
6409 continue;
6411 /* negative case */
6412 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6413 est=QUOT10(carry, DECDPUN);
6414 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6415 carry=est-(DECDPUNMAX+1); /* correctly negative */
6416 #else
6417 /* remainder operator is undefined if negative, so must test */
6418 if ((ueInt)carry<(DECDPUNMAX+1)*2) { /* fastpath carry +1 */
6419 *c=(Unit)(carry-(DECDPUNMAX+1)); /* [helps additions] */
6420 carry=1;
6421 continue;
6423 if (carry>=0) {
6424 *c=(Unit)(carry%(DECDPUNMAX+1));
6425 carry=carry/(DECDPUNMAX+1);
6426 continue;
6428 /* negative case */
6429 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6430 *c=(Unit)(carry%(DECDPUNMAX+1));
6431 carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
6432 #endif
6433 } /* c */
6435 /* now may have one or other to complete */
6436 /* [pretest to avoid loop setup/shutdown] */
6437 if (c<maxC) for (; c<maxC; c++) {
6438 if (a<alsu+alength) { /* still in A */
6439 carry+=*a;
6440 a++;
6442 else { /* inside B */
6443 carry+=((eInt)*b)*m;
6444 b++;
6446 /* here carry is new Unit of digits; it could be +ve or -ve and */
6447 /* magnitude up to DECDPUNMAX squared */
6448 if ((ueInt)carry<=DECDPUNMAX) { /* fastpath 0-DECDPUNMAX */
6449 *c=(Unit)carry;
6450 carry=0;
6451 continue;
6453 /* result for this unit is negative or >DECDPUNMAX */
6454 #if DECDPUN==4 /* use divide-by-multiply */
6455 if (carry>=0) {
6456 est=(((ueInt)carry>>11)*53687)>>18;
6457 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6458 carry=est; /* likely quotient [79.7%] */
6459 if (*c<DECDPUNMAX+1) continue; /* estimate was correct */
6460 carry++;
6461 *c-=DECDPUNMAX+1;
6462 continue;
6464 /* negative case */
6465 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6466 est=(((ueInt)carry>>11)*53687)>>18;
6467 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6468 carry=est-(DECDPUNMAX+1); /* correctly negative */
6469 if (*c<DECDPUNMAX+1) continue; /* was OK */
6470 carry++;
6471 *c-=DECDPUNMAX+1;
6472 #elif DECDPUN==3
6473 if (carry>=0) {
6474 est=(((ueInt)carry>>3)*16777)>>21;
6475 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6476 carry=est; /* likely quotient [99%] */
6477 if (*c<DECDPUNMAX+1) continue; /* estimate was correct */
6478 carry++;
6479 *c-=DECDPUNMAX+1;
6480 continue;
6482 /* negative case */
6483 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6484 est=(((ueInt)carry>>3)*16777)>>21;
6485 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6486 carry=est-(DECDPUNMAX+1); /* correctly negative */
6487 if (*c<DECDPUNMAX+1) continue; /* was OK */
6488 carry++;
6489 *c-=DECDPUNMAX+1;
6490 #elif DECDPUN<=2
6491 if (carry>=0) {
6492 est=QUOT10(carry, DECDPUN);
6493 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6494 carry=est; /* quotient */
6495 continue;
6497 /* negative case */
6498 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6499 est=QUOT10(carry, DECDPUN);
6500 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6501 carry=est-(DECDPUNMAX+1); /* correctly negative */
6502 #else
6503 if ((ueInt)carry<(DECDPUNMAX+1)*2){ /* fastpath carry 1 */
6504 *c=(Unit)(carry-(DECDPUNMAX+1));
6505 carry=1;
6506 continue;
6508 /* remainder operator is undefined if negative, so must test */
6509 if (carry>=0) {
6510 *c=(Unit)(carry%(DECDPUNMAX+1));
6511 carry=carry/(DECDPUNMAX+1);
6512 continue;
6514 /* negative case */
6515 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6516 *c=(Unit)(carry%(DECDPUNMAX+1));
6517 carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
6518 #endif
6519 } /* c */
6521 /* OK, all A and B processed; might still have carry or borrow */
6522 /* return number of Units in the result, negated if a borrow */
6523 if (carry==0) return c-clsu; /* no carry, so no more to do */
6524 if (carry>0) { /* positive carry */
6525 *c=(Unit)carry; /* place as new unit */
6526 c++; /* .. */
6527 return c-clsu;
6529 /* -ve carry: it's a borrow; complement needed */
6530 add=1; /* temporary carry... */
6531 for (c=clsu; c<maxC; c++) {
6532 add=DECDPUNMAX+add-*c;
6533 if (add<=DECDPUNMAX) {
6534 *c=(Unit)add;
6535 add=0;
6537 else {
6538 *c=0;
6539 add=1;
6542 /* add an extra unit iff it would be non-zero */
6543 #if DECTRACE
6544 printf("UAS borrow: add %ld, carry %ld\n", add, carry);
6545 #endif
6546 if ((add-carry-1)!=0) {
6547 *c=(Unit)(add-carry-1);
6548 c++; /* interesting, include it */
6550 return clsu-c; /* -ve result indicates borrowed */
6551 } /* decUnitAddSub */
6553 /* ------------------------------------------------------------------ */
6554 /* decTrim -- trim trailing zeros or normalize */
6555 /* */
6556 /* dn is the number to trim or normalize */
6557 /* set is the context to use to check for clamp */
6558 /* all is 1 to remove all trailing zeros, 0 for just fraction ones */
6559 /* dropped returns the number of discarded trailing zeros */
6560 /* returns dn */
6561 /* */
6562 /* If clamp is set in the context then the number of zeros trimmed */
6563 /* may be limited if the exponent is high. */
6564 /* All fields are updated as required. This is a utility operation, */
6565 /* so special values are unchanged and no error is possible. */
6566 /* ------------------------------------------------------------------ */
6567 static decNumber * decTrim(decNumber *dn, decContext *set, Flag all,
6568 Int *dropped) {
6569 Int d, exp; /* work */
6570 uInt cut; /* .. */
6571 Unit *up; /* -> current Unit */
6573 #if DECCHECK
6574 if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
6575 #endif
6577 *dropped=0; /* assume no zeros dropped */
6578 if ((dn->bits & DECSPECIAL) /* fast exit if special .. */
6579 || (*dn->lsu & 0x01)) return dn; /* .. or odd */
6580 if (ISZERO(dn)) { /* .. or 0 */
6581 dn->exponent=0; /* (sign is preserved) */
6582 return dn;
6585 /* have a finite number which is even */
6586 exp=dn->exponent;
6587 cut=1; /* digit (1-DECDPUN) in Unit */
6588 up=dn->lsu; /* -> current Unit */
6589 for (d=0; d<dn->digits-1; d++) { /* [don't strip the final digit] */
6590 /* slice by powers */
6591 #if DECDPUN<=4
6592 uInt quot=QUOT10(*up, cut);
6593 if ((*up-quot*powers[cut])!=0) break; /* found non-0 digit */
6594 #else
6595 if (*up%powers[cut]!=0) break; /* found non-0 digit */
6596 #endif
6597 /* have a trailing 0 */
6598 if (!all) { /* trimming */
6599 /* [if exp>0 then all trailing 0s are significant for trim] */
6600 if (exp<=0) { /* if digit might be significant */
6601 if (exp==0) break; /* then quit */
6602 exp++; /* next digit might be significant */
6605 cut++; /* next power */
6606 if (cut>DECDPUN) { /* need new Unit */
6607 up++;
6608 cut=1;
6610 } /* d */
6611 if (d==0) return dn; /* none to drop */
6613 /* may need to limit drop if clamping */
6614 if (set->clamp) {
6615 Int maxd=set->emax-set->digits+1-dn->exponent;
6616 if (maxd<=0) return dn; /* nothing possible */
6617 if (d>maxd) d=maxd;
6620 /* effect the drop */
6621 decShiftToLeast(dn->lsu, D2U(dn->digits), d);
6622 dn->exponent+=d; /* maintain numerical value */
6623 dn->digits-=d; /* new length */
6624 *dropped=d; /* report the count */
6625 return dn;
6626 } /* decTrim */
6628 /* ------------------------------------------------------------------ */
6629 /* decReverse -- reverse a Unit array in place */
6630 /* */
6631 /* ulo is the start of the array */
6632 /* uhi is the end of the array (highest Unit to include) */
6633 /* */
6634 /* The units ulo through uhi are reversed in place (if the number */
6635 /* of units is odd, the middle one is untouched). Note that the */
6636 /* digit(s) in each unit are unaffected. */
6637 /* ------------------------------------------------------------------ */
6638 static void decReverse(Unit *ulo, Unit *uhi) {
6639 Unit temp;
6640 for (; ulo<uhi; ulo++, uhi--) {
6641 temp=*ulo;
6642 *ulo=*uhi;
6643 *uhi=temp;
6645 return;
6646 } /* decReverse */
6648 /* ------------------------------------------------------------------ */
6649 /* decShiftToMost -- shift digits in array towards most significant */
6650 /* */
6651 /* uar is the array */
6652 /* digits is the count of digits in use in the array */
6653 /* shift is the number of zeros to pad with (least significant); */
6654 /* it must be zero or positive */
6655 /* */
6656 /* returns the new length of the integer in the array, in digits */
6657 /* */
6658 /* No overflow is permitted (that is, the uar array must be known to */
6659 /* be large enough to hold the result, after shifting). */
6660 /* ------------------------------------------------------------------ */
6661 static Int decShiftToMost(Unit *uar, Int digits, Int shift) {
6662 Unit *target, *source, *first; /* work */
6663 Int cut; /* odd 0's to add */
6664 uInt next; /* work */
6666 if (shift==0) return digits; /* [fastpath] nothing to do */
6667 if ((digits+shift)<=DECDPUN) { /* [fastpath] single-unit case */
6668 *uar=(Unit)(*uar*powers[shift]);
6669 return digits+shift;
6672 next=0; /* all paths */
6673 source=uar+D2U(digits)-1; /* where msu comes from */
6674 target=source+D2U(shift); /* where upper part of first cut goes */
6675 cut=DECDPUN-MSUDIGITS(shift); /* where to slice */
6676 if (cut==0) { /* unit-boundary case */
6677 for (; source>=uar; source--, target--) *target=*source;
6679 else {
6680 first=uar+D2U(digits+shift)-1; /* where msu of source will end up */
6681 for (; source>=uar; source--, target--) {
6682 /* split the source Unit and accumulate remainder for next */
6683 #if DECDPUN<=4
6684 uInt quot=QUOT10(*source, cut);
6685 uInt rem=*source-quot*powers[cut];
6686 next+=quot;
6687 #else
6688 uInt rem=*source%powers[cut];
6689 next+=*source/powers[cut];
6690 #endif
6691 if (target<=first) *target=(Unit)next; /* write to target iff valid */
6692 next=rem*powers[DECDPUN-cut]; /* save remainder for next Unit */
6694 } /* shift-move */
6696 /* propagate any partial unit to one below and clear the rest */
6697 for (; target>=uar; target--) {
6698 *target=(Unit)next;
6699 next=0;
6701 return digits+shift;
6702 } /* decShiftToMost */
6704 /* ------------------------------------------------------------------ */
6705 /* decShiftToLeast -- shift digits in array towards least significant */
6706 /* */
6707 /* uar is the array */
6708 /* units is length of the array, in units */
6709 /* shift is the number of digits to remove from the lsu end; it */
6710 /* must be zero or positive and <= than units*DECDPUN. */
6711 /* */
6712 /* returns the new length of the integer in the array, in units */
6713 /* */
6714 /* Removed digits are discarded (lost). Units not required to hold */
6715 /* the final result are unchanged. */
6716 /* ------------------------------------------------------------------ */
6717 static Int decShiftToLeast(Unit *uar, Int units, Int shift) {
6718 Unit *target, *up; /* work */
6719 Int cut, count; /* work */
6720 Int quot, rem; /* for division */
6722 if (shift==0) return units; /* [fastpath] nothing to do */
6723 if (shift==units*DECDPUN) { /* [fastpath] little to do */
6724 *uar=0; /* all digits cleared gives zero */
6725 return 1; /* leaves just the one */
6728 target=uar; /* both paths */
6729 cut=MSUDIGITS(shift);
6730 if (cut==DECDPUN) { /* unit-boundary case; easy */
6731 up=uar+D2U(shift);
6732 for (; up<uar+units; target++, up++) *target=*up;
6733 return target-uar;
6736 /* messier */
6737 up=uar+D2U(shift-cut); /* source; correct to whole Units */
6738 count=units*DECDPUN-shift; /* the maximum new length */
6739 #if DECDPUN<=4
6740 quot=QUOT10(*up, cut);
6741 #else
6742 quot=*up/powers[cut];
6743 #endif
6744 for (; ; target++) {
6745 *target=(Unit)quot;
6746 count-=(DECDPUN-cut);
6747 if (count<=0) break;
6748 up++;
6749 quot=*up;
6750 #if DECDPUN<=4
6751 quot=QUOT10(quot, cut);
6752 rem=*up-quot*powers[cut];
6753 #else
6754 rem=quot%powers[cut];
6755 quot=quot/powers[cut];
6756 #endif
6757 *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
6758 count-=cut;
6759 if (count<=0) break;
6761 return target-uar+1;
6762 } /* decShiftToLeast */
6764 #if DECSUBSET
6765 /* ------------------------------------------------------------------ */
6766 /* decRoundOperand -- round an operand [used for subset only] */
6767 /* */
6768 /* dn is the number to round (dn->digits is > set->digits) */
6769 /* set is the relevant context */
6770 /* status is the status accumulator */
6771 /* */
6772 /* returns an allocated decNumber with the rounded result. */
6773 /* */
6774 /* lostDigits and other status may be set by this. */
6775 /* */
6776 /* Since the input is an operand, it must not be modified. */
6777 /* Instead, return an allocated decNumber, rounded as required. */
6778 /* It is the caller's responsibility to free the allocated storage. */
6779 /* */
6780 /* If no storage is available then the result cannot be used, so NULL */
6781 /* is returned. */
6782 /* ------------------------------------------------------------------ */
6783 static decNumber *decRoundOperand(const decNumber *dn, decContext *set,
6784 uInt *status) {
6785 decNumber *res; /* result structure */
6786 uInt newstatus=0; /* status from round */
6787 Int residue=0; /* rounding accumulator */
6789 /* Allocate storage for the returned decNumber, big enough for the */
6790 /* length specified by the context */
6791 res=(decNumber *)malloc(sizeof(decNumber)
6792 +(D2U(set->digits)-1)*sizeof(Unit));
6793 if (res==NULL) {
6794 *status|=DEC_Insufficient_storage;
6795 return NULL;
6797 decCopyFit(res, dn, set, &residue, &newstatus);
6798 decApplyRound(res, set, residue, &newstatus);
6800 /* If that set Inexact then "lost digits" is raised... */
6801 if (newstatus & DEC_Inexact) newstatus|=DEC_Lost_digits;
6802 *status|=newstatus;
6803 return res;
6804 } /* decRoundOperand */
6805 #endif
6807 /* ------------------------------------------------------------------ */
6808 /* decCopyFit -- copy a number, truncating the coefficient if needed */
6809 /* */
6810 /* dest is the target decNumber */
6811 /* src is the source decNumber */
6812 /* set is the context [used for length (digits) and rounding mode] */
6813 /* residue is the residue accumulator */
6814 /* status contains the current status to be updated */
6815 /* */
6816 /* (dest==src is allowed and will be a no-op if fits) */
6817 /* All fields are updated as required. */
6818 /* ------------------------------------------------------------------ */
6819 static void decCopyFit(decNumber *dest, const decNumber *src,
6820 decContext *set, Int *residue, uInt *status) {
6821 dest->bits=src->bits;
6822 dest->exponent=src->exponent;
6823 decSetCoeff(dest, set, src->lsu, src->digits, residue, status);
6824 } /* decCopyFit */
6826 /* ------------------------------------------------------------------ */
6827 /* decSetCoeff -- set the coefficient of a number */
6828 /* */
6829 /* dn is the number whose coefficient array is to be set. */
6830 /* It must have space for set->digits digits */
6831 /* set is the context [for size] */
6832 /* lsu -> lsu of the source coefficient [may be dn->lsu] */
6833 /* len is digits in the source coefficient [may be dn->digits] */
6834 /* residue is the residue accumulator. This has values as in */
6835 /* decApplyRound, and will be unchanged unless the */
6836 /* target size is less than len. In this case, the */
6837 /* coefficient is truncated and the residue is updated to */
6838 /* reflect the previous residue and the dropped digits. */
6839 /* status is the status accumulator, as usual */
6840 /* */
6841 /* The coefficient may already be in the number, or it can be an */
6842 /* external intermediate array. If it is in the number, lsu must == */
6843 /* dn->lsu and len must == dn->digits. */
6844 /* */
6845 /* Note that the coefficient length (len) may be < set->digits, and */
6846 /* in this case this merely copies the coefficient (or is a no-op */
6847 /* if dn->lsu==lsu). */
6848 /* */
6849 /* Note also that (only internally, from decQuantizeOp and */
6850 /* decSetSubnormal) the value of set->digits may be less than one, */
6851 /* indicating a round to left. This routine handles that case */
6852 /* correctly; caller ensures space. */
6853 /* */
6854 /* dn->digits, dn->lsu (and as required), and dn->exponent are */
6855 /* updated as necessary. dn->bits (sign) is unchanged. */
6856 /* */
6857 /* DEC_Rounded status is set if any digits are discarded. */
6858 /* DEC_Inexact status is set if any non-zero digits are discarded, or */
6859 /* incoming residue was non-0 (implies rounded) */
6860 /* ------------------------------------------------------------------ */
6861 /* mapping array: maps 0-9 to canonical residues, so that a residue */
6862 /* can be adjusted in the range [-1, +1] and achieve correct rounding */
6863 /* 0 1 2 3 4 5 6 7 8 9 */
6864 static const uByte resmap[10]={0, 3, 3, 3, 3, 5, 7, 7, 7, 7};
6865 static void decSetCoeff(decNumber *dn, decContext *set, const Unit *lsu,
6866 Int len, Int *residue, uInt *status) {
6867 Int discard; /* number of digits to discard */
6868 uInt cut; /* cut point in Unit */
6869 const Unit *up; /* work */
6870 Unit *target; /* .. */
6871 Int count; /* .. */
6872 #if DECDPUN<=4
6873 uInt temp; /* .. */
6874 #endif
6876 discard=len-set->digits; /* digits to discard */
6877 if (discard<=0) { /* no digits are being discarded */
6878 if (dn->lsu!=lsu) { /* copy needed */
6879 /* copy the coefficient array to the result number; no shift needed */
6880 count=len; /* avoids D2U */
6881 up=lsu;
6882 for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
6883 *target=*up;
6884 dn->digits=len; /* set the new length */
6886 /* dn->exponent and residue are unchanged, record any inexactitude */
6887 if (*residue!=0) *status|=(DEC_Inexact | DEC_Rounded);
6888 return;
6891 /* some digits must be discarded ... */
6892 dn->exponent+=discard; /* maintain numerical value */
6893 *status|=DEC_Rounded; /* accumulate Rounded status */
6894 if (*residue>1) *residue=1; /* previous residue now to right, so reduce */
6896 if (discard>len) { /* everything, +1, is being discarded */
6897 /* guard digit is 0 */
6898 /* residue is all the number [NB could be all 0s] */
6899 if (*residue<=0) { /* not already positive */
6900 count=len; /* avoids D2U */
6901 for (up=lsu; count>0; up++, count-=DECDPUN) if (*up!=0) { /* found non-0 */
6902 *residue=1;
6903 break; /* no need to check any others */
6906 if (*residue!=0) *status|=DEC_Inexact; /* record inexactitude */
6907 *dn->lsu=0; /* coefficient will now be 0 */
6908 dn->digits=1; /* .. */
6909 return;
6910 } /* total discard */
6912 /* partial discard [most common case] */
6913 /* here, at least the first (most significant) discarded digit exists */
6915 /* spin up the number, noting residue during the spin, until get to */
6916 /* the Unit with the first discarded digit. When reach it, extract */
6917 /* it and remember its position */
6918 count=0;
6919 for (up=lsu;; up++) {
6920 count+=DECDPUN;
6921 if (count>=discard) break; /* full ones all checked */
6922 if (*up!=0) *residue=1;
6923 } /* up */
6925 /* here up -> Unit with first discarded digit */
6926 cut=discard-(count-DECDPUN)-1;
6927 if (cut==DECDPUN-1) { /* unit-boundary case (fast) */
6928 Unit half=(Unit)powers[DECDPUN]>>1;
6929 /* set residue directly */
6930 if (*up>=half) {
6931 if (*up>half) *residue=7;
6932 else *residue+=5; /* add sticky bit */
6934 else { /* <half */
6935 if (*up!=0) *residue=3; /* [else is 0, leave as sticky bit] */
6937 if (set->digits<=0) { /* special for Quantize/Subnormal :-( */
6938 *dn->lsu=0; /* .. result is 0 */
6939 dn->digits=1; /* .. */
6941 else { /* shift to least */
6942 count=set->digits; /* now digits to end up with */
6943 dn->digits=count; /* set the new length */
6944 up++; /* move to next */
6945 /* on unit boundary, so shift-down copy loop is simple */
6946 for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
6947 *target=*up;
6949 } /* unit-boundary case */
6951 else { /* discard digit is in low digit(s), and not top digit */
6952 uInt discard1; /* first discarded digit */
6953 uInt quot, rem; /* for divisions */
6954 if (cut==0) quot=*up; /* is at bottom of unit */
6955 else /* cut>0 */ { /* it's not at bottom of unit */
6956 #if DECDPUN<=4
6957 quot=QUOT10(*up, cut);
6958 rem=*up-quot*powers[cut];
6959 #else
6960 rem=*up%powers[cut];
6961 quot=*up/powers[cut];
6962 #endif
6963 if (rem!=0) *residue=1;
6965 /* discard digit is now at bottom of quot */
6966 #if DECDPUN<=4
6967 temp=(quot*6554)>>16; /* fast /10 */
6968 /* Vowels algorithm here not a win (9 instructions) */
6969 discard1=quot-X10(temp);
6970 quot=temp;
6971 #else
6972 discard1=quot%10;
6973 quot=quot/10;
6974 #endif
6975 /* here, discard1 is the guard digit, and residue is everything */
6976 /* else [use mapping array to accumulate residue safely] */
6977 *residue+=resmap[discard1];
6978 cut++; /* update cut */
6979 /* here: up -> Unit of the array with bottom digit */
6980 /* cut is the division point for each Unit */
6981 /* quot holds the uncut high-order digits for the current unit */
6982 if (set->digits<=0) { /* special for Quantize/Subnormal :-( */
6983 *dn->lsu=0; /* .. result is 0 */
6984 dn->digits=1; /* .. */
6986 else { /* shift to least needed */
6987 count=set->digits; /* now digits to end up with */
6988 dn->digits=count; /* set the new length */
6989 /* shift-copy the coefficient array to the result number */
6990 for (target=dn->lsu; ; target++) {
6991 *target=(Unit)quot;
6992 count-=(DECDPUN-cut);
6993 if (count<=0) break;
6994 up++;
6995 quot=*up;
6996 #if DECDPUN<=4
6997 quot=QUOT10(quot, cut);
6998 rem=*up-quot*powers[cut];
6999 #else
7000 rem=quot%powers[cut];
7001 quot=quot/powers[cut];
7002 #endif
7003 *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
7004 count-=cut;
7005 if (count<=0) break;
7006 } /* shift-copy loop */
7007 } /* shift to least */
7008 } /* not unit boundary */
7010 if (*residue!=0) *status|=DEC_Inexact; /* record inexactitude */
7011 return;
7012 } /* decSetCoeff */
7014 /* ------------------------------------------------------------------ */
7015 /* decApplyRound -- apply pending rounding to a number */
7016 /* */
7017 /* dn is the number, with space for set->digits digits */
7018 /* set is the context [for size and rounding mode] */
7019 /* residue indicates pending rounding, being any accumulated */
7020 /* guard and sticky information. It may be: */
7021 /* 6-9: rounding digit is >5 */
7022 /* 5: rounding digit is exactly half-way */
7023 /* 1-4: rounding digit is <5 and >0 */
7024 /* 0: the coefficient is exact */
7025 /* -1: as 1, but the hidden digits are subtractive, that */
7026 /* is, of the opposite sign to dn. In this case the */
7027 /* coefficient must be non-0. This case occurs when */
7028 /* subtracting a small number (which can be reduced to */
7029 /* a sticky bit); see decAddOp. */
7030 /* status is the status accumulator, as usual */
7031 /* */
7032 /* This routine applies rounding while keeping the length of the */
7033 /* coefficient constant. The exponent and status are unchanged */
7034 /* except if: */
7035 /* */
7036 /* -- the coefficient was increased and is all nines (in which */
7037 /* case Overflow could occur, and is handled directly here so */
7038 /* the caller does not need to re-test for overflow) */
7039 /* */
7040 /* -- the coefficient was decreased and becomes all nines (in which */
7041 /* case Underflow could occur, and is also handled directly). */
7042 /* */
7043 /* All fields in dn are updated as required. */
7044 /* */
7045 /* ------------------------------------------------------------------ */
7046 static void decApplyRound(decNumber *dn, decContext *set, Int residue,
7047 uInt *status) {
7048 Int bump; /* 1 if coefficient needs to be incremented */
7049 /* -1 if coefficient needs to be decremented */
7051 if (residue==0) return; /* nothing to apply */
7053 bump=0; /* assume a smooth ride */
7055 /* now decide whether, and how, to round, depending on mode */
7056 switch (set->round) {
7057 case DEC_ROUND_05UP: { /* round zero or five up (for reround) */
7058 /* This is the same as DEC_ROUND_DOWN unless there is a */
7059 /* positive residue and the lsd of dn is 0 or 5, in which case */
7060 /* it is bumped; when residue is <0, the number is therefore */
7061 /* bumped down unless the final digit was 1 or 6 (in which */
7062 /* case it is bumped down and then up -- a no-op) */
7063 Int lsd5=*dn->lsu%5; /* get lsd and quintate */
7064 if (residue<0 && lsd5!=1) bump=-1;
7065 else if (residue>0 && lsd5==0) bump=1;
7066 /* [bump==1 could be applied directly; use common path for clarity] */
7067 break;} /* r-05 */
7069 case DEC_ROUND_DOWN: {
7070 /* no change, except if negative residue */
7071 if (residue<0) bump=-1;
7072 break;} /* r-d */
7074 case DEC_ROUND_HALF_DOWN: {
7075 if (residue>5) bump=1;
7076 break;} /* r-h-d */
7078 case DEC_ROUND_HALF_EVEN: {
7079 if (residue>5) bump=1; /* >0.5 goes up */
7080 else if (residue==5) { /* exactly 0.5000... */
7081 /* 0.5 goes up iff [new] lsd is odd */
7082 if (*dn->lsu & 0x01) bump=1;
7084 break;} /* r-h-e */
7086 case DEC_ROUND_HALF_UP: {
7087 if (residue>=5) bump=1;
7088 break;} /* r-h-u */
7090 case DEC_ROUND_UP: {
7091 if (residue>0) bump=1;
7092 break;} /* r-u */
7094 case DEC_ROUND_CEILING: {
7095 /* same as _UP for positive numbers, and as _DOWN for negatives */
7096 /* [negative residue cannot occur on 0] */
7097 if (decNumberIsNegative(dn)) {
7098 if (residue<0) bump=-1;
7100 else {
7101 if (residue>0) bump=1;
7103 break;} /* r-c */
7105 case DEC_ROUND_FLOOR: {
7106 /* same as _UP for negative numbers, and as _DOWN for positive */
7107 /* [negative residue cannot occur on 0] */
7108 if (!decNumberIsNegative(dn)) {
7109 if (residue<0) bump=-1;
7111 else {
7112 if (residue>0) bump=1;
7114 break;} /* r-f */
7116 default: { /* e.g., DEC_ROUND_MAX */
7117 *status|=DEC_Invalid_context;
7118 #if DECTRACE || (DECCHECK && DECVERB)
7119 printf("Unknown rounding mode: %d\n", set->round);
7120 #endif
7121 break;}
7122 } /* switch */
7124 /* now bump the number, up or down, if need be */
7125 if (bump==0) return; /* no action required */
7127 /* Simply use decUnitAddSub unless bumping up and the number is */
7128 /* all nines. In this special case set to 100... explicitly */
7129 /* and adjust the exponent by one (as otherwise could overflow */
7130 /* the array) */
7131 /* Similarly handle all-nines result if bumping down. */
7132 if (bump>0) {
7133 Unit *up; /* work */
7134 uInt count=dn->digits; /* digits to be checked */
7135 for (up=dn->lsu; ; up++) {
7136 if (count<=DECDPUN) {
7137 /* this is the last Unit (the msu) */
7138 if (*up!=powers[count]-1) break; /* not still 9s */
7139 /* here if it, too, is all nines */
7140 *up=(Unit)powers[count-1]; /* here 999 -> 100 etc. */
7141 for (up=up-1; up>=dn->lsu; up--) *up=0; /* others all to 0 */
7142 dn->exponent++; /* and bump exponent */
7143 /* [which, very rarely, could cause Overflow...] */
7144 if ((dn->exponent+dn->digits)>set->emax+1) {
7145 decSetOverflow(dn, set, status);
7147 return; /* done */
7149 /* a full unit to check, with more to come */
7150 if (*up!=DECDPUNMAX) break; /* not still 9s */
7151 count-=DECDPUN;
7152 } /* up */
7153 } /* bump>0 */
7154 else { /* -1 */
7155 /* here checking for a pre-bump of 1000... (leading 1, all */
7156 /* other digits zero) */
7157 Unit *up, *sup; /* work */
7158 uInt count=dn->digits; /* digits to be checked */
7159 for (up=dn->lsu; ; up++) {
7160 if (count<=DECDPUN) {
7161 /* this is the last Unit (the msu) */
7162 if (*up!=powers[count-1]) break; /* not 100.. */
7163 /* here if have the 1000... case */
7164 sup=up; /* save msu pointer */
7165 *up=(Unit)powers[count]-1; /* here 100 in msu -> 999 */
7166 /* others all to all-nines, too */
7167 for (up=up-1; up>=dn->lsu; up--) *up=(Unit)powers[DECDPUN]-1;
7168 dn->exponent--; /* and bump exponent */
7170 /* iff the number was at the subnormal boundary (exponent=etiny) */
7171 /* then the exponent is now out of range, so it will in fact get */
7172 /* clamped to etiny and the final 9 dropped. */
7173 /* printf(">> emin=%d exp=%d sdig=%d\n", set->emin, */
7174 /* dn->exponent, set->digits); */
7175 if (dn->exponent+1==set->emin-set->digits+1) {
7176 if (count==1 && dn->digits==1) *sup=0; /* here 9 -> 0[.9] */
7177 else {
7178 *sup=(Unit)powers[count-1]-1; /* here 999.. in msu -> 99.. */
7179 dn->digits--;
7181 dn->exponent++;
7182 *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
7184 return; /* done */
7187 /* a full unit to check, with more to come */
7188 if (*up!=0) break; /* not still 0s */
7189 count-=DECDPUN;
7190 } /* up */
7192 } /* bump<0 */
7194 /* Actual bump needed. Do it. */
7195 decUnitAddSub(dn->lsu, D2U(dn->digits), uarrone, 1, 0, dn->lsu, bump);
7196 } /* decApplyRound */
7198 #if DECSUBSET
7199 /* ------------------------------------------------------------------ */
7200 /* decFinish -- finish processing a number */
7201 /* */
7202 /* dn is the number */
7203 /* set is the context */
7204 /* residue is the rounding accumulator (as in decApplyRound) */
7205 /* status is the accumulator */
7206 /* */
7207 /* This finishes off the current number by: */
7208 /* 1. If not extended: */
7209 /* a. Converting a zero result to clean '0' */
7210 /* b. Reducing positive exponents to 0, if would fit in digits */
7211 /* 2. Checking for overflow and subnormals (always) */
7212 /* Note this is just Finalize when no subset arithmetic. */
7213 /* All fields are updated as required. */
7214 /* ------------------------------------------------------------------ */
7215 static void decFinish(decNumber *dn, decContext *set, Int *residue,
7216 uInt *status) {
7217 if (!set->extended) {
7218 if ISZERO(dn) { /* value is zero */
7219 dn->exponent=0; /* clean exponent .. */
7220 dn->bits=0; /* .. and sign */
7221 return; /* no error possible */
7223 if (dn->exponent>=0) { /* non-negative exponent */
7224 /* >0; reduce to integer if possible */
7225 if (set->digits >= (dn->exponent+dn->digits)) {
7226 dn->digits=decShiftToMost(dn->lsu, dn->digits, dn->exponent);
7227 dn->exponent=0;
7230 } /* !extended */
7232 decFinalize(dn, set, residue, status);
7233 } /* decFinish */
7234 #endif
7236 /* ------------------------------------------------------------------ */
7237 /* decFinalize -- final check, clamp, and round of a number */
7238 /* */
7239 /* dn is the number */
7240 /* set is the context */
7241 /* residue is the rounding accumulator (as in decApplyRound) */
7242 /* status is the status accumulator */
7243 /* */
7244 /* This finishes off the current number by checking for subnormal */
7245 /* results, applying any pending rounding, checking for overflow, */
7246 /* and applying any clamping. */
7247 /* Underflow and overflow conditions are raised as appropriate. */
7248 /* All fields are updated as required. */
7249 /* ------------------------------------------------------------------ */
7250 static void decFinalize(decNumber *dn, decContext *set, Int *residue,
7251 uInt *status) {
7252 Int shift; /* shift needed if clamping */
7253 Int tinyexp=set->emin-dn->digits+1; /* precalculate subnormal boundary */
7255 /* Must be careful, here, when checking the exponent as the */
7256 /* adjusted exponent could overflow 31 bits [because it may already */
7257 /* be up to twice the expected]. */
7259 /* First test for subnormal. This must be done before any final */
7260 /* round as the result could be rounded to Nmin or 0. */
7261 if (dn->exponent<=tinyexp) { /* prefilter */
7262 Int comp;
7263 decNumber nmin;
7264 /* A very nasty case here is dn == Nmin and residue<0 */
7265 if (dn->exponent<tinyexp) {
7266 /* Go handle subnormals; this will apply round if needed. */
7267 decSetSubnormal(dn, set, residue, status);
7268 return;
7270 /* Equals case: only subnormal if dn=Nmin and negative residue */
7271 decNumberZero(&nmin);
7272 nmin.lsu[0]=1;
7273 nmin.exponent=set->emin;
7274 comp=decCompare(dn, &nmin, 1); /* (signless compare) */
7275 if (comp==BADINT) { /* oops */
7276 *status|=DEC_Insufficient_storage; /* abandon... */
7277 return;
7279 if (*residue<0 && comp==0) { /* neg residue and dn==Nmin */
7280 decApplyRound(dn, set, *residue, status); /* might force down */
7281 decSetSubnormal(dn, set, residue, status);
7282 return;
7286 /* now apply any pending round (this could raise overflow). */
7287 if (*residue!=0) decApplyRound(dn, set, *residue, status);
7289 /* Check for overflow [redundant in the 'rare' case] or clamp */
7290 if (dn->exponent<=set->emax-set->digits+1) return; /* neither needed */
7293 /* here when might have an overflow or clamp to do */
7294 if (dn->exponent>set->emax-dn->digits+1) { /* too big */
7295 decSetOverflow(dn, set, status);
7296 return;
7298 /* here when the result is normal but in clamp range */
7299 if (!set->clamp) return;
7301 /* here when need to apply the IEEE exponent clamp (fold-down) */
7302 shift=dn->exponent-(set->emax-set->digits+1);
7304 /* shift coefficient (if non-zero) */
7305 if (!ISZERO(dn)) {
7306 dn->digits=decShiftToMost(dn->lsu, dn->digits, shift);
7308 dn->exponent-=shift; /* adjust the exponent to match */
7309 *status|=DEC_Clamped; /* and record the dirty deed */
7310 return;
7311 } /* decFinalize */
7313 /* ------------------------------------------------------------------ */
7314 /* decSetOverflow -- set number to proper overflow value */
7315 /* */
7316 /* dn is the number (used for sign [only] and result) */
7317 /* set is the context [used for the rounding mode, etc.] */
7318 /* status contains the current status to be updated */
7319 /* */
7320 /* This sets the sign of a number and sets its value to either */
7321 /* Infinity or the maximum finite value, depending on the sign of */
7322 /* dn and the rounding mode, following IEEE 854 rules. */
7323 /* ------------------------------------------------------------------ */
7324 static void decSetOverflow(decNumber *dn, decContext *set, uInt *status) {
7325 Flag needmax=0; /* result is maximum finite value */
7326 uByte sign=dn->bits&DECNEG; /* clean and save sign bit */
7328 if (ISZERO(dn)) { /* zero does not overflow magnitude */
7329 Int emax=set->emax; /* limit value */
7330 if (set->clamp) emax-=set->digits-1; /* lower if clamping */
7331 if (dn->exponent>emax) { /* clamp required */
7332 dn->exponent=emax;
7333 *status|=DEC_Clamped;
7335 return;
7338 decNumberZero(dn);
7339 switch (set->round) {
7340 case DEC_ROUND_DOWN: {
7341 needmax=1; /* never Infinity */
7342 break;} /* r-d */
7343 case DEC_ROUND_05UP: {
7344 needmax=1; /* never Infinity */
7345 break;} /* r-05 */
7346 case DEC_ROUND_CEILING: {
7347 if (sign) needmax=1; /* Infinity if non-negative */
7348 break;} /* r-c */
7349 case DEC_ROUND_FLOOR: {
7350 if (!sign) needmax=1; /* Infinity if negative */
7351 break;} /* r-f */
7352 default: break; /* Infinity in all other cases */
7354 if (needmax) {
7355 decSetMaxValue(dn, set);
7356 dn->bits=sign; /* set sign */
7358 else dn->bits=sign|DECINF; /* Value is +/-Infinity */
7359 *status|=DEC_Overflow | DEC_Inexact | DEC_Rounded;
7360 } /* decSetOverflow */
7362 /* ------------------------------------------------------------------ */
7363 /* decSetMaxValue -- set number to +Nmax (maximum normal value) */
7364 /* */
7365 /* dn is the number to set */
7366 /* set is the context [used for digits and emax] */
7367 /* */
7368 /* This sets the number to the maximum positive value. */
7369 /* ------------------------------------------------------------------ */
7370 static void decSetMaxValue(decNumber *dn, decContext *set) {
7371 Unit *up; /* work */
7372 Int count=set->digits; /* nines to add */
7373 dn->digits=count;
7374 /* fill in all nines to set maximum value */
7375 for (up=dn->lsu; ; up++) {
7376 if (count>DECDPUN) *up=DECDPUNMAX; /* unit full o'nines */
7377 else { /* this is the msu */
7378 *up=(Unit)(powers[count]-1);
7379 break;
7381 count-=DECDPUN; /* filled those digits */
7382 } /* up */
7383 dn->bits=0; /* + sign */
7384 dn->exponent=set->emax-set->digits+1;
7385 } /* decSetMaxValue */
7387 /* ------------------------------------------------------------------ */
7388 /* decSetSubnormal -- process value whose exponent is <Emin */
7389 /* */
7390 /* dn is the number (used as input as well as output; it may have */
7391 /* an allowed subnormal value, which may need to be rounded) */
7392 /* set is the context [used for the rounding mode] */
7393 /* residue is any pending residue */
7394 /* status contains the current status to be updated */
7395 /* */
7396 /* If subset mode, set result to zero and set Underflow flags. */
7397 /* */
7398 /* Value may be zero with a low exponent; this does not set Subnormal */
7399 /* but the exponent will be clamped to Etiny. */
7400 /* */
7401 /* Otherwise ensure exponent is not out of range, and round as */
7402 /* necessary. Underflow is set if the result is Inexact. */
7403 /* ------------------------------------------------------------------ */
7404 static void decSetSubnormal(decNumber *dn, decContext *set, Int *residue,
7405 uInt *status) {
7406 Int dnexp; /* saves original exponent */
7407 decContext workset; /* work */
7408 Int etiny, adjust; /* .. */
7410 #if DECSUBSET
7411 /* simple set to zero and 'hard underflow' for subset */
7412 if (!set->extended) {
7413 decNumberZero(dn);
7414 /* always full overflow */
7415 *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
7416 return;
7418 #endif
7420 /* Full arithmetic -- allow subnormals, rounded to minimum exponent */
7421 /* (Etiny) if needed */
7422 etiny=set->emin-(set->digits-1); /* smallest allowed exponent */
7424 if ISZERO(dn) { /* value is zero */
7425 /* residue can never be non-zero here */
7426 #if DECCHECK
7427 if (*residue!=0) {
7428 printf("++ Subnormal 0 residue %ld\n", (LI)*residue);
7429 *status|=DEC_Invalid_operation;
7431 #endif
7432 if (dn->exponent<etiny) { /* clamp required */
7433 dn->exponent=etiny;
7434 *status|=DEC_Clamped;
7436 return;
7439 *status|=DEC_Subnormal; /* have a non-zero subnormal */
7440 adjust=etiny-dn->exponent; /* calculate digits to remove */
7441 if (adjust<=0) { /* not out of range; unrounded */
7442 /* residue can never be non-zero here, except in the Nmin-residue */
7443 /* case (which is a subnormal result), so can take fast-path here */
7444 /* it may already be inexact (from setting the coefficient) */
7445 if (*status&DEC_Inexact) *status|=DEC_Underflow;
7446 return;
7449 /* adjust>0, so need to rescale the result so exponent becomes Etiny */
7450 /* [this code is similar to that in rescale] */
7451 dnexp=dn->exponent; /* save exponent */
7452 workset=*set; /* clone rounding, etc. */
7453 workset.digits=dn->digits-adjust; /* set requested length */
7454 workset.emin-=adjust; /* and adjust emin to match */
7455 /* [note that the latter can be <1, here, similar to Rescale case] */
7456 decSetCoeff(dn, &workset, dn->lsu, dn->digits, residue, status);
7457 decApplyRound(dn, &workset, *residue, status);
7459 /* Use 754R/854 default rule: Underflow is set iff Inexact */
7460 /* [independent of whether trapped] */
7461 if (*status&DEC_Inexact) *status|=DEC_Underflow;
7463 /* if rounded up a 999s case, exponent will be off by one; adjust */
7464 /* back if so [it will fit, because it was shortened earlier] */
7465 if (dn->exponent>etiny) {
7466 dn->digits=decShiftToMost(dn->lsu, dn->digits, 1);
7467 dn->exponent--; /* (re)adjust the exponent. */
7470 /* if rounded to zero, it is by definition clamped... */
7471 if (ISZERO(dn)) *status|=DEC_Clamped;
7472 } /* decSetSubnormal */
7474 /* ------------------------------------------------------------------ */
7475 /* decCheckMath - check entry conditions for a math function */
7476 /* */
7477 /* This checks the context and the operand */
7478 /* */
7479 /* rhs is the operand to check */
7480 /* set is the context to check */
7481 /* status is unchanged if both are good */
7482 /* */
7483 /* returns non-zero if status is changed, 0 otherwise */
7484 /* */
7485 /* Restrictions enforced: */
7486 /* */
7487 /* digits, emax, and -emin in the context must be less than */
7488 /* DEC_MAX_MATH (999999), and A must be within these bounds if */
7489 /* non-zero. Invalid_operation is set in the status if a */
7490 /* restriction is violated. */
7491 /* ------------------------------------------------------------------ */
7492 static uInt decCheckMath(const decNumber *rhs, decContext *set,
7493 uInt *status) {
7494 uInt save=*status; /* record */
7495 if (set->digits>DEC_MAX_MATH
7496 || set->emax>DEC_MAX_MATH
7497 || -set->emin>DEC_MAX_MATH) *status|=DEC_Invalid_context;
7498 else if ((rhs->digits>DEC_MAX_MATH
7499 || rhs->exponent+rhs->digits>DEC_MAX_MATH+1
7500 || rhs->exponent+rhs->digits<2*(1-DEC_MAX_MATH))
7501 && !ISZERO(rhs)) *status|=DEC_Invalid_operation;
7502 return (*status!=save);
7503 } /* decCheckMath */
7505 /* ------------------------------------------------------------------ */
7506 /* decGetInt -- get integer from a number */
7507 /* */
7508 /* dn is the number [which will not be altered] */
7509 /* */
7510 /* returns one of: */
7511 /* BADINT if there is a non-zero fraction */
7512 /* the converted integer */
7513 /* BIGEVEN if the integer is even and magnitude > 2*10**9 */
7514 /* BIGODD if the integer is odd and magnitude > 2*10**9 */
7515 /* */
7516 /* This checks and gets a whole number from the input decNumber. */
7517 /* The sign can be determined from dn by the caller when BIGEVEN or */
7518 /* BIGODD is returned. */
7519 /* ------------------------------------------------------------------ */
7520 static Int decGetInt(const decNumber *dn) {
7521 Int theInt; /* result accumulator */
7522 const Unit *up; /* work */
7523 Int got; /* digits (real or not) processed */
7524 Int ilength=dn->digits+dn->exponent; /* integral length */
7525 Flag neg=decNumberIsNegative(dn); /* 1 if -ve */
7527 /* The number must be an integer that fits in 10 digits */
7528 /* Assert, here, that 10 is enough for any rescale Etiny */
7529 #if DEC_MAX_EMAX > 999999999
7530 #error GetInt may need updating [for Emax]
7531 #endif
7532 #if DEC_MIN_EMIN < -999999999
7533 #error GetInt may need updating [for Emin]
7534 #endif
7535 if (ISZERO(dn)) return 0; /* zeros are OK, with any exponent */
7537 up=dn->lsu; /* ready for lsu */
7538 theInt=0; /* ready to accumulate */
7539 if (dn->exponent>=0) { /* relatively easy */
7540 /* no fractional part [usual]; allow for positive exponent */
7541 got=dn->exponent;
7543 else { /* -ve exponent; some fractional part to check and discard */
7544 Int count=-dn->exponent; /* digits to discard */
7545 /* spin up whole units until reach the Unit with the unit digit */
7546 for (; count>=DECDPUN; up++) {
7547 if (*up!=0) return BADINT; /* non-zero Unit to discard */
7548 count-=DECDPUN;
7550 if (count==0) got=0; /* [a multiple of DECDPUN] */
7551 else { /* [not multiple of DECDPUN] */
7552 Int rem; /* work */
7553 /* slice off fraction digits and check for non-zero */
7554 #if DECDPUN<=4
7555 theInt=QUOT10(*up, count);
7556 rem=*up-theInt*powers[count];
7557 #else
7558 rem=*up%powers[count]; /* slice off discards */
7559 theInt=*up/powers[count];
7560 #endif
7561 if (rem!=0) return BADINT; /* non-zero fraction */
7562 /* it looks good */
7563 got=DECDPUN-count; /* number of digits so far */
7564 up++; /* ready for next */
7567 /* now it's known there's no fractional part */
7569 /* tricky code now, to accumulate up to 9.3 digits */
7570 if (got==0) {theInt=*up; got+=DECDPUN; up++;} /* ensure lsu is there */
7572 if (ilength<11) {
7573 Int save=theInt;
7574 /* collect any remaining unit(s) */
7575 for (; got<ilength; up++) {
7576 theInt+=*up*powers[got];
7577 got+=DECDPUN;
7579 if (ilength==10) { /* need to check for wrap */
7580 if (theInt/(Int)powers[got-DECDPUN]!=(Int)*(up-1)) ilength=11;
7581 /* [that test also disallows the BADINT result case] */
7582 else if (neg && theInt>1999999997) ilength=11;
7583 else if (!neg && theInt>999999999) ilength=11;
7584 if (ilength==11) theInt=save; /* restore correct low bit */
7588 if (ilength>10) { /* too big */
7589 if (theInt&1) return BIGODD; /* bottom bit 1 */
7590 return BIGEVEN; /* bottom bit 0 */
7593 if (neg) theInt=-theInt; /* apply sign */
7594 return theInt;
7595 } /* decGetInt */
7597 /* ------------------------------------------------------------------ */
7598 /* decDecap -- decapitate the coefficient of a number */
7599 /* */
7600 /* dn is the number to be decapitated */
7601 /* drop is the number of digits to be removed from the left of dn; */
7602 /* this must be <= dn->digits (if equal, the coefficient is */
7603 /* set to 0) */
7604 /* */
7605 /* Returns dn; dn->digits will be <= the initial digits less drop */
7606 /* (after removing drop digits there may be leading zero digits */
7607 /* which will also be removed). Only dn->lsu and dn->digits change. */
7608 /* ------------------------------------------------------------------ */
7609 static decNumber *decDecap(decNumber *dn, Int drop) {
7610 Unit *msu; /* -> target cut point */
7611 Int cut; /* work */
7612 if (drop>=dn->digits) { /* losing the whole thing */
7613 #if DECCHECK
7614 if (drop>dn->digits)
7615 printf("decDecap called with drop>digits [%ld>%ld]\n",
7616 (LI)drop, (LI)dn->digits);
7617 #endif
7618 dn->lsu[0]=0;
7619 dn->digits=1;
7620 return dn;
7622 msu=dn->lsu+D2U(dn->digits-drop)-1; /* -> likely msu */
7623 cut=MSUDIGITS(dn->digits-drop); /* digits to be in use in msu */
7624 if (cut!=DECDPUN) *msu%=powers[cut]; /* clear left digits */
7625 /* that may have left leading zero digits, so do a proper count... */
7626 dn->digits=decGetDigits(dn->lsu, msu-dn->lsu+1);
7627 return dn;
7628 } /* decDecap */
7630 /* ------------------------------------------------------------------ */
7631 /* decBiStr -- compare string with pairwise options */
7632 /* */
7633 /* targ is the string to compare */
7634 /* str1 is one of the strings to compare against (length may be 0) */
7635 /* str2 is the other; it must be the same length as str1 */
7636 /* */
7637 /* returns 1 if strings compare equal, (that is, it is the same */
7638 /* length as str1 and str2, and each character of targ is in either */
7639 /* str1 or str2 in the corresponding position), or 0 otherwise */
7640 /* */
7641 /* This is used for generic caseless compare, including the awkward */
7642 /* case of the Turkish dotted and dotless Is. Use as (for example): */
7643 /* if (decBiStr(test, "mike", "MIKE")) ... */
7644 /* ------------------------------------------------------------------ */
7645 static Flag decBiStr(const char *targ, const char *str1, const char *str2) {
7646 for (;;targ++, str1++, str2++) {
7647 if (*targ!=*str1 && *targ!=*str2) return 0;
7648 /* *targ has a match in one (or both, if terminator) */
7649 if (*targ=='\0') break;
7650 } /* forever */
7651 return 1;
7652 } /* decBiStr */
7654 /* ------------------------------------------------------------------ */
7655 /* decNaNs -- handle NaN operand or operands */
7656 /* */
7657 /* res is the result number */
7658 /* lhs is the first operand */
7659 /* rhs is the second operand, or NULL if none */
7660 /* context is used to limit payload length */
7661 /* status contains the current status */
7662 /* returns res in case convenient */
7663 /* */
7664 /* Called when one or both operands is a NaN, and propagates the */
7665 /* appropriate result to res. When an sNaN is found, it is changed */
7666 /* to a qNaN and Invalid operation is set. */
7667 /* ------------------------------------------------------------------ */
7668 static decNumber * decNaNs(decNumber *res, const decNumber *lhs,
7669 const decNumber *rhs, decContext *set,
7670 uInt *status) {
7671 /* This decision tree ends up with LHS being the source pointer, */
7672 /* and status updated if need be */
7673 if (lhs->bits & DECSNAN)
7674 *status|=DEC_Invalid_operation | DEC_sNaN;
7675 else if (rhs==NULL);
7676 else if (rhs->bits & DECSNAN) {
7677 lhs=rhs;
7678 *status|=DEC_Invalid_operation | DEC_sNaN;
7680 else if (lhs->bits & DECNAN);
7681 else lhs=rhs;
7683 /* propagate the payload */
7684 if (lhs->digits<=set->digits) decNumberCopy(res, lhs); /* easy */
7685 else { /* too long */
7686 const Unit *ul;
7687 Unit *ur, *uresp1;
7688 /* copy safe number of units, then decapitate */
7689 res->bits=lhs->bits; /* need sign etc. */
7690 uresp1=res->lsu+D2U(set->digits);
7691 for (ur=res->lsu, ul=lhs->lsu; ur<uresp1; ur++, ul++) *ur=*ul;
7692 res->digits=D2U(set->digits)*DECDPUN;
7693 /* maybe still too long */
7694 if (res->digits>set->digits) decDecap(res, res->digits-set->digits);
7697 res->bits&=~DECSNAN; /* convert any sNaN to NaN, while */
7698 res->bits|=DECNAN; /* .. preserving sign */
7699 res->exponent=0; /* clean exponent */
7700 /* [coefficient was copied/decapitated] */
7701 return res;
7702 } /* decNaNs */
7704 /* ------------------------------------------------------------------ */
7705 /* decStatus -- apply non-zero status */
7706 /* */
7707 /* dn is the number to set if error */
7708 /* status contains the current status (not yet in context) */
7709 /* set is the context */
7710 /* */
7711 /* If the status is an error status, the number is set to a NaN, */
7712 /* unless the error was an overflow, divide-by-zero, or underflow, */
7713 /* in which case the number will have already been set. */
7714 /* */
7715 /* The context status is then updated with the new status. Note that */
7716 /* this may raise a signal, so control may never return from this */
7717 /* routine (hence resources must be recovered before it is called). */
7718 /* ------------------------------------------------------------------ */
7719 static void decStatus(decNumber *dn, uInt status, decContext *set) {
7720 if (status & DEC_NaNs) { /* error status -> NaN */
7721 /* if cause was an sNaN, clear and propagate [NaN is already set up] */
7722 if (status & DEC_sNaN) status&=~DEC_sNaN;
7723 else {
7724 decNumberZero(dn); /* other error: clean throughout */
7725 dn->bits=DECNAN; /* and make a quiet NaN */
7728 decContextSetStatus(set, status); /* [may not return] */
7729 return;
7730 } /* decStatus */
7732 /* ------------------------------------------------------------------ */
7733 /* decGetDigits -- count digits in a Units array */
7734 /* */
7735 /* uar is the Unit array holding the number (this is often an */
7736 /* accumulator of some sort) */
7737 /* len is the length of the array in units [>=1] */
7738 /* */
7739 /* returns the number of (significant) digits in the array */
7740 /* */
7741 /* All leading zeros are excluded, except the last if the array has */
7742 /* only zero Units. */
7743 /* ------------------------------------------------------------------ */
7744 /* This may be called twice during some operations. */
7745 static Int decGetDigits(Unit *uar, Int len) {
7746 Unit *up=uar+(len-1); /* -> msu */
7747 Int digits=(len-1)*DECDPUN+1; /* possible digits excluding msu */
7748 #if DECDPUN>4
7749 uInt const *pow; /* work */
7750 #endif
7751 /* (at least 1 in final msu) */
7752 #if DECCHECK
7753 if (len<1) printf("decGetDigits called with len<1 [%ld]\n", (LI)len);
7754 #endif
7756 for (; up>=uar; up--) {
7757 if (*up==0) { /* unit is all 0s */
7758 if (digits==1) break; /* a zero has one digit */
7759 digits-=DECDPUN; /* adjust for 0 unit */
7760 continue;}
7761 /* found the first (most significant) non-zero Unit */
7762 #if DECDPUN>1 /* not done yet */
7763 if (*up<10) break; /* is 1-9 */
7764 digits++;
7765 #if DECDPUN>2 /* not done yet */
7766 if (*up<100) break; /* is 10-99 */
7767 digits++;
7768 #if DECDPUN>3 /* not done yet */
7769 if (*up<1000) break; /* is 100-999 */
7770 digits++;
7771 #if DECDPUN>4 /* count the rest ... */
7772 for (pow=&powers[4]; *up>=*pow; pow++) digits++;
7773 #endif
7774 #endif
7775 #endif
7776 #endif
7777 break;
7778 } /* up */
7779 return digits;
7780 } /* decGetDigits */
7782 #if DECTRACE | DECCHECK
7783 /* ------------------------------------------------------------------ */
7784 /* decNumberShow -- display a number [debug aid] */
7785 /* dn is the number to show */
7786 /* */
7787 /* Shows: sign, exponent, coefficient (msu first), digits */
7788 /* or: sign, special-value */
7789 /* ------------------------------------------------------------------ */
7790 /* this is public so other modules can use it */
7791 void decNumberShow(const decNumber *dn) {
7792 const Unit *up; /* work */
7793 uInt u, d; /* .. */
7794 Int cut; /* .. */
7795 char isign='+'; /* main sign */
7796 if (dn==NULL) {
7797 printf("NULL\n");
7798 return;}
7799 if (decNumberIsNegative(dn)) isign='-';
7800 printf(" >> %c ", isign);
7801 if (dn->bits&DECSPECIAL) { /* Is a special value */
7802 if (decNumberIsInfinite(dn)) printf("Infinity");
7803 else { /* a NaN */
7804 if (dn->bits&DECSNAN) printf("sNaN"); /* signalling NaN */
7805 else printf("NaN");
7807 /* if coefficient and exponent are 0, no more to do */
7808 if (dn->exponent==0 && dn->digits==1 && *dn->lsu==0) {
7809 printf("\n");
7810 return;}
7811 /* drop through to report other information */
7812 printf(" ");
7815 /* now carefully display the coefficient */
7816 up=dn->lsu+D2U(dn->digits)-1; /* msu */
7817 printf("%ld", (LI)*up);
7818 for (up=up-1; up>=dn->lsu; up--) {
7819 u=*up;
7820 printf(":");
7821 for (cut=DECDPUN-1; cut>=0; cut--) {
7822 d=u/powers[cut];
7823 u-=d*powers[cut];
7824 printf("%ld", (LI)d);
7825 } /* cut */
7826 } /* up */
7827 if (dn->exponent!=0) {
7828 char esign='+';
7829 if (dn->exponent<0) esign='-';
7830 printf(" E%c%ld", esign, (LI)abs(dn->exponent));
7832 printf(" [%ld]\n", (LI)dn->digits);
7833 } /* decNumberShow */
7834 #endif
7836 #if DECTRACE || DECCHECK
7837 /* ------------------------------------------------------------------ */
7838 /* decDumpAr -- display a unit array [debug/check aid] */
7839 /* name is a single-character tag name */
7840 /* ar is the array to display */
7841 /* len is the length of the array in Units */
7842 /* ------------------------------------------------------------------ */
7843 static void decDumpAr(char name, const Unit *ar, Int len) {
7844 Int i;
7845 const char *spec;
7846 #if DECDPUN==9
7847 spec="%09d ";
7848 #elif DECDPUN==8
7849 spec="%08d ";
7850 #elif DECDPUN==7
7851 spec="%07d ";
7852 #elif DECDPUN==6
7853 spec="%06d ";
7854 #elif DECDPUN==5
7855 spec="%05d ";
7856 #elif DECDPUN==4
7857 spec="%04d ";
7858 #elif DECDPUN==3
7859 spec="%03d ";
7860 #elif DECDPUN==2
7861 spec="%02d ";
7862 #else
7863 spec="%d ";
7864 #endif
7865 printf(" :%c: ", name);
7866 for (i=len-1; i>=0; i--) {
7867 if (i==len-1) printf("%ld ", (LI)ar[i]);
7868 else printf(spec, ar[i]);
7870 printf("\n");
7871 return;}
7872 #endif
7874 #if DECCHECK
7875 /* ------------------------------------------------------------------ */
7876 /* decCheckOperands -- check operand(s) to a routine */
7877 /* res is the result structure (not checked; it will be set to */
7878 /* quiet NaN if error found (and it is not NULL)) */
7879 /* lhs is the first operand (may be DECUNRESU) */
7880 /* rhs is the second (may be DECUNUSED) */
7881 /* set is the context (may be DECUNCONT) */
7882 /* returns 0 if both operands, and the context are clean, or 1 */
7883 /* otherwise (in which case the context will show an error, */
7884 /* unless NULL). Note that res is not cleaned; caller should */
7885 /* handle this so res=NULL case is safe. */
7886 /* The caller is expected to abandon immediately if 1 is returned. */
7887 /* ------------------------------------------------------------------ */
7888 static Flag decCheckOperands(decNumber *res, const decNumber *lhs,
7889 const decNumber *rhs, decContext *set) {
7890 Flag bad=0;
7891 if (set==NULL) { /* oops; hopeless */
7892 #if DECTRACE || DECVERB
7893 printf("Reference to context is NULL.\n");
7894 #endif
7895 bad=1;
7896 return 1;}
7897 else if (set!=DECUNCONT
7898 && (set->digits<1 || set->round>=DEC_ROUND_MAX)) {
7899 bad=1;
7900 #if DECTRACE || DECVERB
7901 printf("Bad context [digits=%ld round=%ld].\n",
7902 (LI)set->digits, (LI)set->round);
7903 #endif
7905 else {
7906 if (res==NULL) {
7907 bad=1;
7908 #if DECTRACE
7909 /* this one not DECVERB as standard tests include NULL */
7910 printf("Reference to result is NULL.\n");
7911 #endif
7913 if (!bad && lhs!=DECUNUSED) bad=(decCheckNumber(lhs));
7914 if (!bad && rhs!=DECUNUSED) bad=(decCheckNumber(rhs));
7916 if (bad) {
7917 if (set!=DECUNCONT) decContextSetStatus(set, DEC_Invalid_operation);
7918 if (res!=DECUNRESU && res!=NULL) {
7919 decNumberZero(res);
7920 res->bits=DECNAN; /* qNaN */
7923 return bad;
7924 } /* decCheckOperands */
7926 /* ------------------------------------------------------------------ */
7927 /* decCheckNumber -- check a number */
7928 /* dn is the number to check */
7929 /* returns 0 if the number is clean, or 1 otherwise */
7930 /* */
7931 /* The number is considered valid if it could be a result from some */
7932 /* operation in some valid context. */
7933 /* ------------------------------------------------------------------ */
7934 static Flag decCheckNumber(const decNumber *dn) {
7935 const Unit *up; /* work */
7936 uInt maxuint; /* .. */
7937 Int ae, d, digits; /* .. */
7938 Int emin, emax; /* .. */
7940 if (dn==NULL) { /* hopeless */
7941 #if DECTRACE
7942 /* this one not DECVERB as standard tests include NULL */
7943 printf("Reference to decNumber is NULL.\n");
7944 #endif
7945 return 1;}
7947 /* check special values */
7948 if (dn->bits & DECSPECIAL) {
7949 if (dn->exponent!=0) {
7950 #if DECTRACE || DECVERB
7951 printf("Exponent %ld (not 0) for a special value [%02x].\n",
7952 (LI)dn->exponent, dn->bits);
7953 #endif
7954 return 1;}
7956 /* 2003.09.08: NaNs may now have coefficients, so next tests Inf only */
7957 if (decNumberIsInfinite(dn)) {
7958 if (dn->digits!=1) {
7959 #if DECTRACE || DECVERB
7960 printf("Digits %ld (not 1) for an infinity.\n", (LI)dn->digits);
7961 #endif
7962 return 1;}
7963 if (*dn->lsu!=0) {
7964 #if DECTRACE || DECVERB
7965 printf("LSU %ld (not 0) for an infinity.\n", (LI)*dn->lsu);
7966 #endif
7967 decDumpAr('I', dn->lsu, D2U(dn->digits));
7968 return 1;}
7969 } /* Inf */
7970 /* 2002.12.26: negative NaNs can now appear through proposed IEEE */
7971 /* concrete formats (decimal64, etc.). */
7972 return 0;
7975 /* check the coefficient */
7976 if (dn->digits<1 || dn->digits>DECNUMMAXP) {
7977 #if DECTRACE || DECVERB
7978 printf("Digits %ld in number.\n", (LI)dn->digits);
7979 #endif
7980 return 1;}
7982 d=dn->digits;
7984 for (up=dn->lsu; d>0; up++) {
7985 if (d>DECDPUN) maxuint=DECDPUNMAX;
7986 else { /* reached the msu */
7987 maxuint=powers[d]-1;
7988 if (dn->digits>1 && *up<powers[d-1]) {
7989 #if DECTRACE || DECVERB
7990 printf("Leading 0 in number.\n");
7991 decNumberShow(dn);
7992 #endif
7993 return 1;}
7995 if (*up>maxuint) {
7996 #if DECTRACE || DECVERB
7997 printf("Bad Unit [%08lx] in %ld-digit number at offset %ld [maxuint %ld].\n",
7998 (LI)*up, (LI)dn->digits, (LI)(up-dn->lsu), (LI)maxuint);
7999 #endif
8000 return 1;}
8001 d-=DECDPUN;
8004 /* check the exponent. Note that input operands can have exponents */
8005 /* which are out of the set->emin/set->emax and set->digits range */
8006 /* (just as they can have more digits than set->digits). */
8007 ae=dn->exponent+dn->digits-1; /* adjusted exponent */
8008 emax=DECNUMMAXE;
8009 emin=DECNUMMINE;
8010 digits=DECNUMMAXP;
8011 if (ae<emin-(digits-1)) {
8012 #if DECTRACE || DECVERB
8013 printf("Adjusted exponent underflow [%ld].\n", (LI)ae);
8014 decNumberShow(dn);
8015 #endif
8016 return 1;}
8017 if (ae>+emax) {
8018 #if DECTRACE || DECVERB
8019 printf("Adjusted exponent overflow [%ld].\n", (LI)ae);
8020 decNumberShow(dn);
8021 #endif
8022 return 1;}
8024 return 0; /* it's OK */
8025 } /* decCheckNumber */
8027 /* ------------------------------------------------------------------ */
8028 /* decCheckInexact -- check a normal finite inexact result has digits */
8029 /* dn is the number to check */
8030 /* set is the context (for status and precision) */
8031 /* sets Invalid operation, etc., if some digits are missing */
8032 /* [this check is not made for DECSUBSET compilation or when */
8033 /* subnormal is not set] */
8034 /* ------------------------------------------------------------------ */
8035 static void decCheckInexact(const decNumber *dn, decContext *set) {
8036 #if !DECSUBSET && DECEXTFLAG
8037 if ((set->status & (DEC_Inexact|DEC_Subnormal))==DEC_Inexact
8038 && (set->digits!=dn->digits) && !(dn->bits & DECSPECIAL)) {
8039 #if DECTRACE || DECVERB
8040 printf("Insufficient digits [%ld] on normal Inexact result.\n",
8041 (LI)dn->digits);
8042 decNumberShow(dn);
8043 #endif
8044 decContextSetStatus(set, DEC_Invalid_operation);
8046 #else
8047 /* next is a noop for quiet compiler */
8048 if (dn!=NULL && dn->digits==0) set->status|=DEC_Invalid_operation;
8049 #endif
8050 return;
8051 } /* decCheckInexact */
8052 #endif
8054 #if DECALLOC
8055 #undef malloc
8056 #undef free
8057 /* ------------------------------------------------------------------ */
8058 /* decMalloc -- accountable allocation routine */
8059 /* n is the number of bytes to allocate */
8060 /* */
8061 /* Semantics is the same as the stdlib malloc routine, but bytes */
8062 /* allocated are accounted for globally, and corruption fences are */
8063 /* added before and after the 'actual' storage. */
8064 /* ------------------------------------------------------------------ */
8065 /* This routine allocates storage with an extra twelve bytes; 8 are */
8066 /* at the start and hold: */
8067 /* 0-3 the original length requested */
8068 /* 4-7 buffer corruption detection fence (DECFENCE, x4) */
8069 /* The 4 bytes at the end also hold a corruption fence (DECFENCE, x4) */
8070 /* ------------------------------------------------------------------ */
8071 static void *decMalloc(size_t n) {
8072 uInt size=n+12; /* true size */
8073 void *alloc; /* -> allocated storage */
8074 uInt *j; /* work */
8075 uByte *b, *b0; /* .. */
8077 alloc=malloc(size); /* -> allocated storage */
8078 if (alloc==NULL) return NULL; /* out of strorage */
8079 b0=(uByte *)alloc; /* as bytes */
8080 decAllocBytes+=n; /* account for storage */
8081 j=(uInt *)alloc; /* -> first four bytes */
8082 *j=n; /* save n */
8083 /* printf(" alloc ++ dAB: %ld (%d)\n", decAllocBytes, n); */
8084 for (b=b0+4; b<b0+8; b++) *b=DECFENCE;
8085 for (b=b0+n+8; b<b0+n+12; b++) *b=DECFENCE;
8086 return b0+8; /* -> play area */
8087 } /* decMalloc */
8089 /* ------------------------------------------------------------------ */
8090 /* decFree -- accountable free routine */
8091 /* alloc is the storage to free */
8092 /* */
8093 /* Semantics is the same as the stdlib malloc routine, except that */
8094 /* the global storage accounting is updated and the fences are */
8095 /* checked to ensure that no routine has written 'out of bounds'. */
8096 /* ------------------------------------------------------------------ */
8097 /* This routine first checks that the fences have not been corrupted. */
8098 /* It then frees the storage using the 'truw' storage address (that */
8099 /* is, offset by 8). */
8100 /* ------------------------------------------------------------------ */
8101 static void decFree(void *alloc) {
8102 uInt *j, n; /* pointer, original length */
8103 uByte *b, *b0; /* work */
8105 if (alloc==NULL) return; /* allowed; it's a nop */
8106 b0=(uByte *)alloc; /* as bytes */
8107 b0-=8; /* -> true start of storage */
8108 j=(uInt *)b0; /* -> first four bytes */
8109 n=*j; /* lift */
8110 for (b=b0+4; b<b0+8; b++) if (*b!=DECFENCE)
8111 printf("=== Corrupt byte [%02x] at offset %d from %ld ===\n", *b,
8112 b-b0-8, (Int)b0);
8113 for (b=b0+n+8; b<b0+n+12; b++) if (*b!=DECFENCE)
8114 printf("=== Corrupt byte [%02x] at offset +%d from %ld, n=%ld ===\n", *b,
8115 b-b0-8, (Int)b0, n);
8116 free(b0); /* drop the storage */
8117 decAllocBytes-=n; /* account for storage */
8118 /* printf(" free -- dAB: %d (%d)\n", decAllocBytes, -n); */
8119 } /* decFree */
8120 #define malloc(a) decMalloc(a)
8121 #define free(a) decFree(a)
8122 #endif