spapr_pci: fix device tree props for MSI/MSI-X
[qemu/ar7.git] / libdecnumber / decNumber.c
blobca1412f30b5521982eb2f1589958fd8844d747c0
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 "libdecnumber/dconfig.h"
174 #include "libdecnumber/decNumber.h"
175 #include "libdecnumber/decNumberLocal.h"
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 decNumber *decNumberFromInt64(decNumber *dn, int64_t in)
441 uint64_t unsig = in;
442 if (in < 0) {
443 unsig = -unsig;
446 decNumberFromUInt64(dn, unsig);
447 if (in < 0) {
448 dn->bits = DECNEG; /* sign needed */
450 return dn;
451 } /* decNumberFromInt64 */
453 decNumber *decNumberFromUInt64(decNumber *dn, uint64_t uin)
455 Unit *up; /* work pointer */
456 decNumberZero(dn); /* clean */
457 if (uin == 0) {
458 return dn; /* [or decGetDigits bad call] */
460 for (up = dn->lsu; uin > 0; up++) {
461 *up = (Unit)(uin % (DECDPUNMAX + 1));
462 uin = uin / (DECDPUNMAX + 1);
464 dn->digits = decGetDigits(dn->lsu, up-dn->lsu);
465 return dn;
466 } /* decNumberFromUInt64 */
468 /* ------------------------------------------------------------------ */
469 /* to-int64 -- conversion to int64 */
470 /* */
471 /* dn is the decNumber to convert. dn is assumed to have been */
472 /* rounded to a floating point integer value. */
473 /* set is the context for reporting errors */
474 /* returns the converted decNumber, or 0 if Invalid is set */
475 /* */
476 /* Invalid is set if the decNumber is a NaN, Infinite or is out of */
477 /* range for a signed 64 bit integer. */
478 /* ------------------------------------------------------------------ */
480 int64_t decNumberIntegralToInt64(const decNumber *dn, decContext *set)
482 if (decNumberIsSpecial(dn) || (dn->exponent < 0) ||
483 (dn->digits + dn->exponent > 19)) {
484 goto Invalid;
485 } else {
486 int64_t d; /* work */
487 const Unit *up; /* .. */
488 uint64_t hi = 0;
489 up = dn->lsu; /* -> lsu */
491 for (d = 1; d <= dn->digits; up++, d += DECDPUN) {
492 uint64_t prev = hi;
493 hi += *up * powers[d-1];
494 if ((hi < prev) || (hi > INT64_MAX)) {
495 goto Invalid;
499 uint64_t prev = hi;
500 hi *= (uint64_t)powers[dn->exponent];
501 if ((hi < prev) || (hi > INT64_MAX)) {
502 goto Invalid;
504 return (decNumberIsNegative(dn)) ? -((int64_t)hi) : (int64_t)hi;
507 Invalid:
508 decContextSetStatus(set, DEC_Invalid_operation);
509 return 0;
510 } /* decNumberIntegralToInt64 */
513 /* ------------------------------------------------------------------ */
514 /* to-scientific-string -- conversion to numeric string */
515 /* to-engineering-string -- conversion to numeric string */
516 /* */
517 /* decNumberToString(dn, string); */
518 /* decNumberToEngString(dn, string); */
519 /* */
520 /* dn is the decNumber to convert */
521 /* string is the string where the result will be laid out */
522 /* */
523 /* string must be at least dn->digits+14 characters long */
524 /* */
525 /* No error is possible, and no status can be set. */
526 /* ------------------------------------------------------------------ */
527 char * decNumberToString(const decNumber *dn, char *string){
528 decToString(dn, string, 0);
529 return string;
530 } /* DecNumberToString */
532 char * decNumberToEngString(const decNumber *dn, char *string){
533 decToString(dn, string, 1);
534 return string;
535 } /* DecNumberToEngString */
537 /* ------------------------------------------------------------------ */
538 /* to-number -- conversion from numeric string */
539 /* */
540 /* decNumberFromString -- convert string to decNumber */
541 /* dn -- the number structure to fill */
542 /* chars[] -- the string to convert ('\0' terminated) */
543 /* set -- the context used for processing any error, */
544 /* determining the maximum precision available */
545 /* (set.digits), determining the maximum and minimum */
546 /* exponent (set.emax and set.emin), determining if */
547 /* extended values are allowed, and checking the */
548 /* rounding mode if overflow occurs or rounding is */
549 /* needed. */
550 /* */
551 /* The length of the coefficient and the size of the exponent are */
552 /* checked by this routine, so the correct error (Underflow or */
553 /* Overflow) can be reported or rounding applied, as necessary. */
554 /* */
555 /* If bad syntax is detected, the result will be a quiet NaN. */
556 /* ------------------------------------------------------------------ */
557 decNumber * decNumberFromString(decNumber *dn, const char chars[],
558 decContext *set) {
559 Int exponent=0; /* working exponent [assume 0] */
560 uByte bits=0; /* working flags [assume +ve] */
561 Unit *res; /* where result will be built */
562 Unit resbuff[SD2U(DECBUFFER+9)];/* local buffer in case need temporary */
563 /* [+9 allows for ln() constants] */
564 Unit *allocres=NULL; /* -> allocated result, iff allocated */
565 Int d=0; /* count of digits found in decimal part */
566 const char *dotchar=NULL; /* where dot was found */
567 const char *cfirst=chars; /* -> first character of decimal part */
568 const char *last=NULL; /* -> last digit of decimal part */
569 const char *c; /* work */
570 Unit *up; /* .. */
571 #if DECDPUN>1
572 Int cut, out; /* .. */
573 #endif
574 Int residue; /* rounding residue */
575 uInt status=0; /* error code */
577 #if DECCHECK
578 if (decCheckOperands(DECUNRESU, DECUNUSED, DECUNUSED, set))
579 return decNumberZero(dn);
580 #endif
582 do { /* status & malloc protection */
583 for (c=chars;; c++) { /* -> input character */
584 if (*c>='0' && *c<='9') { /* test for Arabic digit */
585 last=c;
586 d++; /* count of real digits */
587 continue; /* still in decimal part */
589 if (*c=='.' && dotchar==NULL) { /* first '.' */
590 dotchar=c; /* record offset into decimal part */
591 if (c==cfirst) cfirst++; /* first digit must follow */
592 continue;}
593 if (c==chars) { /* first in string... */
594 if (*c=='-') { /* valid - sign */
595 cfirst++;
596 bits=DECNEG;
597 continue;}
598 if (*c=='+') { /* valid + sign */
599 cfirst++;
600 continue;}
602 /* *c is not a digit, or a valid +, -, or '.' */
603 break;
604 } /* c */
606 if (last==NULL) { /* no digits yet */
607 status=DEC_Conversion_syntax;/* assume the worst */
608 if (*c=='\0') break; /* and no more to come... */
609 #if DECSUBSET
610 /* if subset then infinities and NaNs are not allowed */
611 if (!set->extended) break; /* hopeless */
612 #endif
613 /* Infinities and NaNs are possible, here */
614 if (dotchar!=NULL) break; /* .. unless had a dot */
615 decNumberZero(dn); /* be optimistic */
616 if (decBiStr(c, "infinity", "INFINITY")
617 || decBiStr(c, "inf", "INF")) {
618 dn->bits=bits | DECINF;
619 status=0; /* is OK */
620 break; /* all done */
622 /* a NaN expected */
623 /* 2003.09.10 NaNs are now permitted to have a sign */
624 dn->bits=bits | DECNAN; /* assume simple NaN */
625 if (*c=='s' || *c=='S') { /* looks like an sNaN */
626 c++;
627 dn->bits=bits | DECSNAN;
629 if (*c!='n' && *c!='N') break; /* check caseless "NaN" */
630 c++;
631 if (*c!='a' && *c!='A') break; /* .. */
632 c++;
633 if (*c!='n' && *c!='N') break; /* .. */
634 c++;
635 /* now either nothing, or nnnn payload, expected */
636 /* -> start of integer and skip leading 0s [including plain 0] */
637 for (cfirst=c; *cfirst=='0';) cfirst++;
638 if (*cfirst=='\0') { /* "NaN" or "sNaN", maybe with all 0s */
639 status=0; /* it's good */
640 break; /* .. */
642 /* something other than 0s; setup last and d as usual [no dots] */
643 for (c=cfirst;; c++, d++) {
644 if (*c<'0' || *c>'9') break; /* test for Arabic digit */
645 last=c;
647 if (*c!='\0') break; /* not all digits */
648 if (d>set->digits-1) {
649 /* [NB: payload in a decNumber can be full length unless */
650 /* clamped, in which case can only be digits-1] */
651 if (set->clamp) break;
652 if (d>set->digits) break;
653 } /* too many digits? */
654 /* good; drop through to convert the integer to coefficient */
655 status=0; /* syntax is OK */
656 bits=dn->bits; /* for copy-back */
657 } /* last==NULL */
659 else if (*c!='\0') { /* more to process... */
660 /* had some digits; exponent is only valid sequence now */
661 Flag nege; /* 1=negative exponent */
662 const char *firstexp; /* -> first significant exponent digit */
663 status=DEC_Conversion_syntax;/* assume the worst */
664 if (*c!='e' && *c!='E') break;
665 /* Found 'e' or 'E' -- now process explicit exponent */
666 /* 1998.07.11: sign no longer required */
667 nege=0;
668 c++; /* to (possible) sign */
669 if (*c=='-') {nege=1; c++;}
670 else if (*c=='+') c++;
671 if (*c=='\0') break;
673 for (; *c=='0' && *(c+1)!='\0';) c++; /* strip insignificant zeros */
674 firstexp=c; /* save exponent digit place */
675 for (; ;c++) {
676 if (*c<'0' || *c>'9') break; /* not a digit */
677 exponent=X10(exponent)+(Int)*c-(Int)'0';
678 } /* c */
679 /* if not now on a '\0', *c must not be a digit */
680 if (*c!='\0') break;
682 /* (this next test must be after the syntax checks) */
683 /* if it was too long the exponent may have wrapped, so check */
684 /* carefully and set it to a certain overflow if wrap possible */
685 if (c>=firstexp+9+1) {
686 if (c>firstexp+9+1 || *firstexp>'1') exponent=DECNUMMAXE*2;
687 /* [up to 1999999999 is OK, for example 1E-1000000998] */
689 if (nege) exponent=-exponent; /* was negative */
690 status=0; /* is OK */
691 } /* stuff after digits */
693 /* Here when whole string has been inspected; syntax is good */
694 /* cfirst->first digit (never dot), last->last digit (ditto) */
696 /* strip leading zeros/dot [leave final 0 if all 0's] */
697 if (*cfirst=='0') { /* [cfirst has stepped over .] */
698 for (c=cfirst; c<last; c++, cfirst++) {
699 if (*c=='.') continue; /* ignore dots */
700 if (*c!='0') break; /* non-zero found */
701 d--; /* 0 stripped */
702 } /* c */
703 #if DECSUBSET
704 /* make a rapid exit for easy zeros if !extended */
705 if (*cfirst=='0' && !set->extended) {
706 decNumberZero(dn); /* clean result */
707 break; /* [could be return] */
709 #endif
710 } /* at least one leading 0 */
712 /* Handle decimal point... */
713 if (dotchar!=NULL && dotchar<last) /* non-trailing '.' found? */
714 exponent-=(last-dotchar); /* adjust exponent */
715 /* [we can now ignore the .] */
717 /* OK, the digits string is good. Assemble in the decNumber, or in */
718 /* a temporary units array if rounding is needed */
719 if (d<=set->digits) res=dn->lsu; /* fits into supplied decNumber */
720 else { /* rounding needed */
721 Int needbytes=D2U(d)*sizeof(Unit);/* bytes needed */
722 res=resbuff; /* assume use local buffer */
723 if (needbytes>(Int)sizeof(resbuff)) { /* too big for local */
724 allocres=(Unit *)malloc(needbytes);
725 if (allocres==NULL) {status|=DEC_Insufficient_storage; break;}
726 res=allocres;
729 /* res now -> number lsu, buffer, or allocated storage for Unit array */
731 /* Place the coefficient into the selected Unit array */
732 /* [this is often 70% of the cost of this function when DECDPUN>1] */
733 #if DECDPUN>1
734 out=0; /* accumulator */
735 up=res+D2U(d)-1; /* -> msu */
736 cut=d-(up-res)*DECDPUN; /* digits in top unit */
737 for (c=cfirst;; c++) { /* along the digits */
738 if (*c=='.') continue; /* ignore '.' [don't decrement cut] */
739 out=X10(out)+(Int)*c-(Int)'0';
740 if (c==last) break; /* done [never get to trailing '.'] */
741 cut--;
742 if (cut>0) continue; /* more for this unit */
743 *up=(Unit)out; /* write unit */
744 up--; /* prepare for unit below.. */
745 cut=DECDPUN; /* .. */
746 out=0; /* .. */
747 } /* c */
748 *up=(Unit)out; /* write lsu */
750 #else
751 /* DECDPUN==1 */
752 up=res; /* -> lsu */
753 for (c=last; c>=cfirst; c--) { /* over each character, from least */
754 if (*c=='.') continue; /* ignore . [don't step up] */
755 *up=(Unit)((Int)*c-(Int)'0');
756 up++;
757 } /* c */
758 #endif
760 dn->bits=bits;
761 dn->exponent=exponent;
762 dn->digits=d;
764 /* if not in number (too long) shorten into the number */
765 if (d>set->digits) {
766 residue=0;
767 decSetCoeff(dn, set, res, d, &residue, &status);
768 /* always check for overflow or subnormal and round as needed */
769 decFinalize(dn, set, &residue, &status);
771 else { /* no rounding, but may still have overflow or subnormal */
772 /* [these tests are just for performance; finalize repeats them] */
773 if ((dn->exponent-1<set->emin-dn->digits)
774 || (dn->exponent-1>set->emax-set->digits)) {
775 residue=0;
776 decFinalize(dn, set, &residue, &status);
779 /* decNumberShow(dn); */
780 } while(0); /* [for break] */
782 if (allocres!=NULL) free(allocres); /* drop any storage used */
783 if (status!=0) decStatus(dn, status, set);
784 return dn;
785 } /* decNumberFromString */
787 /* ================================================================== */
788 /* Operators */
789 /* ================================================================== */
791 /* ------------------------------------------------------------------ */
792 /* decNumberAbs -- absolute value operator */
793 /* */
794 /* This computes C = abs(A) */
795 /* */
796 /* res is C, the result. C may be A */
797 /* rhs is A */
798 /* set is the context */
799 /* */
800 /* See also decNumberCopyAbs for a quiet bitwise version of this. */
801 /* C must have space for set->digits digits. */
802 /* ------------------------------------------------------------------ */
803 /* This has the same effect as decNumberPlus unless A is negative, */
804 /* in which case it has the same effect as decNumberMinus. */
805 /* ------------------------------------------------------------------ */
806 decNumber * decNumberAbs(decNumber *res, const decNumber *rhs,
807 decContext *set) {
808 decNumber dzero; /* for 0 */
809 uInt status=0; /* accumulator */
811 #if DECCHECK
812 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
813 #endif
815 decNumberZero(&dzero); /* set 0 */
816 dzero.exponent=rhs->exponent; /* [no coefficient expansion] */
817 decAddOp(res, &dzero, rhs, set, (uByte)(rhs->bits & DECNEG), &status);
818 if (status!=0) decStatus(res, status, set);
819 #if DECCHECK
820 decCheckInexact(res, set);
821 #endif
822 return res;
823 } /* decNumberAbs */
825 /* ------------------------------------------------------------------ */
826 /* decNumberAdd -- add two Numbers */
827 /* */
828 /* This computes C = A + B */
829 /* */
830 /* res is C, the result. C may be A and/or B (e.g., X=X+X) */
831 /* lhs is A */
832 /* rhs is B */
833 /* set is the context */
834 /* */
835 /* C must have space for set->digits digits. */
836 /* ------------------------------------------------------------------ */
837 /* This just calls the routine shared with Subtract */
838 decNumber * decNumberAdd(decNumber *res, const decNumber *lhs,
839 const decNumber *rhs, decContext *set) {
840 uInt status=0; /* accumulator */
841 decAddOp(res, lhs, rhs, set, 0, &status);
842 if (status!=0) decStatus(res, status, set);
843 #if DECCHECK
844 decCheckInexact(res, set);
845 #endif
846 return res;
847 } /* decNumberAdd */
849 /* ------------------------------------------------------------------ */
850 /* decNumberAnd -- AND two Numbers, digitwise */
851 /* */
852 /* This computes C = A & B */
853 /* */
854 /* res is C, the result. C may be A and/or B (e.g., X=X&X) */
855 /* lhs is A */
856 /* rhs is B */
857 /* set is the context (used for result length and error report) */
858 /* */
859 /* C must have space for set->digits digits. */
860 /* */
861 /* Logical function restrictions apply (see above); a NaN is */
862 /* returned with Invalid_operation if a restriction is violated. */
863 /* ------------------------------------------------------------------ */
864 decNumber * decNumberAnd(decNumber *res, const decNumber *lhs,
865 const decNumber *rhs, decContext *set) {
866 const Unit *ua, *ub; /* -> operands */
867 const Unit *msua, *msub; /* -> operand msus */
868 Unit *uc, *msuc; /* -> result and its msu */
869 Int msudigs; /* digits in res msu */
870 #if DECCHECK
871 if (decCheckOperands(res, lhs, rhs, set)) return res;
872 #endif
874 if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
875 || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
876 decStatus(res, DEC_Invalid_operation, set);
877 return res;
880 /* operands are valid */
881 ua=lhs->lsu; /* bottom-up */
882 ub=rhs->lsu; /* .. */
883 uc=res->lsu; /* .. */
884 msua=ua+D2U(lhs->digits)-1; /* -> msu of lhs */
885 msub=ub+D2U(rhs->digits)-1; /* -> msu of rhs */
886 msuc=uc+D2U(set->digits)-1; /* -> msu of result */
887 msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */
888 for (; uc<=msuc; ua++, ub++, uc++) { /* Unit loop */
889 Unit a, b; /* extract units */
890 if (ua>msua) a=0;
891 else a=*ua;
892 if (ub>msub) b=0;
893 else b=*ub;
894 *uc=0; /* can now write back */
895 if (a|b) { /* maybe 1 bits to examine */
896 Int i, j;
897 *uc=0; /* can now write back */
898 /* This loop could be unrolled and/or use BIN2BCD tables */
899 for (i=0; i<DECDPUN; i++) {
900 if (a&b&1) *uc=*uc+(Unit)powers[i]; /* effect AND */
901 j=a%10;
902 a=a/10;
903 j|=b%10;
904 b=b/10;
905 if (j>1) {
906 decStatus(res, DEC_Invalid_operation, set);
907 return res;
909 if (uc==msuc && i==msudigs-1) break; /* just did final digit */
910 } /* each digit */
911 } /* both OK */
912 } /* each unit */
913 /* [here uc-1 is the msu of the result] */
914 res->digits=decGetDigits(res->lsu, uc-res->lsu);
915 res->exponent=0; /* integer */
916 res->bits=0; /* sign=0 */
917 return res; /* [no status to set] */
918 } /* decNumberAnd */
920 /* ------------------------------------------------------------------ */
921 /* decNumberCompare -- compare two Numbers */
922 /* */
923 /* This computes C = A ? B */
924 /* */
925 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
926 /* lhs is A */
927 /* rhs is B */
928 /* set is the context */
929 /* */
930 /* C must have space for one digit (or NaN). */
931 /* ------------------------------------------------------------------ */
932 decNumber * decNumberCompare(decNumber *res, const decNumber *lhs,
933 const decNumber *rhs, decContext *set) {
934 uInt status=0; /* accumulator */
935 decCompareOp(res, lhs, rhs, set, COMPARE, &status);
936 if (status!=0) decStatus(res, status, set);
937 return res;
938 } /* decNumberCompare */
940 /* ------------------------------------------------------------------ */
941 /* decNumberCompareSignal -- compare, signalling on all NaNs */
942 /* */
943 /* This computes C = A ? B */
944 /* */
945 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
946 /* lhs is A */
947 /* rhs is B */
948 /* set is the context */
949 /* */
950 /* C must have space for one digit (or NaN). */
951 /* ------------------------------------------------------------------ */
952 decNumber * decNumberCompareSignal(decNumber *res, const decNumber *lhs,
953 const decNumber *rhs, decContext *set) {
954 uInt status=0; /* accumulator */
955 decCompareOp(res, lhs, rhs, set, COMPSIG, &status);
956 if (status!=0) decStatus(res, status, set);
957 return res;
958 } /* decNumberCompareSignal */
960 /* ------------------------------------------------------------------ */
961 /* decNumberCompareTotal -- compare two Numbers, using total ordering */
962 /* */
963 /* This computes C = A ? B, under total ordering */
964 /* */
965 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
966 /* lhs is A */
967 /* rhs is B */
968 /* set is the context */
969 /* */
970 /* C must have space for one digit; the result will always be one of */
971 /* -1, 0, or 1. */
972 /* ------------------------------------------------------------------ */
973 decNumber * decNumberCompareTotal(decNumber *res, const decNumber *lhs,
974 const decNumber *rhs, decContext *set) {
975 uInt status=0; /* accumulator */
976 decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
977 if (status!=0) decStatus(res, status, set);
978 return res;
979 } /* decNumberCompareTotal */
981 /* ------------------------------------------------------------------ */
982 /* decNumberCompareTotalMag -- compare, total ordering of magnitudes */
983 /* */
984 /* This computes C = |A| ? |B|, under total ordering */
985 /* */
986 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
987 /* lhs is A */
988 /* rhs is B */
989 /* set is the context */
990 /* */
991 /* C must have space for one digit; the result will always be one of */
992 /* -1, 0, or 1. */
993 /* ------------------------------------------------------------------ */
994 decNumber * decNumberCompareTotalMag(decNumber *res, const decNumber *lhs,
995 const decNumber *rhs, decContext *set) {
996 uInt status=0; /* accumulator */
997 uInt needbytes; /* for space calculations */
998 decNumber bufa[D2N(DECBUFFER+1)];/* +1 in case DECBUFFER=0 */
999 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
1000 decNumber bufb[D2N(DECBUFFER+1)];
1001 decNumber *allocbufb=NULL; /* -> allocated bufb, iff allocated */
1002 decNumber *a, *b; /* temporary pointers */
1004 #if DECCHECK
1005 if (decCheckOperands(res, lhs, rhs, set)) return res;
1006 #endif
1008 do { /* protect allocated storage */
1009 /* if either is negative, take a copy and absolute */
1010 if (decNumberIsNegative(lhs)) { /* lhs<0 */
1011 a=bufa;
1012 needbytes=sizeof(decNumber)+(D2U(lhs->digits)-1)*sizeof(Unit);
1013 if (needbytes>sizeof(bufa)) { /* need malloc space */
1014 allocbufa=(decNumber *)malloc(needbytes);
1015 if (allocbufa==NULL) { /* hopeless -- abandon */
1016 status|=DEC_Insufficient_storage;
1017 break;}
1018 a=allocbufa; /* use the allocated space */
1020 decNumberCopy(a, lhs); /* copy content */
1021 a->bits&=~DECNEG; /* .. and clear the sign */
1022 lhs=a; /* use copy from here on */
1024 if (decNumberIsNegative(rhs)) { /* rhs<0 */
1025 b=bufb;
1026 needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
1027 if (needbytes>sizeof(bufb)) { /* need malloc space */
1028 allocbufb=(decNumber *)malloc(needbytes);
1029 if (allocbufb==NULL) { /* hopeless -- abandon */
1030 status|=DEC_Insufficient_storage;
1031 break;}
1032 b=allocbufb; /* use the allocated space */
1034 decNumberCopy(b, rhs); /* copy content */
1035 b->bits&=~DECNEG; /* .. and clear the sign */
1036 rhs=b; /* use copy from here on */
1038 decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
1039 } while(0); /* end protected */
1041 if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */
1042 if (allocbufb!=NULL) free(allocbufb); /* .. */
1043 if (status!=0) decStatus(res, status, set);
1044 return res;
1045 } /* decNumberCompareTotalMag */
1047 /* ------------------------------------------------------------------ */
1048 /* decNumberDivide -- divide one number by another */
1049 /* */
1050 /* This computes C = A / B */
1051 /* */
1052 /* res is C, the result. C may be A and/or B (e.g., X=X/X) */
1053 /* lhs is A */
1054 /* rhs is B */
1055 /* set is the context */
1056 /* */
1057 /* C must have space for set->digits digits. */
1058 /* ------------------------------------------------------------------ */
1059 decNumber * decNumberDivide(decNumber *res, const decNumber *lhs,
1060 const decNumber *rhs, decContext *set) {
1061 uInt status=0; /* accumulator */
1062 decDivideOp(res, lhs, rhs, set, DIVIDE, &status);
1063 if (status!=0) decStatus(res, status, set);
1064 #if DECCHECK
1065 decCheckInexact(res, set);
1066 #endif
1067 return res;
1068 } /* decNumberDivide */
1070 /* ------------------------------------------------------------------ */
1071 /* decNumberDivideInteger -- divide and return integer quotient */
1072 /* */
1073 /* This computes C = A # B, where # is the integer divide operator */
1074 /* */
1075 /* res is C, the result. C may be A and/or B (e.g., X=X#X) */
1076 /* lhs is A */
1077 /* rhs is B */
1078 /* set is the context */
1079 /* */
1080 /* C must have space for set->digits digits. */
1081 /* ------------------------------------------------------------------ */
1082 decNumber * decNumberDivideInteger(decNumber *res, const decNumber *lhs,
1083 const decNumber *rhs, decContext *set) {
1084 uInt status=0; /* accumulator */
1085 decDivideOp(res, lhs, rhs, set, DIVIDEINT, &status);
1086 if (status!=0) decStatus(res, status, set);
1087 return res;
1088 } /* decNumberDivideInteger */
1090 /* ------------------------------------------------------------------ */
1091 /* decNumberExp -- exponentiation */
1092 /* */
1093 /* This computes C = exp(A) */
1094 /* */
1095 /* res is C, the result. C may be A */
1096 /* rhs is A */
1097 /* set is the context; note that rounding mode has no effect */
1098 /* */
1099 /* C must have space for set->digits digits. */
1100 /* */
1101 /* Mathematical function restrictions apply (see above); a NaN is */
1102 /* returned with Invalid_operation if a restriction is violated. */
1103 /* */
1104 /* Finite results will always be full precision and Inexact, except */
1105 /* when A is a zero or -Infinity (giving 1 or 0 respectively). */
1106 /* */
1107 /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */
1108 /* almost always be correctly rounded, but may be up to 1 ulp in */
1109 /* error in rare cases. */
1110 /* ------------------------------------------------------------------ */
1111 /* This is a wrapper for decExpOp which can handle the slightly wider */
1112 /* (double) range needed by Ln (which has to be able to calculate */
1113 /* exp(-a) where a can be the tiniest number (Ntiny). */
1114 /* ------------------------------------------------------------------ */
1115 decNumber * decNumberExp(decNumber *res, const decNumber *rhs,
1116 decContext *set) {
1117 uInt status=0; /* accumulator */
1118 #if DECSUBSET
1119 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */
1120 #endif
1122 #if DECCHECK
1123 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1124 #endif
1126 /* Check restrictions; these restrictions ensure that if h=8 (see */
1127 /* decExpOp) then the result will either overflow or underflow to 0. */
1128 /* Other math functions restrict the input range, too, for inverses. */
1129 /* If not violated then carry out the operation. */
1130 if (!decCheckMath(rhs, set, &status)) do { /* protect allocation */
1131 #if DECSUBSET
1132 if (!set->extended) {
1133 /* reduce operand and set lostDigits status, as needed */
1134 if (rhs->digits>set->digits) {
1135 allocrhs=decRoundOperand(rhs, set, &status);
1136 if (allocrhs==NULL) break;
1137 rhs=allocrhs;
1140 #endif
1141 decExpOp(res, rhs, set, &status);
1142 } while(0); /* end protected */
1144 #if DECSUBSET
1145 if (allocrhs !=NULL) free(allocrhs); /* drop any storage used */
1146 #endif
1147 /* apply significant status */
1148 if (status!=0) decStatus(res, status, set);
1149 #if DECCHECK
1150 decCheckInexact(res, set);
1151 #endif
1152 return res;
1153 } /* decNumberExp */
1155 /* ------------------------------------------------------------------ */
1156 /* decNumberFMA -- fused multiply add */
1157 /* */
1158 /* This computes D = (A * B) + C with only one rounding */
1159 /* */
1160 /* res is D, the result. D may be A or B or C (e.g., X=FMA(X,X,X)) */
1161 /* lhs is A */
1162 /* rhs is B */
1163 /* fhs is C [far hand side] */
1164 /* set is the context */
1165 /* */
1166 /* Mathematical function restrictions apply (see above); a NaN is */
1167 /* returned with Invalid_operation if a restriction is violated. */
1168 /* */
1169 /* C must have space for set->digits digits. */
1170 /* ------------------------------------------------------------------ */
1171 decNumber * decNumberFMA(decNumber *res, const decNumber *lhs,
1172 const decNumber *rhs, const decNumber *fhs,
1173 decContext *set) {
1174 uInt status=0; /* accumulator */
1175 decContext dcmul; /* context for the multiplication */
1176 uInt needbytes; /* for space calculations */
1177 decNumber bufa[D2N(DECBUFFER*2+1)];
1178 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
1179 decNumber *acc; /* accumulator pointer */
1180 decNumber dzero; /* work */
1182 #if DECCHECK
1183 if (decCheckOperands(res, lhs, rhs, set)) return res;
1184 if (decCheckOperands(res, fhs, DECUNUSED, set)) return res;
1185 #endif
1187 do { /* protect allocated storage */
1188 #if DECSUBSET
1189 if (!set->extended) { /* [undefined if subset] */
1190 status|=DEC_Invalid_operation;
1191 break;}
1192 #endif
1193 /* Check math restrictions [these ensure no overflow or underflow] */
1194 if ((!decNumberIsSpecial(lhs) && decCheckMath(lhs, set, &status))
1195 || (!decNumberIsSpecial(rhs) && decCheckMath(rhs, set, &status))
1196 || (!decNumberIsSpecial(fhs) && decCheckMath(fhs, set, &status))) break;
1197 /* set up context for multiply */
1198 dcmul=*set;
1199 dcmul.digits=lhs->digits+rhs->digits; /* just enough */
1200 /* [The above may be an over-estimate for subset arithmetic, but that's OK] */
1201 dcmul.emax=DEC_MAX_EMAX; /* effectively unbounded .. */
1202 dcmul.emin=DEC_MIN_EMIN; /* [thanks to Math restrictions] */
1203 /* set up decNumber space to receive the result of the multiply */
1204 acc=bufa; /* may fit */
1205 needbytes=sizeof(decNumber)+(D2U(dcmul.digits)-1)*sizeof(Unit);
1206 if (needbytes>sizeof(bufa)) { /* need malloc space */
1207 allocbufa=(decNumber *)malloc(needbytes);
1208 if (allocbufa==NULL) { /* hopeless -- abandon */
1209 status|=DEC_Insufficient_storage;
1210 break;}
1211 acc=allocbufa; /* use the allocated space */
1213 /* multiply with extended range and necessary precision */
1214 /*printf("emin=%ld\n", dcmul.emin); */
1215 decMultiplyOp(acc, lhs, rhs, &dcmul, &status);
1216 /* Only Invalid operation (from sNaN or Inf * 0) is possible in */
1217 /* status; if either is seen than ignore fhs (in case it is */
1218 /* another sNaN) and set acc to NaN unless we had an sNaN */
1219 /* [decMultiplyOp leaves that to caller] */
1220 /* Note sNaN has to go through addOp to shorten payload if */
1221 /* necessary */
1222 if ((status&DEC_Invalid_operation)!=0) {
1223 if (!(status&DEC_sNaN)) { /* but be true invalid */
1224 decNumberZero(res); /* acc not yet set */
1225 res->bits=DECNAN;
1226 break;
1228 decNumberZero(&dzero); /* make 0 (any non-NaN would do) */
1229 fhs=&dzero; /* use that */
1231 #if DECCHECK
1232 else { /* multiply was OK */
1233 if (status!=0) printf("Status=%08lx after FMA multiply\n", status);
1235 #endif
1236 /* add the third operand and result -> res, and all is done */
1237 decAddOp(res, acc, fhs, set, 0, &status);
1238 } while(0); /* end protected */
1240 if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */
1241 if (status!=0) decStatus(res, status, set);
1242 #if DECCHECK
1243 decCheckInexact(res, set);
1244 #endif
1245 return res;
1246 } /* decNumberFMA */
1248 /* ------------------------------------------------------------------ */
1249 /* decNumberInvert -- invert a Number, digitwise */
1250 /* */
1251 /* This computes C = ~A */
1252 /* */
1253 /* res is C, the result. C may be A (e.g., X=~X) */
1254 /* rhs is A */
1255 /* set is the context (used for result length and error report) */
1256 /* */
1257 /* C must have space for set->digits digits. */
1258 /* */
1259 /* Logical function restrictions apply (see above); a NaN is */
1260 /* returned with Invalid_operation if a restriction is violated. */
1261 /* ------------------------------------------------------------------ */
1262 decNumber * decNumberInvert(decNumber *res, const decNumber *rhs,
1263 decContext *set) {
1264 const Unit *ua, *msua; /* -> operand and its msu */
1265 Unit *uc, *msuc; /* -> result and its msu */
1266 Int msudigs; /* digits in res msu */
1267 #if DECCHECK
1268 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1269 #endif
1271 if (rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
1272 decStatus(res, DEC_Invalid_operation, set);
1273 return res;
1275 /* operand is valid */
1276 ua=rhs->lsu; /* bottom-up */
1277 uc=res->lsu; /* .. */
1278 msua=ua+D2U(rhs->digits)-1; /* -> msu of rhs */
1279 msuc=uc+D2U(set->digits)-1; /* -> msu of result */
1280 msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */
1281 for (; uc<=msuc; ua++, uc++) { /* Unit loop */
1282 Unit a; /* extract unit */
1283 Int i, j; /* work */
1284 if (ua>msua) a=0;
1285 else a=*ua;
1286 *uc=0; /* can now write back */
1287 /* always need to examine all bits in rhs */
1288 /* This loop could be unrolled and/or use BIN2BCD tables */
1289 for (i=0; i<DECDPUN; i++) {
1290 if ((~a)&1) *uc=*uc+(Unit)powers[i]; /* effect INVERT */
1291 j=a%10;
1292 a=a/10;
1293 if (j>1) {
1294 decStatus(res, DEC_Invalid_operation, set);
1295 return res;
1297 if (uc==msuc && i==msudigs-1) break; /* just did final digit */
1298 } /* each digit */
1299 } /* each unit */
1300 /* [here uc-1 is the msu of the result] */
1301 res->digits=decGetDigits(res->lsu, uc-res->lsu);
1302 res->exponent=0; /* integer */
1303 res->bits=0; /* sign=0 */
1304 return res; /* [no status to set] */
1305 } /* decNumberInvert */
1307 /* ------------------------------------------------------------------ */
1308 /* decNumberLn -- natural logarithm */
1309 /* */
1310 /* This computes C = ln(A) */
1311 /* */
1312 /* res is C, the result. C may be A */
1313 /* rhs is A */
1314 /* set is the context; note that rounding mode has no effect */
1315 /* */
1316 /* C must have space for set->digits digits. */
1317 /* */
1318 /* Notable cases: */
1319 /* A<0 -> Invalid */
1320 /* A=0 -> -Infinity (Exact) */
1321 /* A=+Infinity -> +Infinity (Exact) */
1322 /* A=1 exactly -> 0 (Exact) */
1323 /* */
1324 /* Mathematical function restrictions apply (see above); a NaN is */
1325 /* returned with Invalid_operation if a restriction is violated. */
1326 /* */
1327 /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */
1328 /* almost always be correctly rounded, but may be up to 1 ulp in */
1329 /* error in rare cases. */
1330 /* ------------------------------------------------------------------ */
1331 /* This is a wrapper for decLnOp which can handle the slightly wider */
1332 /* (+11) range needed by Ln, Log10, etc. (which may have to be able */
1333 /* to calculate at p+e+2). */
1334 /* ------------------------------------------------------------------ */
1335 decNumber * decNumberLn(decNumber *res, const decNumber *rhs,
1336 decContext *set) {
1337 uInt status=0; /* accumulator */
1338 #if DECSUBSET
1339 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */
1340 #endif
1342 #if DECCHECK
1343 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1344 #endif
1346 /* Check restrictions; this is a math function; if not violated */
1347 /* then carry out the operation. */
1348 if (!decCheckMath(rhs, set, &status)) do { /* protect allocation */
1349 #if DECSUBSET
1350 if (!set->extended) {
1351 /* reduce operand and set lostDigits status, as needed */
1352 if (rhs->digits>set->digits) {
1353 allocrhs=decRoundOperand(rhs, set, &status);
1354 if (allocrhs==NULL) break;
1355 rhs=allocrhs;
1357 /* special check in subset for rhs=0 */
1358 if (ISZERO(rhs)) { /* +/- zeros -> error */
1359 status|=DEC_Invalid_operation;
1360 break;}
1361 } /* extended=0 */
1362 #endif
1363 decLnOp(res, rhs, set, &status);
1364 } while(0); /* end protected */
1366 #if DECSUBSET
1367 if (allocrhs !=NULL) free(allocrhs); /* drop any storage used */
1368 #endif
1369 /* apply significant status */
1370 if (status!=0) decStatus(res, status, set);
1371 #if DECCHECK
1372 decCheckInexact(res, set);
1373 #endif
1374 return res;
1375 } /* decNumberLn */
1377 /* ------------------------------------------------------------------ */
1378 /* decNumberLogB - get adjusted exponent, by 754r rules */
1379 /* */
1380 /* This computes C = adjustedexponent(A) */
1381 /* */
1382 /* res is C, the result. C may be A */
1383 /* rhs is A */
1384 /* set is the context, used only for digits and status */
1385 /* */
1386 /* C must have space for 10 digits (A might have 10**9 digits and */
1387 /* an exponent of +999999999, or one digit and an exponent of */
1388 /* -1999999999). */
1389 /* */
1390 /* This returns the adjusted exponent of A after (in theory) padding */
1391 /* with zeros on the right to set->digits digits while keeping the */
1392 /* same value. The exponent is not limited by emin/emax. */
1393 /* */
1394 /* Notable cases: */
1395 /* A<0 -> Use |A| */
1396 /* A=0 -> -Infinity (Division by zero) */
1397 /* A=Infinite -> +Infinity (Exact) */
1398 /* A=1 exactly -> 0 (Exact) */
1399 /* NaNs are propagated as usual */
1400 /* ------------------------------------------------------------------ */
1401 decNumber * decNumberLogB(decNumber *res, const decNumber *rhs,
1402 decContext *set) {
1403 uInt status=0; /* accumulator */
1405 #if DECCHECK
1406 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1407 #endif
1409 /* NaNs as usual; Infinities return +Infinity; 0->oops */
1410 if (decNumberIsNaN(rhs)) decNaNs(res, rhs, NULL, set, &status);
1411 else if (decNumberIsInfinite(rhs)) decNumberCopyAbs(res, rhs);
1412 else if (decNumberIsZero(rhs)) {
1413 decNumberZero(res); /* prepare for Infinity */
1414 res->bits=DECNEG|DECINF; /* -Infinity */
1415 status|=DEC_Division_by_zero; /* as per 754r */
1417 else { /* finite non-zero */
1418 Int ae=rhs->exponent+rhs->digits-1; /* adjusted exponent */
1419 decNumberFromInt32(res, ae); /* lay it out */
1422 if (status!=0) decStatus(res, status, set);
1423 return res;
1424 } /* decNumberLogB */
1426 /* ------------------------------------------------------------------ */
1427 /* decNumberLog10 -- logarithm in base 10 */
1428 /* */
1429 /* This computes C = log10(A) */
1430 /* */
1431 /* res is C, the result. C may be A */
1432 /* rhs is A */
1433 /* set is the context; note that rounding mode has no effect */
1434 /* */
1435 /* C must have space for set->digits digits. */
1436 /* */
1437 /* Notable cases: */
1438 /* A<0 -> Invalid */
1439 /* A=0 -> -Infinity (Exact) */
1440 /* A=+Infinity -> +Infinity (Exact) */
1441 /* A=10**n (if n is an integer) -> n (Exact) */
1442 /* */
1443 /* Mathematical function restrictions apply (see above); a NaN is */
1444 /* returned with Invalid_operation if a restriction is violated. */
1445 /* */
1446 /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */
1447 /* almost always be correctly rounded, but may be up to 1 ulp in */
1448 /* error in rare cases. */
1449 /* ------------------------------------------------------------------ */
1450 /* This calculates ln(A)/ln(10) using appropriate precision. For */
1451 /* ln(A) this is the max(p, rhs->digits + t) + 3, where p is the */
1452 /* requested digits and t is the number of digits in the exponent */
1453 /* (maximum 6). For ln(10) it is p + 3; this is often handled by the */
1454 /* fastpath in decLnOp. The final division is done to the requested */
1455 /* precision. */
1456 /* ------------------------------------------------------------------ */
1457 decNumber * decNumberLog10(decNumber *res, const decNumber *rhs,
1458 decContext *set) {
1459 uInt status=0, ignore=0; /* status accumulators */
1460 uInt needbytes; /* for space calculations */
1461 Int p; /* working precision */
1462 Int t; /* digits in exponent of A */
1464 /* buffers for a and b working decimals */
1465 /* (adjustment calculator, same size) */
1466 decNumber bufa[D2N(DECBUFFER+2)];
1467 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
1468 decNumber *a=bufa; /* temporary a */
1469 decNumber bufb[D2N(DECBUFFER+2)];
1470 decNumber *allocbufb=NULL; /* -> allocated bufb, iff allocated */
1471 decNumber *b=bufb; /* temporary b */
1472 decNumber bufw[D2N(10)]; /* working 2-10 digit number */
1473 decNumber *w=bufw; /* .. */
1474 #if DECSUBSET
1475 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */
1476 #endif
1478 decContext aset; /* working context */
1480 #if DECCHECK
1481 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1482 #endif
1484 /* Check restrictions; this is a math function; if not violated */
1485 /* then carry out the operation. */
1486 if (!decCheckMath(rhs, set, &status)) do { /* protect malloc */
1487 #if DECSUBSET
1488 if (!set->extended) {
1489 /* reduce operand and set lostDigits status, as needed */
1490 if (rhs->digits>set->digits) {
1491 allocrhs=decRoundOperand(rhs, set, &status);
1492 if (allocrhs==NULL) break;
1493 rhs=allocrhs;
1495 /* special check in subset for rhs=0 */
1496 if (ISZERO(rhs)) { /* +/- zeros -> error */
1497 status|=DEC_Invalid_operation;
1498 break;}
1499 } /* extended=0 */
1500 #endif
1502 decContextDefault(&aset, DEC_INIT_DECIMAL64); /* clean context */
1504 /* handle exact powers of 10; only check if +ve finite */
1505 if (!(rhs->bits&(DECNEG|DECSPECIAL)) && !ISZERO(rhs)) {
1506 Int residue=0; /* (no residue) */
1507 uInt copystat=0; /* clean status */
1509 /* round to a single digit... */
1510 aset.digits=1;
1511 decCopyFit(w, rhs, &aset, &residue, &copystat); /* copy & shorten */
1512 /* if exact and the digit is 1, rhs is a power of 10 */
1513 if (!(copystat&DEC_Inexact) && w->lsu[0]==1) {
1514 /* the exponent, conveniently, is the power of 10; making */
1515 /* this the result needs a little care as it might not fit, */
1516 /* so first convert it into the working number, and then move */
1517 /* to res */
1518 decNumberFromInt32(w, w->exponent);
1519 residue=0;
1520 decCopyFit(res, w, set, &residue, &status); /* copy & round */
1521 decFinish(res, set, &residue, &status); /* cleanup/set flags */
1522 break;
1523 } /* not a power of 10 */
1524 } /* not a candidate for exact */
1526 /* simplify the information-content calculation to use 'total */
1527 /* number of digits in a, including exponent' as compared to the */
1528 /* requested digits, as increasing this will only rarely cost an */
1529 /* iteration in ln(a) anyway */
1530 t=6; /* it can never be >6 */
1532 /* allocate space when needed... */
1533 p=(rhs->digits+t>set->digits?rhs->digits+t:set->digits)+3;
1534 needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1535 if (needbytes>sizeof(bufa)) { /* need malloc space */
1536 allocbufa=(decNumber *)malloc(needbytes);
1537 if (allocbufa==NULL) { /* hopeless -- abandon */
1538 status|=DEC_Insufficient_storage;
1539 break;}
1540 a=allocbufa; /* use the allocated space */
1542 aset.digits=p; /* as calculated */
1543 aset.emax=DEC_MAX_MATH; /* usual bounds */
1544 aset.emin=-DEC_MAX_MATH; /* .. */
1545 aset.clamp=0; /* and no concrete format */
1546 decLnOp(a, rhs, &aset, &status); /* a=ln(rhs) */
1548 /* skip the division if the result so far is infinite, NaN, or */
1549 /* zero, or there was an error; note NaN from sNaN needs copy */
1550 if (status&DEC_NaNs && !(status&DEC_sNaN)) break;
1551 if (a->bits&DECSPECIAL || ISZERO(a)) {
1552 decNumberCopy(res, a); /* [will fit] */
1553 break;}
1555 /* for ln(10) an extra 3 digits of precision are needed */
1556 p=set->digits+3;
1557 needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1558 if (needbytes>sizeof(bufb)) { /* need malloc space */
1559 allocbufb=(decNumber *)malloc(needbytes);
1560 if (allocbufb==NULL) { /* hopeless -- abandon */
1561 status|=DEC_Insufficient_storage;
1562 break;}
1563 b=allocbufb; /* use the allocated space */
1565 decNumberZero(w); /* set up 10... */
1566 #if DECDPUN==1
1567 w->lsu[1]=1; w->lsu[0]=0; /* .. */
1568 #else
1569 w->lsu[0]=10; /* .. */
1570 #endif
1571 w->digits=2; /* .. */
1573 aset.digits=p;
1574 decLnOp(b, w, &aset, &ignore); /* b=ln(10) */
1576 aset.digits=set->digits; /* for final divide */
1577 decDivideOp(res, a, b, &aset, DIVIDE, &status); /* into result */
1578 } while(0); /* [for break] */
1580 if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */
1581 if (allocbufb!=NULL) free(allocbufb); /* .. */
1582 #if DECSUBSET
1583 if (allocrhs !=NULL) free(allocrhs); /* .. */
1584 #endif
1585 /* apply significant status */
1586 if (status!=0) decStatus(res, status, set);
1587 #if DECCHECK
1588 decCheckInexact(res, set);
1589 #endif
1590 return res;
1591 } /* decNumberLog10 */
1593 /* ------------------------------------------------------------------ */
1594 /* decNumberMax -- compare two Numbers and return the maximum */
1595 /* */
1596 /* This computes C = A ? B, returning the maximum by 754R rules */
1597 /* */
1598 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
1599 /* lhs is A */
1600 /* rhs is B */
1601 /* set is the context */
1602 /* */
1603 /* C must have space for set->digits digits. */
1604 /* ------------------------------------------------------------------ */
1605 decNumber * decNumberMax(decNumber *res, const decNumber *lhs,
1606 const decNumber *rhs, decContext *set) {
1607 uInt status=0; /* accumulator */
1608 decCompareOp(res, lhs, rhs, set, COMPMAX, &status);
1609 if (status!=0) decStatus(res, status, set);
1610 #if DECCHECK
1611 decCheckInexact(res, set);
1612 #endif
1613 return res;
1614 } /* decNumberMax */
1616 /* ------------------------------------------------------------------ */
1617 /* decNumberMaxMag -- compare and return the maximum by magnitude */
1618 /* */
1619 /* This computes C = A ? B, returning the maximum by 754R rules */
1620 /* */
1621 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
1622 /* lhs is A */
1623 /* rhs is B */
1624 /* set is the context */
1625 /* */
1626 /* C must have space for set->digits digits. */
1627 /* ------------------------------------------------------------------ */
1628 decNumber * decNumberMaxMag(decNumber *res, const decNumber *lhs,
1629 const decNumber *rhs, decContext *set) {
1630 uInt status=0; /* accumulator */
1631 decCompareOp(res, lhs, rhs, set, COMPMAXMAG, &status);
1632 if (status!=0) decStatus(res, status, set);
1633 #if DECCHECK
1634 decCheckInexact(res, set);
1635 #endif
1636 return res;
1637 } /* decNumberMaxMag */
1639 /* ------------------------------------------------------------------ */
1640 /* decNumberMin -- compare two Numbers and return the minimum */
1641 /* */
1642 /* This computes C = A ? B, returning the minimum by 754R rules */
1643 /* */
1644 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
1645 /* lhs is A */
1646 /* rhs is B */
1647 /* set is the context */
1648 /* */
1649 /* C must have space for set->digits digits. */
1650 /* ------------------------------------------------------------------ */
1651 decNumber * decNumberMin(decNumber *res, const decNumber *lhs,
1652 const decNumber *rhs, decContext *set) {
1653 uInt status=0; /* accumulator */
1654 decCompareOp(res, lhs, rhs, set, COMPMIN, &status);
1655 if (status!=0) decStatus(res, status, set);
1656 #if DECCHECK
1657 decCheckInexact(res, set);
1658 #endif
1659 return res;
1660 } /* decNumberMin */
1662 /* ------------------------------------------------------------------ */
1663 /* decNumberMinMag -- compare and return the minimum by magnitude */
1664 /* */
1665 /* This computes C = A ? B, returning the minimum by 754R rules */
1666 /* */
1667 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
1668 /* lhs is A */
1669 /* rhs is B */
1670 /* set is the context */
1671 /* */
1672 /* C must have space for set->digits digits. */
1673 /* ------------------------------------------------------------------ */
1674 decNumber * decNumberMinMag(decNumber *res, const decNumber *lhs,
1675 const decNumber *rhs, decContext *set) {
1676 uInt status=0; /* accumulator */
1677 decCompareOp(res, lhs, rhs, set, COMPMINMAG, &status);
1678 if (status!=0) decStatus(res, status, set);
1679 #if DECCHECK
1680 decCheckInexact(res, set);
1681 #endif
1682 return res;
1683 } /* decNumberMinMag */
1685 /* ------------------------------------------------------------------ */
1686 /* decNumberMinus -- prefix minus operator */
1687 /* */
1688 /* This computes C = 0 - A */
1689 /* */
1690 /* res is C, the result. C may be A */
1691 /* rhs is A */
1692 /* set is the context */
1693 /* */
1694 /* See also decNumberCopyNegate for a quiet bitwise version of this. */
1695 /* C must have space for set->digits digits. */
1696 /* ------------------------------------------------------------------ */
1697 /* Simply use AddOp for the subtract, which will do the necessary. */
1698 /* ------------------------------------------------------------------ */
1699 decNumber * decNumberMinus(decNumber *res, const decNumber *rhs,
1700 decContext *set) {
1701 decNumber dzero;
1702 uInt status=0; /* accumulator */
1704 #if DECCHECK
1705 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1706 #endif
1708 decNumberZero(&dzero); /* make 0 */
1709 dzero.exponent=rhs->exponent; /* [no coefficient expansion] */
1710 decAddOp(res, &dzero, rhs, set, DECNEG, &status);
1711 if (status!=0) decStatus(res, status, set);
1712 #if DECCHECK
1713 decCheckInexact(res, set);
1714 #endif
1715 return res;
1716 } /* decNumberMinus */
1718 /* ------------------------------------------------------------------ */
1719 /* decNumberNextMinus -- next towards -Infinity */
1720 /* */
1721 /* This computes C = A - infinitesimal, rounded towards -Infinity */
1722 /* */
1723 /* res is C, the result. C may be A */
1724 /* rhs is A */
1725 /* set is the context */
1726 /* */
1727 /* This is a generalization of 754r NextDown. */
1728 /* ------------------------------------------------------------------ */
1729 decNumber * decNumberNextMinus(decNumber *res, const decNumber *rhs,
1730 decContext *set) {
1731 decNumber dtiny; /* constant */
1732 decContext workset=*set; /* work */
1733 uInt status=0; /* accumulator */
1734 #if DECCHECK
1735 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1736 #endif
1738 /* +Infinity is the special case */
1739 if ((rhs->bits&(DECINF|DECNEG))==DECINF) {
1740 decSetMaxValue(res, set); /* is +ve */
1741 /* there is no status to set */
1742 return res;
1744 decNumberZero(&dtiny); /* start with 0 */
1745 dtiny.lsu[0]=1; /* make number that is .. */
1746 dtiny.exponent=DEC_MIN_EMIN-1; /* .. smaller than tiniest */
1747 workset.round=DEC_ROUND_FLOOR;
1748 decAddOp(res, rhs, &dtiny, &workset, DECNEG, &status);
1749 status&=DEC_Invalid_operation|DEC_sNaN; /* only sNaN Invalid please */
1750 if (status!=0) decStatus(res, status, set);
1751 return res;
1752 } /* decNumberNextMinus */
1754 /* ------------------------------------------------------------------ */
1755 /* decNumberNextPlus -- next towards +Infinity */
1756 /* */
1757 /* This computes C = A + infinitesimal, rounded towards +Infinity */
1758 /* */
1759 /* res is C, the result. C may be A */
1760 /* rhs is A */
1761 /* set is the context */
1762 /* */
1763 /* This is a generalization of 754r NextUp. */
1764 /* ------------------------------------------------------------------ */
1765 decNumber * decNumberNextPlus(decNumber *res, const decNumber *rhs,
1766 decContext *set) {
1767 decNumber dtiny; /* constant */
1768 decContext workset=*set; /* work */
1769 uInt status=0; /* accumulator */
1770 #if DECCHECK
1771 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1772 #endif
1774 /* -Infinity is the special case */
1775 if ((rhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1776 decSetMaxValue(res, set);
1777 res->bits=DECNEG; /* negative */
1778 /* there is no status to set */
1779 return res;
1781 decNumberZero(&dtiny); /* start with 0 */
1782 dtiny.lsu[0]=1; /* make number that is .. */
1783 dtiny.exponent=DEC_MIN_EMIN-1; /* .. smaller than tiniest */
1784 workset.round=DEC_ROUND_CEILING;
1785 decAddOp(res, rhs, &dtiny, &workset, 0, &status);
1786 status&=DEC_Invalid_operation|DEC_sNaN; /* only sNaN Invalid please */
1787 if (status!=0) decStatus(res, status, set);
1788 return res;
1789 } /* decNumberNextPlus */
1791 /* ------------------------------------------------------------------ */
1792 /* decNumberNextToward -- next towards rhs */
1793 /* */
1794 /* This computes C = A +/- infinitesimal, rounded towards */
1795 /* +/-Infinity in the direction of B, as per 754r nextafter rules */
1796 /* */
1797 /* res is C, the result. C may be A or B. */
1798 /* lhs is A */
1799 /* rhs is B */
1800 /* set is the context */
1801 /* */
1802 /* This is a generalization of 754r NextAfter. */
1803 /* ------------------------------------------------------------------ */
1804 decNumber * decNumberNextToward(decNumber *res, const decNumber *lhs,
1805 const decNumber *rhs, decContext *set) {
1806 decNumber dtiny; /* constant */
1807 decContext workset=*set; /* work */
1808 Int result; /* .. */
1809 uInt status=0; /* accumulator */
1810 #if DECCHECK
1811 if (decCheckOperands(res, lhs, rhs, set)) return res;
1812 #endif
1814 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) {
1815 decNaNs(res, lhs, rhs, set, &status);
1817 else { /* Is numeric, so no chance of sNaN Invalid, etc. */
1818 result=decCompare(lhs, rhs, 0); /* sign matters */
1819 if (result==BADINT) status|=DEC_Insufficient_storage; /* rare */
1820 else { /* valid compare */
1821 if (result==0) decNumberCopySign(res, lhs, rhs); /* easy */
1822 else { /* differ: need NextPlus or NextMinus */
1823 uByte sub; /* add or subtract */
1824 if (result<0) { /* lhs<rhs, do nextplus */
1825 /* -Infinity is the special case */
1826 if ((lhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1827 decSetMaxValue(res, set);
1828 res->bits=DECNEG; /* negative */
1829 return res; /* there is no status to set */
1831 workset.round=DEC_ROUND_CEILING;
1832 sub=0; /* add, please */
1833 } /* plus */
1834 else { /* lhs>rhs, do nextminus */
1835 /* +Infinity is the special case */
1836 if ((lhs->bits&(DECINF|DECNEG))==DECINF) {
1837 decSetMaxValue(res, set);
1838 return res; /* there is no status to set */
1840 workset.round=DEC_ROUND_FLOOR;
1841 sub=DECNEG; /* subtract, please */
1842 } /* minus */
1843 decNumberZero(&dtiny); /* start with 0 */
1844 dtiny.lsu[0]=1; /* make number that is .. */
1845 dtiny.exponent=DEC_MIN_EMIN-1; /* .. smaller than tiniest */
1846 decAddOp(res, lhs, &dtiny, &workset, sub, &status); /* + or - */
1847 /* turn off exceptions if the result is a normal number */
1848 /* (including Nmin), otherwise let all status through */
1849 if (decNumberIsNormal(res, set)) status=0;
1850 } /* unequal */
1851 } /* compare OK */
1852 } /* numeric */
1853 if (status!=0) decStatus(res, status, set);
1854 return res;
1855 } /* decNumberNextToward */
1857 /* ------------------------------------------------------------------ */
1858 /* decNumberOr -- OR two Numbers, digitwise */
1859 /* */
1860 /* This computes C = A | B */
1861 /* */
1862 /* res is C, the result. C may be A and/or B (e.g., X=X|X) */
1863 /* lhs is A */
1864 /* rhs is B */
1865 /* set is the context (used for result length and error report) */
1866 /* */
1867 /* C must have space for set->digits digits. */
1868 /* */
1869 /* Logical function restrictions apply (see above); a NaN is */
1870 /* returned with Invalid_operation if a restriction is violated. */
1871 /* ------------------------------------------------------------------ */
1872 decNumber * decNumberOr(decNumber *res, const decNumber *lhs,
1873 const decNumber *rhs, decContext *set) {
1874 const Unit *ua, *ub; /* -> operands */
1875 const Unit *msua, *msub; /* -> operand msus */
1876 Unit *uc, *msuc; /* -> result and its msu */
1877 Int msudigs; /* digits in res msu */
1878 #if DECCHECK
1879 if (decCheckOperands(res, lhs, rhs, set)) return res;
1880 #endif
1882 if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
1883 || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
1884 decStatus(res, DEC_Invalid_operation, set);
1885 return res;
1887 /* operands are valid */
1888 ua=lhs->lsu; /* bottom-up */
1889 ub=rhs->lsu; /* .. */
1890 uc=res->lsu; /* .. */
1891 msua=ua+D2U(lhs->digits)-1; /* -> msu of lhs */
1892 msub=ub+D2U(rhs->digits)-1; /* -> msu of rhs */
1893 msuc=uc+D2U(set->digits)-1; /* -> msu of result */
1894 msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */
1895 for (; uc<=msuc; ua++, ub++, uc++) { /* Unit loop */
1896 Unit a, b; /* extract units */
1897 if (ua>msua) a=0;
1898 else a=*ua;
1899 if (ub>msub) b=0;
1900 else b=*ub;
1901 *uc=0; /* can now write back */
1902 if (a|b) { /* maybe 1 bits to examine */
1903 Int i, j;
1904 /* This loop could be unrolled and/or use BIN2BCD tables */
1905 for (i=0; i<DECDPUN; i++) {
1906 if ((a|b)&1) *uc=*uc+(Unit)powers[i]; /* effect OR */
1907 j=a%10;
1908 a=a/10;
1909 j|=b%10;
1910 b=b/10;
1911 if (j>1) {
1912 decStatus(res, DEC_Invalid_operation, set);
1913 return res;
1915 if (uc==msuc && i==msudigs-1) break; /* just did final digit */
1916 } /* each digit */
1917 } /* non-zero */
1918 } /* each unit */
1919 /* [here uc-1 is the msu of the result] */
1920 res->digits=decGetDigits(res->lsu, uc-res->lsu);
1921 res->exponent=0; /* integer */
1922 res->bits=0; /* sign=0 */
1923 return res; /* [no status to set] */
1924 } /* decNumberOr */
1926 /* ------------------------------------------------------------------ */
1927 /* decNumberPlus -- prefix plus operator */
1928 /* */
1929 /* This computes C = 0 + A */
1930 /* */
1931 /* res is C, the result. C may be A */
1932 /* rhs is A */
1933 /* set is the context */
1934 /* */
1935 /* See also decNumberCopy for a quiet bitwise version of this. */
1936 /* C must have space for set->digits digits. */
1937 /* ------------------------------------------------------------------ */
1938 /* This simply uses AddOp; Add will take fast path after preparing A. */
1939 /* Performance is a concern here, as this routine is often used to */
1940 /* check operands and apply rounding and overflow/underflow testing. */
1941 /* ------------------------------------------------------------------ */
1942 decNumber * decNumberPlus(decNumber *res, const decNumber *rhs,
1943 decContext *set) {
1944 decNumber dzero;
1945 uInt status=0; /* accumulator */
1946 #if DECCHECK
1947 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1948 #endif
1950 decNumberZero(&dzero); /* make 0 */
1951 dzero.exponent=rhs->exponent; /* [no coefficient expansion] */
1952 decAddOp(res, &dzero, rhs, set, 0, &status);
1953 if (status!=0) decStatus(res, status, set);
1954 #if DECCHECK
1955 decCheckInexact(res, set);
1956 #endif
1957 return res;
1958 } /* decNumberPlus */
1960 /* ------------------------------------------------------------------ */
1961 /* decNumberMultiply -- multiply two Numbers */
1962 /* */
1963 /* This computes C = A x B */
1964 /* */
1965 /* res is C, the result. C may be A and/or B (e.g., X=X+X) */
1966 /* lhs is A */
1967 /* rhs is B */
1968 /* set is the context */
1969 /* */
1970 /* C must have space for set->digits digits. */
1971 /* ------------------------------------------------------------------ */
1972 decNumber * decNumberMultiply(decNumber *res, const decNumber *lhs,
1973 const decNumber *rhs, decContext *set) {
1974 uInt status=0; /* accumulator */
1975 decMultiplyOp(res, lhs, rhs, set, &status);
1976 if (status!=0) decStatus(res, status, set);
1977 #if DECCHECK
1978 decCheckInexact(res, set);
1979 #endif
1980 return res;
1981 } /* decNumberMultiply */
1983 /* ------------------------------------------------------------------ */
1984 /* decNumberPower -- raise a number to a power */
1985 /* */
1986 /* This computes C = A ** B */
1987 /* */
1988 /* res is C, the result. C may be A and/or B (e.g., X=X**X) */
1989 /* lhs is A */
1990 /* rhs is B */
1991 /* set is the context */
1992 /* */
1993 /* C must have space for set->digits digits. */
1994 /* */
1995 /* Mathematical function restrictions apply (see above); a NaN is */
1996 /* returned with Invalid_operation if a restriction is violated. */
1997 /* */
1998 /* However, if 1999999997<=B<=999999999 and B is an integer then the */
1999 /* restrictions on A and the context are relaxed to the usual bounds, */
2000 /* for compatibility with the earlier (integer power only) version */
2001 /* of this function. */
2002 /* */
2003 /* When B is an integer, the result may be exact, even if rounded. */
2004 /* */
2005 /* The final result is rounded according to the context; it will */
2006 /* almost always be correctly rounded, but may be up to 1 ulp in */
2007 /* error in rare cases. */
2008 /* ------------------------------------------------------------------ */
2009 decNumber * decNumberPower(decNumber *res, const decNumber *lhs,
2010 const decNumber *rhs, decContext *set) {
2011 #if DECSUBSET
2012 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */
2013 decNumber *allocrhs=NULL; /* .., rhs */
2014 #endif
2015 decNumber *allocdac=NULL; /* -> allocated acc buffer, iff used */
2016 decNumber *allocinv=NULL; /* -> allocated 1/x buffer, iff used */
2017 Int reqdigits=set->digits; /* requested DIGITS */
2018 Int n; /* rhs in binary */
2019 Flag rhsint=0; /* 1 if rhs is an integer */
2020 Flag useint=0; /* 1 if can use integer calculation */
2021 Flag isoddint=0; /* 1 if rhs is an integer and odd */
2022 Int i; /* work */
2023 #if DECSUBSET
2024 Int dropped; /* .. */
2025 #endif
2026 uInt needbytes; /* buffer size needed */
2027 Flag seenbit; /* seen a bit while powering */
2028 Int residue=0; /* rounding residue */
2029 uInt status=0; /* accumulators */
2030 uByte bits=0; /* result sign if errors */
2031 decContext aset; /* working context */
2032 decNumber dnOne; /* work value 1... */
2033 /* local accumulator buffer [a decNumber, with digits+elength+1 digits] */
2034 decNumber dacbuff[D2N(DECBUFFER+9)];
2035 decNumber *dac=dacbuff; /* -> result accumulator */
2036 /* same again for possible 1/lhs calculation */
2037 decNumber invbuff[D2N(DECBUFFER+9)];
2039 #if DECCHECK
2040 if (decCheckOperands(res, lhs, rhs, set)) return res;
2041 #endif
2043 do { /* protect allocated storage */
2044 #if DECSUBSET
2045 if (!set->extended) { /* reduce operands and set status, as needed */
2046 if (lhs->digits>reqdigits) {
2047 alloclhs=decRoundOperand(lhs, set, &status);
2048 if (alloclhs==NULL) break;
2049 lhs=alloclhs;
2051 if (rhs->digits>reqdigits) {
2052 allocrhs=decRoundOperand(rhs, set, &status);
2053 if (allocrhs==NULL) break;
2054 rhs=allocrhs;
2057 #endif
2058 /* [following code does not require input rounding] */
2060 /* handle NaNs and rhs Infinity (lhs infinity is harder) */
2061 if (SPECIALARGS) {
2062 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) { /* NaNs */
2063 decNaNs(res, lhs, rhs, set, &status);
2064 break;}
2065 if (decNumberIsInfinite(rhs)) { /* rhs Infinity */
2066 Flag rhsneg=rhs->bits&DECNEG; /* save rhs sign */
2067 if (decNumberIsNegative(lhs) /* lhs<0 */
2068 && !decNumberIsZero(lhs)) /* .. */
2069 status|=DEC_Invalid_operation;
2070 else { /* lhs >=0 */
2071 decNumberZero(&dnOne); /* set up 1 */
2072 dnOne.lsu[0]=1;
2073 decNumberCompare(dac, lhs, &dnOne, set); /* lhs ? 1 */
2074 decNumberZero(res); /* prepare for 0/1/Infinity */
2075 if (decNumberIsNegative(dac)) { /* lhs<1 */
2076 if (rhsneg) res->bits|=DECINF; /* +Infinity [else is +0] */
2078 else if (dac->lsu[0]==0) { /* lhs=1 */
2079 /* 1**Infinity is inexact, so return fully-padded 1.0000 */
2080 Int shift=set->digits-1;
2081 *res->lsu=1; /* was 0, make int 1 */
2082 res->digits=decShiftToMost(res->lsu, 1, shift);
2083 res->exponent=-shift; /* make 1.0000... */
2084 status|=DEC_Inexact|DEC_Rounded; /* deemed inexact */
2086 else { /* lhs>1 */
2087 if (!rhsneg) res->bits|=DECINF; /* +Infinity [else is +0] */
2089 } /* lhs>=0 */
2090 break;}
2091 /* [lhs infinity drops through] */
2092 } /* specials */
2094 /* Original rhs may be an integer that fits and is in range */
2095 n=decGetInt(rhs);
2096 if (n!=BADINT) { /* it is an integer */
2097 rhsint=1; /* record the fact for 1**n */
2098 isoddint=(Flag)n&1; /* [works even if big] */
2099 if (n!=BIGEVEN && n!=BIGODD) /* can use integer path? */
2100 useint=1; /* looks good */
2103 if (decNumberIsNegative(lhs) /* -x .. */
2104 && isoddint) bits=DECNEG; /* .. to an odd power */
2106 /* handle LHS infinity */
2107 if (decNumberIsInfinite(lhs)) { /* [NaNs already handled] */
2108 uByte rbits=rhs->bits; /* save */
2109 decNumberZero(res); /* prepare */
2110 if (n==0) *res->lsu=1; /* [-]Inf**0 => 1 */
2111 else {
2112 /* -Inf**nonint -> error */
2113 if (!rhsint && decNumberIsNegative(lhs)) {
2114 status|=DEC_Invalid_operation; /* -Inf**nonint is error */
2115 break;}
2116 if (!(rbits & DECNEG)) bits|=DECINF; /* was not a **-n */
2117 /* [otherwise will be 0 or -0] */
2118 res->bits=bits;
2120 break;}
2122 /* similarly handle LHS zero */
2123 if (decNumberIsZero(lhs)) {
2124 if (n==0) { /* 0**0 => Error */
2125 #if DECSUBSET
2126 if (!set->extended) { /* [unless subset] */
2127 decNumberZero(res);
2128 *res->lsu=1; /* return 1 */
2129 break;}
2130 #endif
2131 status|=DEC_Invalid_operation;
2133 else { /* 0**x */
2134 uByte rbits=rhs->bits; /* save */
2135 if (rbits & DECNEG) { /* was a 0**(-n) */
2136 #if DECSUBSET
2137 if (!set->extended) { /* [bad if subset] */
2138 status|=DEC_Invalid_operation;
2139 break;}
2140 #endif
2141 bits|=DECINF;
2143 decNumberZero(res); /* prepare */
2144 /* [otherwise will be 0 or -0] */
2145 res->bits=bits;
2147 break;}
2149 /* here both lhs and rhs are finite; rhs==0 is handled in the */
2150 /* integer path. Next handle the non-integer cases */
2151 if (!useint) { /* non-integral rhs */
2152 /* any -ve lhs is bad, as is either operand or context out of */
2153 /* bounds */
2154 if (decNumberIsNegative(lhs)) {
2155 status|=DEC_Invalid_operation;
2156 break;}
2157 if (decCheckMath(lhs, set, &status)
2158 || decCheckMath(rhs, set, &status)) break; /* variable status */
2160 decContextDefault(&aset, DEC_INIT_DECIMAL64); /* clean context */
2161 aset.emax=DEC_MAX_MATH; /* usual bounds */
2162 aset.emin=-DEC_MAX_MATH; /* .. */
2163 aset.clamp=0; /* and no concrete format */
2165 /* calculate the result using exp(ln(lhs)*rhs), which can */
2166 /* all be done into the accumulator, dac. The precision needed */
2167 /* is enough to contain the full information in the lhs (which */
2168 /* is the total digits, including exponent), or the requested */
2169 /* precision, if larger, + 4; 6 is used for the exponent */
2170 /* maximum length, and this is also used when it is shorter */
2171 /* than the requested digits as it greatly reduces the >0.5 ulp */
2172 /* cases at little cost (because Ln doubles digits each */
2173 /* iteration so a few extra digits rarely causes an extra */
2174 /* iteration) */
2175 aset.digits=MAXI(lhs->digits, set->digits)+6+4;
2176 } /* non-integer rhs */
2178 else { /* rhs is in-range integer */
2179 if (n==0) { /* x**0 = 1 */
2180 /* (0**0 was handled above) */
2181 decNumberZero(res); /* result=1 */
2182 *res->lsu=1; /* .. */
2183 break;}
2184 /* rhs is a non-zero integer */
2185 if (n<0) n=-n; /* use abs(n) */
2187 aset=*set; /* clone the context */
2188 aset.round=DEC_ROUND_HALF_EVEN; /* internally use balanced */
2189 /* calculate the working DIGITS */
2190 aset.digits=reqdigits+(rhs->digits+rhs->exponent)+2;
2191 #if DECSUBSET
2192 if (!set->extended) aset.digits--; /* use classic precision */
2193 #endif
2194 /* it's an error if this is more than can be handled */
2195 if (aset.digits>DECNUMMAXP) {status|=DEC_Invalid_operation; break;}
2196 } /* integer path */
2198 /* aset.digits is the count of digits for the accumulator needed */
2199 /* if accumulator is too long for local storage, then allocate */
2200 needbytes=sizeof(decNumber)+(D2U(aset.digits)-1)*sizeof(Unit);
2201 /* [needbytes also used below if 1/lhs needed] */
2202 if (needbytes>sizeof(dacbuff)) {
2203 allocdac=(decNumber *)malloc(needbytes);
2204 if (allocdac==NULL) { /* hopeless -- abandon */
2205 status|=DEC_Insufficient_storage;
2206 break;}
2207 dac=allocdac; /* use the allocated space */
2209 /* here, aset is set up and accumulator is ready for use */
2211 if (!useint) { /* non-integral rhs */
2212 /* x ** y; special-case x=1 here as it will otherwise always */
2213 /* reduce to integer 1; decLnOp has a fastpath which detects */
2214 /* the case of x=1 */
2215 decLnOp(dac, lhs, &aset, &status); /* dac=ln(lhs) */
2216 /* [no error possible, as lhs 0 already handled] */
2217 if (ISZERO(dac)) { /* x==1, 1.0, etc. */
2218 /* need to return fully-padded 1.0000 etc., but rhsint->1 */
2219 *dac->lsu=1; /* was 0, make int 1 */
2220 if (!rhsint) { /* add padding */
2221 Int shift=set->digits-1;
2222 dac->digits=decShiftToMost(dac->lsu, 1, shift);
2223 dac->exponent=-shift; /* make 1.0000... */
2224 status|=DEC_Inexact|DEC_Rounded; /* deemed inexact */
2227 else {
2228 decMultiplyOp(dac, dac, rhs, &aset, &status); /* dac=dac*rhs */
2229 decExpOp(dac, dac, &aset, &status); /* dac=exp(dac) */
2231 /* and drop through for final rounding */
2232 } /* non-integer rhs */
2234 else { /* carry on with integer */
2235 decNumberZero(dac); /* acc=1 */
2236 *dac->lsu=1; /* .. */
2238 /* if a negative power the constant 1 is needed, and if not subset */
2239 /* invert the lhs now rather than inverting the result later */
2240 if (decNumberIsNegative(rhs)) { /* was a **-n [hence digits>0] */
2241 decNumber *inv=invbuff; /* assume use fixed buffer */
2242 decNumberCopy(&dnOne, dac); /* dnOne=1; [needed now or later] */
2243 #if DECSUBSET
2244 if (set->extended) { /* need to calculate 1/lhs */
2245 #endif
2246 /* divide lhs into 1, putting result in dac [dac=1/dac] */
2247 decDivideOp(dac, &dnOne, lhs, &aset, DIVIDE, &status);
2248 /* now locate or allocate space for the inverted lhs */
2249 if (needbytes>sizeof(invbuff)) {
2250 allocinv=(decNumber *)malloc(needbytes);
2251 if (allocinv==NULL) { /* hopeless -- abandon */
2252 status|=DEC_Insufficient_storage;
2253 break;}
2254 inv=allocinv; /* use the allocated space */
2256 /* [inv now points to big-enough buffer or allocated storage] */
2257 decNumberCopy(inv, dac); /* copy the 1/lhs */
2258 decNumberCopy(dac, &dnOne); /* restore acc=1 */
2259 lhs=inv; /* .. and go forward with new lhs */
2260 #if DECSUBSET
2262 #endif
2265 /* Raise-to-the-power loop... */
2266 seenbit=0; /* set once a 1-bit is encountered */
2267 for (i=1;;i++){ /* for each bit [top bit ignored] */
2268 /* abandon if had overflow or terminal underflow */
2269 if (status & (DEC_Overflow|DEC_Underflow)) { /* interesting? */
2270 if (status&DEC_Overflow || ISZERO(dac)) break;
2272 /* [the following two lines revealed an optimizer bug in a C++ */
2273 /* compiler, with symptom: 5**3 -> 25, when n=n+n was used] */
2274 n=n<<1; /* move next bit to testable position */
2275 if (n<0) { /* top bit is set */
2276 seenbit=1; /* OK, significant bit seen */
2277 decMultiplyOp(dac, dac, lhs, &aset, &status); /* dac=dac*x */
2279 if (i==31) break; /* that was the last bit */
2280 if (!seenbit) continue; /* no need to square 1 */
2281 decMultiplyOp(dac, dac, dac, &aset, &status); /* dac=dac*dac [square] */
2282 } /*i*/ /* 32 bits */
2284 /* complete internal overflow or underflow processing */
2285 if (status & (DEC_Overflow|DEC_Underflow)) {
2286 #if DECSUBSET
2287 /* If subset, and power was negative, reverse the kind of -erflow */
2288 /* [1/x not yet done] */
2289 if (!set->extended && decNumberIsNegative(rhs)) {
2290 if (status & DEC_Overflow)
2291 status^=DEC_Overflow | DEC_Underflow | DEC_Subnormal;
2292 else { /* trickier -- Underflow may or may not be set */
2293 status&=~(DEC_Underflow | DEC_Subnormal); /* [one or both] */
2294 status|=DEC_Overflow;
2297 #endif
2298 dac->bits=(dac->bits & ~DECNEG) | bits; /* force correct sign */
2299 /* round subnormals [to set.digits rather than aset.digits] */
2300 /* or set overflow result similarly as required */
2301 decFinalize(dac, set, &residue, &status);
2302 decNumberCopy(res, dac); /* copy to result (is now OK length) */
2303 break;
2306 #if DECSUBSET
2307 if (!set->extended && /* subset math */
2308 decNumberIsNegative(rhs)) { /* was a **-n [hence digits>0] */
2309 /* so divide result into 1 [dac=1/dac] */
2310 decDivideOp(dac, &dnOne, dac, &aset, DIVIDE, &status);
2312 #endif
2313 } /* rhs integer path */
2315 /* reduce result to the requested length and copy to result */
2316 decCopyFit(res, dac, set, &residue, &status);
2317 decFinish(res, set, &residue, &status); /* final cleanup */
2318 #if DECSUBSET
2319 if (!set->extended) decTrim(res, set, 0, &dropped); /* trailing zeros */
2320 #endif
2321 } while(0); /* end protected */
2323 if (allocdac!=NULL) free(allocdac); /* drop any storage used */
2324 if (allocinv!=NULL) free(allocinv); /* .. */
2325 #if DECSUBSET
2326 if (alloclhs!=NULL) free(alloclhs); /* .. */
2327 if (allocrhs!=NULL) free(allocrhs); /* .. */
2328 #endif
2329 if (status!=0) decStatus(res, status, set);
2330 #if DECCHECK
2331 decCheckInexact(res, set);
2332 #endif
2333 return res;
2334 } /* decNumberPower */
2336 /* ------------------------------------------------------------------ */
2337 /* decNumberQuantize -- force exponent to requested value */
2338 /* */
2339 /* This computes C = op(A, B), where op adjusts the coefficient */
2340 /* of C (by rounding or shifting) such that the exponent (-scale) */
2341 /* of C has exponent of B. The numerical value of C will equal A, */
2342 /* except for the effects of any rounding that occurred. */
2343 /* */
2344 /* res is C, the result. C may be A or B */
2345 /* lhs is A, the number to adjust */
2346 /* rhs is B, the number with exponent to match */
2347 /* set is the context */
2348 /* */
2349 /* C must have space for set->digits digits. */
2350 /* */
2351 /* Unless there is an error or the result is infinite, the exponent */
2352 /* after the operation is guaranteed to be equal to that of B. */
2353 /* ------------------------------------------------------------------ */
2354 decNumber * decNumberQuantize(decNumber *res, const decNumber *lhs,
2355 const decNumber *rhs, decContext *set) {
2356 uInt status=0; /* accumulator */
2357 decQuantizeOp(res, lhs, rhs, set, 1, &status);
2358 if (status!=0) decStatus(res, status, set);
2359 return res;
2360 } /* decNumberQuantize */
2362 /* ------------------------------------------------------------------ */
2363 /* decNumberReduce -- remove trailing zeros */
2364 /* */
2365 /* This computes C = 0 + A, and normalizes the result */
2366 /* */
2367 /* res is C, the result. C may be A */
2368 /* rhs is A */
2369 /* set is the context */
2370 /* */
2371 /* C must have space for set->digits digits. */
2372 /* ------------------------------------------------------------------ */
2373 /* Previously known as Normalize */
2374 decNumber * decNumberNormalize(decNumber *res, const decNumber *rhs,
2375 decContext *set) {
2376 return decNumberReduce(res, rhs, set);
2377 } /* decNumberNormalize */
2379 decNumber * decNumberReduce(decNumber *res, const decNumber *rhs,
2380 decContext *set) {
2381 #if DECSUBSET
2382 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */
2383 #endif
2384 uInt status=0; /* as usual */
2385 Int residue=0; /* as usual */
2386 Int dropped; /* work */
2388 #if DECCHECK
2389 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
2390 #endif
2392 do { /* protect allocated storage */
2393 #if DECSUBSET
2394 if (!set->extended) {
2395 /* reduce operand and set lostDigits status, as needed */
2396 if (rhs->digits>set->digits) {
2397 allocrhs=decRoundOperand(rhs, set, &status);
2398 if (allocrhs==NULL) break;
2399 rhs=allocrhs;
2402 #endif
2403 /* [following code does not require input rounding] */
2405 /* Infinities copy through; NaNs need usual treatment */
2406 if (decNumberIsNaN(rhs)) {
2407 decNaNs(res, rhs, NULL, set, &status);
2408 break;
2411 /* reduce result to the requested length and copy to result */
2412 decCopyFit(res, rhs, set, &residue, &status); /* copy & round */
2413 decFinish(res, set, &residue, &status); /* cleanup/set flags */
2414 decTrim(res, set, 1, &dropped); /* normalize in place */
2415 } while(0); /* end protected */
2417 #if DECSUBSET
2418 if (allocrhs !=NULL) free(allocrhs); /* .. */
2419 #endif
2420 if (status!=0) decStatus(res, status, set);/* then report status */
2421 return res;
2422 } /* decNumberReduce */
2424 /* ------------------------------------------------------------------ */
2425 /* decNumberRescale -- force exponent to requested value */
2426 /* */
2427 /* This computes C = op(A, B), where op adjusts the coefficient */
2428 /* of C (by rounding or shifting) such that the exponent (-scale) */
2429 /* of C has the value B. The numerical value of C will equal A, */
2430 /* except for the effects of any rounding that occurred. */
2431 /* */
2432 /* res is C, the result. C may be A or B */
2433 /* lhs is A, the number to adjust */
2434 /* rhs is B, the requested exponent */
2435 /* set is the context */
2436 /* */
2437 /* C must have space for set->digits digits. */
2438 /* */
2439 /* Unless there is an error or the result is infinite, the exponent */
2440 /* after the operation is guaranteed to be equal to B. */
2441 /* ------------------------------------------------------------------ */
2442 decNumber * decNumberRescale(decNumber *res, const decNumber *lhs,
2443 const decNumber *rhs, decContext *set) {
2444 uInt status=0; /* accumulator */
2445 decQuantizeOp(res, lhs, rhs, set, 0, &status);
2446 if (status!=0) decStatus(res, status, set);
2447 return res;
2448 } /* decNumberRescale */
2450 /* ------------------------------------------------------------------ */
2451 /* decNumberRemainder -- divide and return remainder */
2452 /* */
2453 /* This computes C = A % B */
2454 /* */
2455 /* res is C, the result. C may be A and/or B (e.g., X=X%X) */
2456 /* lhs is A */
2457 /* rhs is B */
2458 /* set is the context */
2459 /* */
2460 /* C must have space for set->digits digits. */
2461 /* ------------------------------------------------------------------ */
2462 decNumber * decNumberRemainder(decNumber *res, const decNumber *lhs,
2463 const decNumber *rhs, decContext *set) {
2464 uInt status=0; /* accumulator */
2465 decDivideOp(res, lhs, rhs, set, REMAINDER, &status);
2466 if (status!=0) decStatus(res, status, set);
2467 #if DECCHECK
2468 decCheckInexact(res, set);
2469 #endif
2470 return res;
2471 } /* decNumberRemainder */
2473 /* ------------------------------------------------------------------ */
2474 /* decNumberRemainderNear -- divide and return remainder from nearest */
2475 /* */
2476 /* This computes C = A % B, where % is the IEEE remainder operator */
2477 /* */
2478 /* res is C, the result. C may be A and/or B (e.g., X=X%X) */
2479 /* lhs is A */
2480 /* rhs is B */
2481 /* set is the context */
2482 /* */
2483 /* C must have space for set->digits digits. */
2484 /* ------------------------------------------------------------------ */
2485 decNumber * decNumberRemainderNear(decNumber *res, const decNumber *lhs,
2486 const decNumber *rhs, decContext *set) {
2487 uInt status=0; /* accumulator */
2488 decDivideOp(res, lhs, rhs, set, REMNEAR, &status);
2489 if (status!=0) decStatus(res, status, set);
2490 #if DECCHECK
2491 decCheckInexact(res, set);
2492 #endif
2493 return res;
2494 } /* decNumberRemainderNear */
2496 /* ------------------------------------------------------------------ */
2497 /* decNumberRotate -- rotate the coefficient of a Number left/right */
2498 /* */
2499 /* This computes C = A rot B (in base ten and rotating set->digits */
2500 /* digits). */
2501 /* */
2502 /* res is C, the result. C may be A and/or B (e.g., X=XrotX) */
2503 /* lhs is A */
2504 /* rhs is B, the number of digits to rotate (-ve to right) */
2505 /* set is the context */
2506 /* */
2507 /* The digits of the coefficient of A are rotated to the left (if B */
2508 /* is positive) or to the right (if B is negative) without adjusting */
2509 /* the exponent or the sign of A. If lhs->digits is less than */
2510 /* set->digits the coefficient is padded with zeros on the left */
2511 /* before the rotate. Any leading zeros in the result are removed */
2512 /* as usual. */
2513 /* */
2514 /* B must be an integer (q=0) and in the range -set->digits through */
2515 /* +set->digits. */
2516 /* C must have space for set->digits digits. */
2517 /* NaNs are propagated as usual. Infinities are unaffected (but */
2518 /* B must be valid). No status is set unless B is invalid or an */
2519 /* operand is an sNaN. */
2520 /* ------------------------------------------------------------------ */
2521 decNumber * decNumberRotate(decNumber *res, const decNumber *lhs,
2522 const decNumber *rhs, decContext *set) {
2523 uInt status=0; /* accumulator */
2524 Int rotate; /* rhs as an Int */
2526 #if DECCHECK
2527 if (decCheckOperands(res, lhs, rhs, set)) return res;
2528 #endif
2530 /* NaNs propagate as normal */
2531 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2532 decNaNs(res, lhs, rhs, set, &status);
2533 /* rhs must be an integer */
2534 else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2535 status=DEC_Invalid_operation;
2536 else { /* both numeric, rhs is an integer */
2537 rotate=decGetInt(rhs); /* [cannot fail] */
2538 if (rotate==BADINT /* something bad .. */
2539 || rotate==BIGODD || rotate==BIGEVEN /* .. very big .. */
2540 || abs(rotate)>set->digits) /* .. or out of range */
2541 status=DEC_Invalid_operation;
2542 else { /* rhs is OK */
2543 decNumberCopy(res, lhs);
2544 /* convert -ve rotate to equivalent positive rotation */
2545 if (rotate<0) rotate=set->digits+rotate;
2546 if (rotate!=0 && rotate!=set->digits /* zero or full rotation */
2547 && !decNumberIsInfinite(res)) { /* lhs was infinite */
2548 /* left-rotate to do; 0 < rotate < set->digits */
2549 uInt units, shift; /* work */
2550 uInt msudigits; /* digits in result msu */
2551 Unit *msu=res->lsu+D2U(res->digits)-1; /* current msu */
2552 Unit *msumax=res->lsu+D2U(set->digits)-1; /* rotation msu */
2553 for (msu++; msu<=msumax; msu++) *msu=0; /* ensure high units=0 */
2554 res->digits=set->digits; /* now full-length */
2555 msudigits=MSUDIGITS(res->digits); /* actual digits in msu */
2557 /* rotation here is done in-place, in three steps */
2558 /* 1. shift all to least up to one unit to unit-align final */
2559 /* lsd [any digits shifted out are rotated to the left, */
2560 /* abutted to the original msd (which may require split)] */
2561 /* */
2562 /* [if there are no whole units left to rotate, the */
2563 /* rotation is now complete] */
2564 /* */
2565 /* 2. shift to least, from below the split point only, so that */
2566 /* the final msd is in the right place in its Unit [any */
2567 /* digits shifted out will fit exactly in the current msu, */
2568 /* left aligned, no split required] */
2569 /* */
2570 /* 3. rotate all the units by reversing left part, right */
2571 /* part, and then whole */
2572 /* */
2573 /* example: rotate right 8 digits (2 units + 2), DECDPUN=3. */
2574 /* */
2575 /* start: 00a bcd efg hij klm npq */
2576 /* */
2577 /* 1a 000 0ab cde fgh|ijk lmn [pq saved] */
2578 /* 1b 00p qab cde fgh|ijk lmn */
2579 /* */
2580 /* 2a 00p qab cde fgh|00i jkl [mn saved] */
2581 /* 2b mnp qab cde fgh|00i jkl */
2582 /* */
2583 /* 3a fgh cde qab mnp|00i jkl */
2584 /* 3b fgh cde qab mnp|jkl 00i */
2585 /* 3c 00i jkl mnp qab cde fgh */
2587 /* Step 1: amount to shift is the partial right-rotate count */
2588 rotate=set->digits-rotate; /* make it right-rotate */
2589 units=rotate/DECDPUN; /* whole units to rotate */
2590 shift=rotate%DECDPUN; /* left-over digits count */
2591 if (shift>0) { /* not an exact number of units */
2592 uInt save=res->lsu[0]%powers[shift]; /* save low digit(s) */
2593 decShiftToLeast(res->lsu, D2U(res->digits), shift);
2594 if (shift>msudigits) { /* msumax-1 needs >0 digits */
2595 uInt rem=save%powers[shift-msudigits];/* split save */
2596 *msumax=(Unit)(save/powers[shift-msudigits]); /* and insert */
2597 *(msumax-1)=*(msumax-1)
2598 +(Unit)(rem*powers[DECDPUN-(shift-msudigits)]); /* .. */
2600 else { /* all fits in msumax */
2601 *msumax=*msumax+(Unit)(save*powers[msudigits-shift]); /* [maybe *1] */
2603 } /* digits shift needed */
2605 /* If whole units to rotate... */
2606 if (units>0) { /* some to do */
2607 /* Step 2: the units to touch are the whole ones in rotate, */
2608 /* if any, and the shift is DECDPUN-msudigits (which may be */
2609 /* 0, again) */
2610 shift=DECDPUN-msudigits;
2611 if (shift>0) { /* not an exact number of units */
2612 uInt save=res->lsu[0]%powers[shift]; /* save low digit(s) */
2613 decShiftToLeast(res->lsu, units, shift);
2614 *msumax=*msumax+(Unit)(save*powers[msudigits]);
2615 } /* partial shift needed */
2617 /* Step 3: rotate the units array using triple reverse */
2618 /* (reversing is easy and fast) */
2619 decReverse(res->lsu+units, msumax); /* left part */
2620 decReverse(res->lsu, res->lsu+units-1); /* right part */
2621 decReverse(res->lsu, msumax); /* whole */
2622 } /* whole units to rotate */
2623 /* the rotation may have left an undetermined number of zeros */
2624 /* on the left, so true length needs to be calculated */
2625 res->digits=decGetDigits(res->lsu, msumax-res->lsu+1);
2626 } /* rotate needed */
2627 } /* rhs OK */
2628 } /* numerics */
2629 if (status!=0) decStatus(res, status, set);
2630 return res;
2631 } /* decNumberRotate */
2633 /* ------------------------------------------------------------------ */
2634 /* decNumberSameQuantum -- test for equal exponents */
2635 /* */
2636 /* res is the result number, which will contain either 0 or 1 */
2637 /* lhs is a number to test */
2638 /* rhs is the second (usually a pattern) */
2639 /* */
2640 /* No errors are possible and no context is needed. */
2641 /* ------------------------------------------------------------------ */
2642 decNumber * decNumberSameQuantum(decNumber *res, const decNumber *lhs,
2643 const decNumber *rhs) {
2644 Unit ret=0; /* return value */
2646 #if DECCHECK
2647 if (decCheckOperands(res, lhs, rhs, DECUNCONT)) return res;
2648 #endif
2650 if (SPECIALARGS) {
2651 if (decNumberIsNaN(lhs) && decNumberIsNaN(rhs)) ret=1;
2652 else if (decNumberIsInfinite(lhs) && decNumberIsInfinite(rhs)) ret=1;
2653 /* [anything else with a special gives 0] */
2655 else if (lhs->exponent==rhs->exponent) ret=1;
2657 decNumberZero(res); /* OK to overwrite an operand now */
2658 *res->lsu=ret;
2659 return res;
2660 } /* decNumberSameQuantum */
2662 /* ------------------------------------------------------------------ */
2663 /* decNumberScaleB -- multiply by a power of 10 */
2664 /* */
2665 /* This computes C = A x 10**B where B is an integer (q=0) with */
2666 /* maximum magnitude 2*(emax+digits) */
2667 /* */
2668 /* res is C, the result. C may be A or B */
2669 /* lhs is A, the number to adjust */
2670 /* rhs is B, the requested power of ten to use */
2671 /* set is the context */
2672 /* */
2673 /* C must have space for set->digits digits. */
2674 /* */
2675 /* The result may underflow or overflow. */
2676 /* ------------------------------------------------------------------ */
2677 decNumber * decNumberScaleB(decNumber *res, const decNumber *lhs,
2678 const decNumber *rhs, decContext *set) {
2679 Int reqexp; /* requested exponent change [B] */
2680 uInt status=0; /* accumulator */
2681 Int residue; /* work */
2683 #if DECCHECK
2684 if (decCheckOperands(res, lhs, rhs, set)) return res;
2685 #endif
2687 /* Handle special values except lhs infinite */
2688 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2689 decNaNs(res, lhs, rhs, set, &status);
2690 /* rhs must be an integer */
2691 else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2692 status=DEC_Invalid_operation;
2693 else {
2694 /* lhs is a number; rhs is a finite with q==0 */
2695 reqexp=decGetInt(rhs); /* [cannot fail] */
2696 if (reqexp==BADINT /* something bad .. */
2697 || reqexp==BIGODD || reqexp==BIGEVEN /* .. very big .. */
2698 || abs(reqexp)>(2*(set->digits+set->emax))) /* .. or out of range */
2699 status=DEC_Invalid_operation;
2700 else { /* rhs is OK */
2701 decNumberCopy(res, lhs); /* all done if infinite lhs */
2702 if (!decNumberIsInfinite(res)) { /* prepare to scale */
2703 res->exponent+=reqexp; /* adjust the exponent */
2704 residue=0;
2705 decFinalize(res, set, &residue, &status); /* .. and check */
2706 } /* finite LHS */
2707 } /* rhs OK */
2708 } /* rhs finite */
2709 if (status!=0) decStatus(res, status, set);
2710 return res;
2711 } /* decNumberScaleB */
2713 /* ------------------------------------------------------------------ */
2714 /* decNumberShift -- shift the coefficient of a Number left or right */
2715 /* */
2716 /* This computes C = A << B or C = A >> -B (in base ten). */
2717 /* */
2718 /* res is C, the result. C may be A and/or B (e.g., X=X<<X) */
2719 /* lhs is A */
2720 /* rhs is B, the number of digits to shift (-ve to right) */
2721 /* set is the context */
2722 /* */
2723 /* The digits of the coefficient of A are shifted to the left (if B */
2724 /* is positive) or to the right (if B is negative) without adjusting */
2725 /* the exponent or the sign of A. */
2726 /* */
2727 /* B must be an integer (q=0) and in the range -set->digits through */
2728 /* +set->digits. */
2729 /* C must have space for set->digits digits. */
2730 /* NaNs are propagated as usual. Infinities are unaffected (but */
2731 /* B must be valid). No status is set unless B is invalid or an */
2732 /* operand is an sNaN. */
2733 /* ------------------------------------------------------------------ */
2734 decNumber * decNumberShift(decNumber *res, const decNumber *lhs,
2735 const decNumber *rhs, decContext *set) {
2736 uInt status=0; /* accumulator */
2737 Int shift; /* rhs as an Int */
2739 #if DECCHECK
2740 if (decCheckOperands(res, lhs, rhs, set)) return res;
2741 #endif
2743 /* NaNs propagate as normal */
2744 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2745 decNaNs(res, lhs, rhs, set, &status);
2746 /* rhs must be an integer */
2747 else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2748 status=DEC_Invalid_operation;
2749 else { /* both numeric, rhs is an integer */
2750 shift=decGetInt(rhs); /* [cannot fail] */
2751 if (shift==BADINT /* something bad .. */
2752 || shift==BIGODD || shift==BIGEVEN /* .. very big .. */
2753 || abs(shift)>set->digits) /* .. or out of range */
2754 status=DEC_Invalid_operation;
2755 else { /* rhs is OK */
2756 decNumberCopy(res, lhs);
2757 if (shift!=0 && !decNumberIsInfinite(res)) { /* something to do */
2758 if (shift>0) { /* to left */
2759 if (shift==set->digits) { /* removing all */
2760 *res->lsu=0; /* so place 0 */
2761 res->digits=1; /* .. */
2763 else { /* */
2764 /* first remove leading digits if necessary */
2765 if (res->digits+shift>set->digits) {
2766 decDecap(res, res->digits+shift-set->digits);
2767 /* that updated res->digits; may have gone to 1 (for a */
2768 /* single digit or for zero */
2770 if (res->digits>1 || *res->lsu) /* if non-zero.. */
2771 res->digits=decShiftToMost(res->lsu, res->digits, shift);
2772 } /* partial left */
2773 } /* left */
2774 else { /* to right */
2775 if (-shift>=res->digits) { /* discarding all */
2776 *res->lsu=0; /* so place 0 */
2777 res->digits=1; /* .. */
2779 else {
2780 decShiftToLeast(res->lsu, D2U(res->digits), -shift);
2781 res->digits-=(-shift);
2783 } /* to right */
2784 } /* non-0 non-Inf shift */
2785 } /* rhs OK */
2786 } /* numerics */
2787 if (status!=0) decStatus(res, status, set);
2788 return res;
2789 } /* decNumberShift */
2791 /* ------------------------------------------------------------------ */
2792 /* decNumberSquareRoot -- square root operator */
2793 /* */
2794 /* This computes C = squareroot(A) */
2795 /* */
2796 /* res is C, the result. C may be A */
2797 /* rhs is A */
2798 /* set is the context; note that rounding mode has no effect */
2799 /* */
2800 /* C must have space for set->digits digits. */
2801 /* ------------------------------------------------------------------ */
2802 /* This uses the following varying-precision algorithm in: */
2803 /* */
2804 /* Properly Rounded Variable Precision Square Root, T. E. Hull and */
2805 /* A. Abrham, ACM Transactions on Mathematical Software, Vol 11 #3, */
2806 /* pp229-237, ACM, September 1985. */
2807 /* */
2808 /* The square-root is calculated using Newton's method, after which */
2809 /* a check is made to ensure the result is correctly rounded. */
2810 /* */
2811 /* % [Reformatted original Numerical Turing source code follows.] */
2812 /* function sqrt(x : real) : real */
2813 /* % sqrt(x) returns the properly rounded approximation to the square */
2814 /* % root of x, in the precision of the calling environment, or it */
2815 /* % fails if x < 0. */
2816 /* % t e hull and a abrham, august, 1984 */
2817 /* if x <= 0 then */
2818 /* if x < 0 then */
2819 /* assert false */
2820 /* else */
2821 /* result 0 */
2822 /* end if */
2823 /* end if */
2824 /* var f := setexp(x, 0) % fraction part of x [0.1 <= x < 1] */
2825 /* var e := getexp(x) % exponent part of x */
2826 /* var approx : real */
2827 /* if e mod 2 = 0 then */
2828 /* approx := .259 + .819 * f % approx to root of f */
2829 /* else */
2830 /* f := f/l0 % adjustments */
2831 /* e := e + 1 % for odd */
2832 /* approx := .0819 + 2.59 * f % exponent */
2833 /* end if */
2834 /* */
2835 /* var p:= 3 */
2836 /* const maxp := currentprecision + 2 */
2837 /* loop */
2838 /* p := min(2*p - 2, maxp) % p = 4,6,10, . . . , maxp */
2839 /* precision p */
2840 /* approx := .5 * (approx + f/approx) */
2841 /* exit when p = maxp */
2842 /* end loop */
2843 /* */
2844 /* % approx is now within 1 ulp of the properly rounded square root */
2845 /* % of f; to ensure proper rounding, compare squares of (approx - */
2846 /* % l/2 ulp) and (approx + l/2 ulp) with f. */
2847 /* p := currentprecision */
2848 /* begin */
2849 /* precision p + 2 */
2850 /* const approxsubhalf := approx - setexp(.5, -p) */
2851 /* if mulru(approxsubhalf, approxsubhalf) > f then */
2852 /* approx := approx - setexp(.l, -p + 1) */
2853 /* else */
2854 /* const approxaddhalf := approx + setexp(.5, -p) */
2855 /* if mulrd(approxaddhalf, approxaddhalf) < f then */
2856 /* approx := approx + setexp(.l, -p + 1) */
2857 /* end if */
2858 /* end if */
2859 /* end */
2860 /* result setexp(approx, e div 2) % fix exponent */
2861 /* end sqrt */
2862 /* ------------------------------------------------------------------ */
2863 decNumber * decNumberSquareRoot(decNumber *res, const decNumber *rhs,
2864 decContext *set) {
2865 decContext workset, approxset; /* work contexts */
2866 decNumber dzero; /* used for constant zero */
2867 Int maxp; /* largest working precision */
2868 Int workp; /* working precision */
2869 Int residue=0; /* rounding residue */
2870 uInt status=0, ignore=0; /* status accumulators */
2871 uInt rstatus; /* .. */
2872 Int exp; /* working exponent */
2873 Int ideal; /* ideal (preferred) exponent */
2874 Int needbytes; /* work */
2875 Int dropped; /* .. */
2877 #if DECSUBSET
2878 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */
2879 #endif
2880 /* buffer for f [needs +1 in case DECBUFFER 0] */
2881 decNumber buff[D2N(DECBUFFER+1)];
2882 /* buffer for a [needs +2 to match likely maxp] */
2883 decNumber bufa[D2N(DECBUFFER+2)];
2884 /* buffer for temporary, b [must be same size as a] */
2885 decNumber bufb[D2N(DECBUFFER+2)];
2886 decNumber *allocbuff=NULL; /* -> allocated buff, iff allocated */
2887 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
2888 decNumber *allocbufb=NULL; /* -> allocated bufb, iff allocated */
2889 decNumber *f=buff; /* reduced fraction */
2890 decNumber *a=bufa; /* approximation to result */
2891 decNumber *b=bufb; /* intermediate result */
2892 /* buffer for temporary variable, up to 3 digits */
2893 decNumber buft[D2N(3)];
2894 decNumber *t=buft; /* up-to-3-digit constant or work */
2896 #if DECCHECK
2897 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
2898 #endif
2900 do { /* protect allocated storage */
2901 #if DECSUBSET
2902 if (!set->extended) {
2903 /* reduce operand and set lostDigits status, as needed */
2904 if (rhs->digits>set->digits) {
2905 allocrhs=decRoundOperand(rhs, set, &status);
2906 if (allocrhs==NULL) break;
2907 /* [Note: 'f' allocation below could reuse this buffer if */
2908 /* used, but as this is rare they are kept separate for clarity.] */
2909 rhs=allocrhs;
2912 #endif
2913 /* [following code does not require input rounding] */
2915 /* handle infinities and NaNs */
2916 if (SPECIALARG) {
2917 if (decNumberIsInfinite(rhs)) { /* an infinity */
2918 if (decNumberIsNegative(rhs)) status|=DEC_Invalid_operation;
2919 else decNumberCopy(res, rhs); /* +Infinity */
2921 else decNaNs(res, rhs, NULL, set, &status); /* a NaN */
2922 break;
2925 /* calculate the ideal (preferred) exponent [floor(exp/2)] */
2926 /* [We would like to write: ideal=rhs->exponent>>1, but this */
2927 /* generates a compiler warning. Generated code is the same.] */
2928 ideal=(rhs->exponent&~1)/2; /* target */
2930 /* handle zeros */
2931 if (ISZERO(rhs)) {
2932 decNumberCopy(res, rhs); /* could be 0 or -0 */
2933 res->exponent=ideal; /* use the ideal [safe] */
2934 /* use decFinish to clamp any out-of-range exponent, etc. */
2935 decFinish(res, set, &residue, &status);
2936 break;
2939 /* any other -x is an oops */
2940 if (decNumberIsNegative(rhs)) {
2941 status|=DEC_Invalid_operation;
2942 break;
2945 /* space is needed for three working variables */
2946 /* f -- the same precision as the RHS, reduced to 0.01->0.99... */
2947 /* a -- Hull's approximation -- precision, when assigned, is */
2948 /* currentprecision+1 or the input argument precision, */
2949 /* whichever is larger (+2 for use as temporary) */
2950 /* b -- intermediate temporary result (same size as a) */
2951 /* if any is too long for local storage, then allocate */
2952 workp=MAXI(set->digits+1, rhs->digits); /* actual rounding precision */
2953 maxp=workp+2; /* largest working precision */
2955 needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
2956 if (needbytes>(Int)sizeof(buff)) {
2957 allocbuff=(decNumber *)malloc(needbytes);
2958 if (allocbuff==NULL) { /* hopeless -- abandon */
2959 status|=DEC_Insufficient_storage;
2960 break;}
2961 f=allocbuff; /* use the allocated space */
2963 /* a and b both need to be able to hold a maxp-length number */
2964 needbytes=sizeof(decNumber)+(D2U(maxp)-1)*sizeof(Unit);
2965 if (needbytes>(Int)sizeof(bufa)) { /* [same applies to b] */
2966 allocbufa=(decNumber *)malloc(needbytes);
2967 allocbufb=(decNumber *)malloc(needbytes);
2968 if (allocbufa==NULL || allocbufb==NULL) { /* hopeless */
2969 status|=DEC_Insufficient_storage;
2970 break;}
2971 a=allocbufa; /* use the allocated spaces */
2972 b=allocbufb; /* .. */
2975 /* copy rhs -> f, save exponent, and reduce so 0.1 <= f < 1 */
2976 decNumberCopy(f, rhs);
2977 exp=f->exponent+f->digits; /* adjusted to Hull rules */
2978 f->exponent=-(f->digits); /* to range */
2980 /* set up working context */
2981 decContextDefault(&workset, DEC_INIT_DECIMAL64);
2983 /* [Until further notice, no error is possible and status bits */
2984 /* (Rounded, etc.) should be ignored, not accumulated.] */
2986 /* Calculate initial approximation, and allow for odd exponent */
2987 workset.digits=workp; /* p for initial calculation */
2988 t->bits=0; t->digits=3;
2989 a->bits=0; a->digits=3;
2990 if ((exp & 1)==0) { /* even exponent */
2991 /* Set t=0.259, a=0.819 */
2992 t->exponent=-3;
2993 a->exponent=-3;
2994 #if DECDPUN>=3
2995 t->lsu[0]=259;
2996 a->lsu[0]=819;
2997 #elif DECDPUN==2
2998 t->lsu[0]=59; t->lsu[1]=2;
2999 a->lsu[0]=19; a->lsu[1]=8;
3000 #else
3001 t->lsu[0]=9; t->lsu[1]=5; t->lsu[2]=2;
3002 a->lsu[0]=9; a->lsu[1]=1; a->lsu[2]=8;
3003 #endif
3005 else { /* odd exponent */
3006 /* Set t=0.0819, a=2.59 */
3007 f->exponent--; /* f=f/10 */
3008 exp++; /* e=e+1 */
3009 t->exponent=-4;
3010 a->exponent=-2;
3011 #if DECDPUN>=3
3012 t->lsu[0]=819;
3013 a->lsu[0]=259;
3014 #elif DECDPUN==2
3015 t->lsu[0]=19; t->lsu[1]=8;
3016 a->lsu[0]=59; a->lsu[1]=2;
3017 #else
3018 t->lsu[0]=9; t->lsu[1]=1; t->lsu[2]=8;
3019 a->lsu[0]=9; a->lsu[1]=5; a->lsu[2]=2;
3020 #endif
3022 decMultiplyOp(a, a, f, &workset, &ignore); /* a=a*f */
3023 decAddOp(a, a, t, &workset, 0, &ignore); /* ..+t */
3024 /* [a is now the initial approximation for sqrt(f), calculated with */
3025 /* currentprecision, which is also a's precision.] */
3027 /* the main calculation loop */
3028 decNumberZero(&dzero); /* make 0 */
3029 decNumberZero(t); /* set t = 0.5 */
3030 t->lsu[0]=5; /* .. */
3031 t->exponent=-1; /* .. */
3032 workset.digits=3; /* initial p */
3033 for (;;) {
3034 /* set p to min(2*p - 2, maxp) [hence 3; or: 4, 6, 10, ... , maxp] */
3035 workset.digits=workset.digits*2-2;
3036 if (workset.digits>maxp) workset.digits=maxp;
3037 /* a = 0.5 * (a + f/a) */
3038 /* [calculated at p then rounded to currentprecision] */
3039 decDivideOp(b, f, a, &workset, DIVIDE, &ignore); /* b=f/a */
3040 decAddOp(b, b, a, &workset, 0, &ignore); /* b=b+a */
3041 decMultiplyOp(a, b, t, &workset, &ignore); /* a=b*0.5 */
3042 if (a->digits==maxp) break; /* have required digits */
3043 } /* loop */
3045 /* Here, 0.1 <= a < 1 [Hull], and a has maxp digits */
3046 /* now reduce to length, etc.; this needs to be done with a */
3047 /* having the correct exponent so as to handle subnormals */
3048 /* correctly */
3049 approxset=*set; /* get emin, emax, etc. */
3050 approxset.round=DEC_ROUND_HALF_EVEN;
3051 a->exponent+=exp/2; /* set correct exponent */
3053 rstatus=0; /* clear status */
3054 residue=0; /* .. and accumulator */
3055 decCopyFit(a, a, &approxset, &residue, &rstatus); /* reduce (if needed) */
3056 decFinish(a, &approxset, &residue, &rstatus); /* clean and finalize */
3058 /* Overflow was possible if the input exponent was out-of-range, */
3059 /* in which case quit */
3060 if (rstatus&DEC_Overflow) {
3061 status=rstatus; /* use the status as-is */
3062 decNumberCopy(res, a); /* copy to result */
3063 break;
3066 /* Preserve status except Inexact/Rounded */
3067 status|=(rstatus & ~(DEC_Rounded|DEC_Inexact));
3069 /* Carry out the Hull correction */
3070 a->exponent-=exp/2; /* back to 0.1->1 */
3072 /* a is now at final precision and within 1 ulp of the properly */
3073 /* rounded square root of f; to ensure proper rounding, compare */
3074 /* squares of (a - l/2 ulp) and (a + l/2 ulp) with f. */
3075 /* Here workset.digits=maxp and t=0.5, and a->digits determines */
3076 /* the ulp */
3077 workset.digits--; /* maxp-1 is OK now */
3078 t->exponent=-a->digits-1; /* make 0.5 ulp */
3079 decAddOp(b, a, t, &workset, DECNEG, &ignore); /* b = a - 0.5 ulp */
3080 workset.round=DEC_ROUND_UP;
3081 decMultiplyOp(b, b, b, &workset, &ignore); /* b = mulru(b, b) */
3082 decCompareOp(b, f, b, &workset, COMPARE, &ignore); /* b ? f, reversed */
3083 if (decNumberIsNegative(b)) { /* f < b [i.e., b > f] */
3084 /* this is the more common adjustment, though both are rare */
3085 t->exponent++; /* make 1.0 ulp */
3086 t->lsu[0]=1; /* .. */
3087 decAddOp(a, a, t, &workset, DECNEG, &ignore); /* a = a - 1 ulp */
3088 /* assign to approx [round to length] */
3089 approxset.emin-=exp/2; /* adjust to match a */
3090 approxset.emax-=exp/2;
3091 decAddOp(a, &dzero, a, &approxset, 0, &ignore);
3093 else {
3094 decAddOp(b, a, t, &workset, 0, &ignore); /* b = a + 0.5 ulp */
3095 workset.round=DEC_ROUND_DOWN;
3096 decMultiplyOp(b, b, b, &workset, &ignore); /* b = mulrd(b, b) */
3097 decCompareOp(b, b, f, &workset, COMPARE, &ignore); /* b ? f */
3098 if (decNumberIsNegative(b)) { /* b < f */
3099 t->exponent++; /* make 1.0 ulp */
3100 t->lsu[0]=1; /* .. */
3101 decAddOp(a, a, t, &workset, 0, &ignore); /* a = a + 1 ulp */
3102 /* assign to approx [round to length] */
3103 approxset.emin-=exp/2; /* adjust to match a */
3104 approxset.emax-=exp/2;
3105 decAddOp(a, &dzero, a, &approxset, 0, &ignore);
3108 /* [no errors are possible in the above, and rounding/inexact during */
3109 /* estimation are irrelevant, so status was not accumulated] */
3111 /* Here, 0.1 <= a < 1 (still), so adjust back */
3112 a->exponent+=exp/2; /* set correct exponent */
3114 /* count droppable zeros [after any subnormal rounding] by */
3115 /* trimming a copy */
3116 decNumberCopy(b, a);
3117 decTrim(b, set, 1, &dropped); /* [drops trailing zeros] */
3119 /* Set Inexact and Rounded. The answer can only be exact if */
3120 /* it is short enough so that squaring it could fit in workp digits, */
3121 /* and it cannot have trailing zeros due to clamping, so these are */
3122 /* the only (relatively rare) conditions a careful check is needed */
3123 if (b->digits*2-1 > workp && !set->clamp) { /* cannot fit */
3124 status|=DEC_Inexact|DEC_Rounded;
3126 else { /* could be exact/unrounded */
3127 uInt mstatus=0; /* local status */
3128 decMultiplyOp(b, b, b, &workset, &mstatus); /* try the multiply */
3129 if (mstatus&DEC_Overflow) { /* result just won't fit */
3130 status|=DEC_Inexact|DEC_Rounded;
3132 else { /* plausible */
3133 decCompareOp(t, b, rhs, &workset, COMPARE, &mstatus); /* b ? rhs */
3134 if (!ISZERO(t)) status|=DEC_Inexact|DEC_Rounded; /* not equal */
3135 else { /* is Exact */
3136 /* here, dropped is the count of trailing zeros in 'a' */
3137 /* use closest exponent to ideal... */
3138 Int todrop=ideal-a->exponent; /* most that can be dropped */
3139 if (todrop<0) status|=DEC_Rounded; /* ideally would add 0s */
3140 else { /* unrounded */
3141 if (dropped<todrop) { /* clamp to those available */
3142 todrop=dropped;
3143 status|=DEC_Clamped;
3145 if (todrop>0) { /* have some to drop */
3146 decShiftToLeast(a->lsu, D2U(a->digits), todrop);
3147 a->exponent+=todrop; /* maintain numerical value */
3148 a->digits-=todrop; /* new length */
3155 /* double-check Underflow, as perhaps the result could not have */
3156 /* been subnormal (initial argument too big), or it is now Exact */
3157 if (status&DEC_Underflow) {
3158 Int ae=rhs->exponent+rhs->digits-1; /* adjusted exponent */
3159 /* check if truly subnormal */
3160 #if DECEXTFLAG /* DEC_Subnormal too */
3161 if (ae>=set->emin*2) status&=~(DEC_Subnormal|DEC_Underflow);
3162 #else
3163 if (ae>=set->emin*2) status&=~DEC_Underflow;
3164 #endif
3165 /* check if truly inexact */
3166 if (!(status&DEC_Inexact)) status&=~DEC_Underflow;
3169 decNumberCopy(res, a); /* a is now the result */
3170 } while(0); /* end protected */
3172 if (allocbuff!=NULL) free(allocbuff); /* drop any storage used */
3173 if (allocbufa!=NULL) free(allocbufa); /* .. */
3174 if (allocbufb!=NULL) free(allocbufb); /* .. */
3175 #if DECSUBSET
3176 if (allocrhs !=NULL) free(allocrhs); /* .. */
3177 #endif
3178 if (status!=0) decStatus(res, status, set);/* then report status */
3179 #if DECCHECK
3180 decCheckInexact(res, set);
3181 #endif
3182 return res;
3183 } /* decNumberSquareRoot */
3185 /* ------------------------------------------------------------------ */
3186 /* decNumberSubtract -- subtract two Numbers */
3187 /* */
3188 /* This computes C = A - B */
3189 /* */
3190 /* res is C, the result. C may be A and/or B (e.g., X=X-X) */
3191 /* lhs is A */
3192 /* rhs is B */
3193 /* set is the context */
3194 /* */
3195 /* C must have space for set->digits digits. */
3196 /* ------------------------------------------------------------------ */
3197 decNumber * decNumberSubtract(decNumber *res, const decNumber *lhs,
3198 const decNumber *rhs, decContext *set) {
3199 uInt status=0; /* accumulator */
3201 decAddOp(res, lhs, rhs, set, DECNEG, &status);
3202 if (status!=0) decStatus(res, status, set);
3203 #if DECCHECK
3204 decCheckInexact(res, set);
3205 #endif
3206 return res;
3207 } /* decNumberSubtract */
3209 /* ------------------------------------------------------------------ */
3210 /* decNumberToIntegralExact -- round-to-integral-value with InExact */
3211 /* decNumberToIntegralValue -- round-to-integral-value */
3212 /* */
3213 /* res is the result */
3214 /* rhs is input number */
3215 /* set is the context */
3216 /* */
3217 /* res must have space for any value of rhs. */
3218 /* */
3219 /* This implements the IEEE special operators and therefore treats */
3220 /* special values as valid. For finite numbers it returns */
3221 /* rescale(rhs, 0) if rhs->exponent is <0. */
3222 /* Otherwise the result is rhs (so no error is possible, except for */
3223 /* sNaN). */
3224 /* */
3225 /* The context is used for rounding mode and status after sNaN, but */
3226 /* the digits setting is ignored. The Exact version will signal */
3227 /* Inexact if the result differs numerically from rhs; the other */
3228 /* never signals Inexact. */
3229 /* ------------------------------------------------------------------ */
3230 decNumber * decNumberToIntegralExact(decNumber *res, const decNumber *rhs,
3231 decContext *set) {
3232 decNumber dn;
3233 decContext workset; /* working context */
3234 uInt status=0; /* accumulator */
3236 #if DECCHECK
3237 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
3238 #endif
3240 /* handle infinities and NaNs */
3241 if (SPECIALARG) {
3242 if (decNumberIsInfinite(rhs)) decNumberCopy(res, rhs); /* an Infinity */
3243 else decNaNs(res, rhs, NULL, set, &status); /* a NaN */
3245 else { /* finite */
3246 /* have a finite number; no error possible (res must be big enough) */
3247 if (rhs->exponent>=0) return decNumberCopy(res, rhs);
3248 /* that was easy, but if negative exponent there is work to do... */
3249 workset=*set; /* clone rounding, etc. */
3250 workset.digits=rhs->digits; /* no length rounding */
3251 workset.traps=0; /* no traps */
3252 decNumberZero(&dn); /* make a number with exponent 0 */
3253 decNumberQuantize(res, rhs, &dn, &workset);
3254 status|=workset.status;
3256 if (status!=0) decStatus(res, status, set);
3257 return res;
3258 } /* decNumberToIntegralExact */
3260 decNumber * decNumberToIntegralValue(decNumber *res, const decNumber *rhs,
3261 decContext *set) {
3262 decContext workset=*set; /* working context */
3263 workset.traps=0; /* no traps */
3264 decNumberToIntegralExact(res, rhs, &workset);
3265 /* this never affects set, except for sNaNs; NaN will have been set */
3266 /* or propagated already, so no need to call decStatus */
3267 set->status|=workset.status&DEC_Invalid_operation;
3268 return res;
3269 } /* decNumberToIntegralValue */
3271 /* ------------------------------------------------------------------ */
3272 /* decNumberXor -- XOR two Numbers, digitwise */
3273 /* */
3274 /* This computes C = A ^ B */
3275 /* */
3276 /* res is C, the result. C may be A and/or B (e.g., X=X^X) */
3277 /* lhs is A */
3278 /* rhs is B */
3279 /* set is the context (used for result length and error report) */
3280 /* */
3281 /* C must have space for set->digits digits. */
3282 /* */
3283 /* Logical function restrictions apply (see above); a NaN is */
3284 /* returned with Invalid_operation if a restriction is violated. */
3285 /* ------------------------------------------------------------------ */
3286 decNumber * decNumberXor(decNumber *res, const decNumber *lhs,
3287 const decNumber *rhs, decContext *set) {
3288 const Unit *ua, *ub; /* -> operands */
3289 const Unit *msua, *msub; /* -> operand msus */
3290 Unit *uc, *msuc; /* -> result and its msu */
3291 Int msudigs; /* digits in res msu */
3292 #if DECCHECK
3293 if (decCheckOperands(res, lhs, rhs, set)) return res;
3294 #endif
3296 if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
3297 || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
3298 decStatus(res, DEC_Invalid_operation, set);
3299 return res;
3301 /* operands are valid */
3302 ua=lhs->lsu; /* bottom-up */
3303 ub=rhs->lsu; /* .. */
3304 uc=res->lsu; /* .. */
3305 msua=ua+D2U(lhs->digits)-1; /* -> msu of lhs */
3306 msub=ub+D2U(rhs->digits)-1; /* -> msu of rhs */
3307 msuc=uc+D2U(set->digits)-1; /* -> msu of result */
3308 msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */
3309 for (; uc<=msuc; ua++, ub++, uc++) { /* Unit loop */
3310 Unit a, b; /* extract units */
3311 if (ua>msua) a=0;
3312 else a=*ua;
3313 if (ub>msub) b=0;
3314 else b=*ub;
3315 *uc=0; /* can now write back */
3316 if (a|b) { /* maybe 1 bits to examine */
3317 Int i, j;
3318 /* This loop could be unrolled and/or use BIN2BCD tables */
3319 for (i=0; i<DECDPUN; i++) {
3320 if ((a^b)&1) *uc=*uc+(Unit)powers[i]; /* effect XOR */
3321 j=a%10;
3322 a=a/10;
3323 j|=b%10;
3324 b=b/10;
3325 if (j>1) {
3326 decStatus(res, DEC_Invalid_operation, set);
3327 return res;
3329 if (uc==msuc && i==msudigs-1) break; /* just did final digit */
3330 } /* each digit */
3331 } /* non-zero */
3332 } /* each unit */
3333 /* [here uc-1 is the msu of the result] */
3334 res->digits=decGetDigits(res->lsu, uc-res->lsu);
3335 res->exponent=0; /* integer */
3336 res->bits=0; /* sign=0 */
3337 return res; /* [no status to set] */
3338 } /* decNumberXor */
3341 /* ================================================================== */
3342 /* Utility routines */
3343 /* ================================================================== */
3345 /* ------------------------------------------------------------------ */
3346 /* decNumberClass -- return the decClass of a decNumber */
3347 /* dn -- the decNumber to test */
3348 /* set -- the context to use for Emin */
3349 /* returns the decClass enum */
3350 /* ------------------------------------------------------------------ */
3351 enum decClass decNumberClass(const decNumber *dn, decContext *set) {
3352 if (decNumberIsSpecial(dn)) {
3353 if (decNumberIsQNaN(dn)) return DEC_CLASS_QNAN;
3354 if (decNumberIsSNaN(dn)) return DEC_CLASS_SNAN;
3355 /* must be an infinity */
3356 if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_INF;
3357 return DEC_CLASS_POS_INF;
3359 /* is finite */
3360 if (decNumberIsNormal(dn, set)) { /* most common */
3361 if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_NORMAL;
3362 return DEC_CLASS_POS_NORMAL;
3364 /* is subnormal or zero */
3365 if (decNumberIsZero(dn)) { /* most common */
3366 if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_ZERO;
3367 return DEC_CLASS_POS_ZERO;
3369 if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_SUBNORMAL;
3370 return DEC_CLASS_POS_SUBNORMAL;
3371 } /* decNumberClass */
3373 /* ------------------------------------------------------------------ */
3374 /* decNumberClassToString -- convert decClass to a string */
3375 /* */
3376 /* eclass is a valid decClass */
3377 /* returns a constant string describing the class (max 13+1 chars) */
3378 /* ------------------------------------------------------------------ */
3379 const char *decNumberClassToString(enum decClass eclass) {
3380 if (eclass==DEC_CLASS_POS_NORMAL) return DEC_ClassString_PN;
3381 if (eclass==DEC_CLASS_NEG_NORMAL) return DEC_ClassString_NN;
3382 if (eclass==DEC_CLASS_POS_ZERO) return DEC_ClassString_PZ;
3383 if (eclass==DEC_CLASS_NEG_ZERO) return DEC_ClassString_NZ;
3384 if (eclass==DEC_CLASS_POS_SUBNORMAL) return DEC_ClassString_PS;
3385 if (eclass==DEC_CLASS_NEG_SUBNORMAL) return DEC_ClassString_NS;
3386 if (eclass==DEC_CLASS_POS_INF) return DEC_ClassString_PI;
3387 if (eclass==DEC_CLASS_NEG_INF) return DEC_ClassString_NI;
3388 if (eclass==DEC_CLASS_QNAN) return DEC_ClassString_QN;
3389 if (eclass==DEC_CLASS_SNAN) return DEC_ClassString_SN;
3390 return DEC_ClassString_UN; /* Unknown */
3391 } /* decNumberClassToString */
3393 /* ------------------------------------------------------------------ */
3394 /* decNumberCopy -- copy a number */
3395 /* */
3396 /* dest is the target decNumber */
3397 /* src is the source decNumber */
3398 /* returns dest */
3399 /* */
3400 /* (dest==src is allowed and is a no-op) */
3401 /* All fields are updated as required. This is a utility operation, */
3402 /* so special values are unchanged and no error is possible. */
3403 /* ------------------------------------------------------------------ */
3404 decNumber * decNumberCopy(decNumber *dest, const decNumber *src) {
3406 #if DECCHECK
3407 if (src==NULL) return decNumberZero(dest);
3408 #endif
3410 if (dest==src) return dest; /* no copy required */
3412 /* Use explicit assignments here as structure assignment could copy */
3413 /* more than just the lsu (for small DECDPUN). This would not affect */
3414 /* the value of the results, but could disturb test harness spill */
3415 /* checking. */
3416 dest->bits=src->bits;
3417 dest->exponent=src->exponent;
3418 dest->digits=src->digits;
3419 dest->lsu[0]=src->lsu[0];
3420 if (src->digits>DECDPUN) { /* more Units to come */
3421 const Unit *smsup, *s; /* work */
3422 Unit *d; /* .. */
3423 /* memcpy for the remaining Units would be safe as they cannot */
3424 /* overlap. However, this explicit loop is faster in short cases. */
3425 d=dest->lsu+1; /* -> first destination */
3426 smsup=src->lsu+D2U(src->digits); /* -> source msu+1 */
3427 for (s=src->lsu+1; s<smsup; s++, d++) *d=*s;
3429 return dest;
3430 } /* decNumberCopy */
3432 /* ------------------------------------------------------------------ */
3433 /* decNumberCopyAbs -- quiet absolute value operator */
3434 /* */
3435 /* This sets C = abs(A) */
3436 /* */
3437 /* res is C, the result. C may be A */
3438 /* rhs is A */
3439 /* */
3440 /* C must have space for set->digits digits. */
3441 /* No exception or error can occur; this is a quiet bitwise operation.*/
3442 /* See also decNumberAbs for a checking version of this. */
3443 /* ------------------------------------------------------------------ */
3444 decNumber * decNumberCopyAbs(decNumber *res, const decNumber *rhs) {
3445 #if DECCHECK
3446 if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3447 #endif
3448 decNumberCopy(res, rhs);
3449 res->bits&=~DECNEG; /* turn off sign */
3450 return res;
3451 } /* decNumberCopyAbs */
3453 /* ------------------------------------------------------------------ */
3454 /* decNumberCopyNegate -- quiet negate value operator */
3455 /* */
3456 /* This sets C = negate(A) */
3457 /* */
3458 /* res is C, the result. C may be A */
3459 /* rhs is A */
3460 /* */
3461 /* C must have space for set->digits digits. */
3462 /* No exception or error can occur; this is a quiet bitwise operation.*/
3463 /* See also decNumberMinus for a checking version of this. */
3464 /* ------------------------------------------------------------------ */
3465 decNumber * decNumberCopyNegate(decNumber *res, const decNumber *rhs) {
3466 #if DECCHECK
3467 if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3468 #endif
3469 decNumberCopy(res, rhs);
3470 res->bits^=DECNEG; /* invert the sign */
3471 return res;
3472 } /* decNumberCopyNegate */
3474 /* ------------------------------------------------------------------ */
3475 /* decNumberCopySign -- quiet copy and set sign operator */
3476 /* */
3477 /* This sets C = A with the sign of B */
3478 /* */
3479 /* res is C, the result. C may be A */
3480 /* lhs is A */
3481 /* rhs is B */
3482 /* */
3483 /* C must have space for set->digits digits. */
3484 /* No exception or error can occur; this is a quiet bitwise operation.*/
3485 /* ------------------------------------------------------------------ */
3486 decNumber * decNumberCopySign(decNumber *res, const decNumber *lhs,
3487 const decNumber *rhs) {
3488 uByte sign; /* rhs sign */
3489 #if DECCHECK
3490 if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3491 #endif
3492 sign=rhs->bits & DECNEG; /* save sign bit */
3493 decNumberCopy(res, lhs);
3494 res->bits&=~DECNEG; /* clear the sign */
3495 res->bits|=sign; /* set from rhs */
3496 return res;
3497 } /* decNumberCopySign */
3499 /* ------------------------------------------------------------------ */
3500 /* decNumberGetBCD -- get the coefficient in BCD8 */
3501 /* dn is the source decNumber */
3502 /* bcd is the uInt array that will receive dn->digits BCD bytes, */
3503 /* most-significant at offset 0 */
3504 /* returns bcd */
3505 /* */
3506 /* bcd must have at least dn->digits bytes. No error is possible; if */
3507 /* dn is a NaN or Infinite, digits must be 1 and the coefficient 0. */
3508 /* ------------------------------------------------------------------ */
3509 uByte * decNumberGetBCD(const decNumber *dn, uint8_t *bcd) {
3510 uByte *ub=bcd+dn->digits-1; /* -> lsd */
3511 const Unit *up=dn->lsu; /* Unit pointer, -> lsu */
3513 #if DECDPUN==1 /* trivial simple copy */
3514 for (; ub>=bcd; ub--, up++) *ub=*up;
3515 #else /* chopping needed */
3516 uInt u=*up; /* work */
3517 uInt cut=DECDPUN; /* downcounter through unit */
3518 for (; ub>=bcd; ub--) {
3519 *ub=(uByte)(u%10); /* [*6554 trick inhibits, here] */
3520 u=u/10;
3521 cut--;
3522 if (cut>0) continue; /* more in this unit */
3523 up++;
3524 u=*up;
3525 cut=DECDPUN;
3527 #endif
3528 return bcd;
3529 } /* decNumberGetBCD */
3531 /* ------------------------------------------------------------------ */
3532 /* decNumberSetBCD -- set (replace) the coefficient from BCD8 */
3533 /* dn is the target decNumber */
3534 /* bcd is the uInt array that will source n BCD bytes, most- */
3535 /* significant at offset 0 */
3536 /* n is the number of digits in the source BCD array (bcd) */
3537 /* returns dn */
3538 /* */
3539 /* dn must have space for at least n digits. No error is possible; */
3540 /* if dn is a NaN, or Infinite, or is to become a zero, n must be 1 */
3541 /* and bcd[0] zero. */
3542 /* ------------------------------------------------------------------ */
3543 decNumber * decNumberSetBCD(decNumber *dn, const uByte *bcd, uInt n) {
3544 Unit *up = dn->lsu + D2U(n) - 1; /* -> msu [target pointer] */
3545 const uByte *ub=bcd; /* -> source msd */
3547 #if DECDPUN==1 /* trivial simple copy */
3548 for (; ub<bcd+n; ub++, up--) *up=*ub;
3549 #else /* some assembly needed */
3550 /* calculate how many digits in msu, and hence first cut */
3551 Int cut=MSUDIGITS(n); /* [faster than remainder] */
3552 for (;up>=dn->lsu; up--) { /* each Unit from msu */
3553 *up=0; /* will take <=DECDPUN digits */
3554 for (; cut>0; ub++, cut--) *up=X10(*up)+*ub;
3555 cut=DECDPUN; /* next Unit has all digits */
3557 #endif
3558 dn->digits=n; /* set digit count */
3559 return dn;
3560 } /* decNumberSetBCD */
3562 /* ------------------------------------------------------------------ */
3563 /* decNumberIsNormal -- test normality of a decNumber */
3564 /* dn is the decNumber to test */
3565 /* set is the context to use for Emin */
3566 /* returns 1 if |dn| is finite and >=Nmin, 0 otherwise */
3567 /* ------------------------------------------------------------------ */
3568 Int decNumberIsNormal(const decNumber *dn, decContext *set) {
3569 Int ae; /* adjusted exponent */
3570 #if DECCHECK
3571 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
3572 #endif
3574 if (decNumberIsSpecial(dn)) return 0; /* not finite */
3575 if (decNumberIsZero(dn)) return 0; /* not non-zero */
3577 ae=dn->exponent+dn->digits-1; /* adjusted exponent */
3578 if (ae<set->emin) return 0; /* is subnormal */
3579 return 1;
3580 } /* decNumberIsNormal */
3582 /* ------------------------------------------------------------------ */
3583 /* decNumberIsSubnormal -- test subnormality of a decNumber */
3584 /* dn is the decNumber to test */
3585 /* set is the context to use for Emin */
3586 /* returns 1 if |dn| is finite, non-zero, and <Nmin, 0 otherwise */
3587 /* ------------------------------------------------------------------ */
3588 Int decNumberIsSubnormal(const decNumber *dn, decContext *set) {
3589 Int ae; /* adjusted exponent */
3590 #if DECCHECK
3591 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
3592 #endif
3594 if (decNumberIsSpecial(dn)) return 0; /* not finite */
3595 if (decNumberIsZero(dn)) return 0; /* not non-zero */
3597 ae=dn->exponent+dn->digits-1; /* adjusted exponent */
3598 if (ae<set->emin) return 1; /* is subnormal */
3599 return 0;
3600 } /* decNumberIsSubnormal */
3602 /* ------------------------------------------------------------------ */
3603 /* decNumberTrim -- remove insignificant zeros */
3604 /* */
3605 /* dn is the number to trim */
3606 /* returns dn */
3607 /* */
3608 /* All fields are updated as required. This is a utility operation, */
3609 /* so special values are unchanged and no error is possible. */
3610 /* ------------------------------------------------------------------ */
3611 decNumber * decNumberTrim(decNumber *dn) {
3612 Int dropped; /* work */
3613 decContext set; /* .. */
3614 #if DECCHECK
3615 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, DECUNCONT)) return dn;
3616 #endif
3617 decContextDefault(&set, DEC_INIT_BASE); /* clamp=0 */
3618 return decTrim(dn, &set, 0, &dropped);
3619 } /* decNumberTrim */
3621 /* ------------------------------------------------------------------ */
3622 /* decNumberVersion -- return the name and version of this module */
3623 /* */
3624 /* No error is possible. */
3625 /* ------------------------------------------------------------------ */
3626 const char * decNumberVersion(void) {
3627 return DECVERSION;
3628 } /* decNumberVersion */
3630 /* ------------------------------------------------------------------ */
3631 /* decNumberZero -- set a number to 0 */
3632 /* */
3633 /* dn is the number to set, with space for one digit */
3634 /* returns dn */
3635 /* */
3636 /* No error is possible. */
3637 /* ------------------------------------------------------------------ */
3638 /* Memset is not used as it is much slower in some environments. */
3639 decNumber * decNumberZero(decNumber *dn) {
3641 #if DECCHECK
3642 if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
3643 #endif
3645 dn->bits=0;
3646 dn->exponent=0;
3647 dn->digits=1;
3648 dn->lsu[0]=0;
3649 return dn;
3650 } /* decNumberZero */
3652 /* ================================================================== */
3653 /* Local routines */
3654 /* ================================================================== */
3656 /* ------------------------------------------------------------------ */
3657 /* decToString -- lay out a number into a string */
3658 /* */
3659 /* dn is the number to lay out */
3660 /* string is where to lay out the number */
3661 /* eng is 1 if Engineering, 0 if Scientific */
3662 /* */
3663 /* string must be at least dn->digits+14 characters long */
3664 /* No error is possible. */
3665 /* */
3666 /* Note that this routine can generate a -0 or 0.000. These are */
3667 /* never generated in subset to-number or arithmetic, but can occur */
3668 /* in non-subset arithmetic (e.g., -1*0 or 1.234-1.234). */
3669 /* ------------------------------------------------------------------ */
3670 /* If DECCHECK is enabled the string "?" is returned if a number is */
3671 /* invalid. */
3672 static void decToString(const decNumber *dn, char *string, Flag eng) {
3673 Int exp=dn->exponent; /* local copy */
3674 Int e; /* E-part value */
3675 Int pre; /* digits before the '.' */
3676 Int cut; /* for counting digits in a Unit */
3677 char *c=string; /* work [output pointer] */
3678 const Unit *up=dn->lsu+D2U(dn->digits)-1; /* -> msu [input pointer] */
3679 uInt u, pow; /* work */
3681 #if DECCHECK
3682 if (decCheckOperands(DECUNRESU, dn, DECUNUSED, DECUNCONT)) {
3683 strcpy(string, "?");
3684 return;}
3685 #endif
3687 if (decNumberIsNegative(dn)) { /* Negatives get a minus */
3688 *c='-';
3689 c++;
3691 if (dn->bits&DECSPECIAL) { /* Is a special value */
3692 if (decNumberIsInfinite(dn)) {
3693 strcpy(c, "Inf");
3694 strcpy(c+3, "inity");
3695 return;}
3696 /* a NaN */
3697 if (dn->bits&DECSNAN) { /* signalling NaN */
3698 *c='s';
3699 c++;
3701 strcpy(c, "NaN");
3702 c+=3; /* step past */
3703 /* if not a clean non-zero coefficient, that's all there is in a */
3704 /* NaN string */
3705 if (exp!=0 || (*dn->lsu==0 && dn->digits==1)) return;
3706 /* [drop through to add integer] */
3709 /* calculate how many digits in msu, and hence first cut */
3710 cut=MSUDIGITS(dn->digits); /* [faster than remainder] */
3711 cut--; /* power of ten for digit */
3713 if (exp==0) { /* simple integer [common fastpath] */
3714 for (;up>=dn->lsu; up--) { /* each Unit from msu */
3715 u=*up; /* contains DECDPUN digits to lay out */
3716 for (; cut>=0; c++, cut--) TODIGIT(u, cut, c, pow);
3717 cut=DECDPUN-1; /* next Unit has all digits */
3719 *c='\0'; /* terminate the string */
3720 return;}
3722 /* non-0 exponent -- assume plain form */
3723 pre=dn->digits+exp; /* digits before '.' */
3724 e=0; /* no E */
3725 if ((exp>0) || (pre<-5)) { /* need exponential form */
3726 e=exp+dn->digits-1; /* calculate E value */
3727 pre=1; /* assume one digit before '.' */
3728 if (eng && (e!=0)) { /* engineering: may need to adjust */
3729 Int adj; /* adjustment */
3730 /* The C remainder operator is undefined for negative numbers, so */
3731 /* a positive remainder calculation must be used here */
3732 if (e<0) {
3733 adj=(-e)%3;
3734 if (adj!=0) adj=3-adj;
3736 else { /* e>0 */
3737 adj=e%3;
3739 e=e-adj;
3740 /* if dealing with zero still produce an exponent which is a */
3741 /* multiple of three, as expected, but there will only be the */
3742 /* one zero before the E, still. Otherwise note the padding. */
3743 if (!ISZERO(dn)) pre+=adj;
3744 else { /* is zero */
3745 if (adj!=0) { /* 0.00Esnn needed */
3746 e=e+3;
3747 pre=-(2-adj);
3749 } /* zero */
3750 } /* eng */
3751 } /* need exponent */
3753 /* lay out the digits of the coefficient, adding 0s and . as needed */
3754 u=*up;
3755 if (pre>0) { /* xxx.xxx or xx00 (engineering) form */
3756 Int n=pre;
3757 for (; pre>0; pre--, c++, cut--) {
3758 if (cut<0) { /* need new Unit */
3759 if (up==dn->lsu) break; /* out of input digits (pre>digits) */
3760 up--;
3761 cut=DECDPUN-1;
3762 u=*up;
3764 TODIGIT(u, cut, c, pow);
3766 if (n<dn->digits) { /* more to come, after '.' */
3767 *c='.'; c++;
3768 for (;; c++, cut--) {
3769 if (cut<0) { /* need new Unit */
3770 if (up==dn->lsu) break; /* out of input digits */
3771 up--;
3772 cut=DECDPUN-1;
3773 u=*up;
3775 TODIGIT(u, cut, c, pow);
3778 else for (; pre>0; pre--, c++) *c='0'; /* 0 padding (for engineering) needed */
3780 else { /* 0.xxx or 0.000xxx form */
3781 *c='0'; c++;
3782 *c='.'; c++;
3783 for (; pre<0; pre++, c++) *c='0'; /* add any 0's after '.' */
3784 for (; ; c++, cut--) {
3785 if (cut<0) { /* need new Unit */
3786 if (up==dn->lsu) break; /* out of input digits */
3787 up--;
3788 cut=DECDPUN-1;
3789 u=*up;
3791 TODIGIT(u, cut, c, pow);
3795 /* Finally add the E-part, if needed. It will never be 0, has a
3796 base maximum and minimum of +999999999 through -999999999, but
3797 could range down to -1999999998 for anormal numbers */
3798 if (e!=0) {
3799 Flag had=0; /* 1=had non-zero */
3800 *c='E'; c++;
3801 *c='+'; c++; /* assume positive */
3802 u=e; /* .. */
3803 if (e<0) {
3804 *(c-1)='-'; /* oops, need - */
3805 u=-e; /* uInt, please */
3807 /* lay out the exponent [_itoa or equivalent is not ANSI C] */
3808 for (cut=9; cut>=0; cut--) {
3809 TODIGIT(u, cut, c, pow);
3810 if (*c=='0' && !had) continue; /* skip leading zeros */
3811 had=1; /* had non-0 */
3812 c++; /* step for next */
3813 } /* cut */
3815 *c='\0'; /* terminate the string (all paths) */
3816 return;
3817 } /* decToString */
3819 /* ------------------------------------------------------------------ */
3820 /* decAddOp -- add/subtract operation */
3821 /* */
3822 /* This computes C = A + B */
3823 /* */
3824 /* res is C, the result. C may be A and/or B (e.g., X=X+X) */
3825 /* lhs is A */
3826 /* rhs is B */
3827 /* set is the context */
3828 /* negate is DECNEG if rhs should be negated, or 0 otherwise */
3829 /* status accumulates status for the caller */
3830 /* */
3831 /* C must have space for set->digits digits. */
3832 /* Inexact in status must be 0 for correct Exact zero sign in result */
3833 /* ------------------------------------------------------------------ */
3834 /* If possible, the coefficient is calculated directly into C. */
3835 /* However, if: */
3836 /* -- a digits+1 calculation is needed because the numbers are */
3837 /* unaligned and span more than set->digits digits */
3838 /* -- a carry to digits+1 digits looks possible */
3839 /* -- C is the same as A or B, and the result would destructively */
3840 /* overlap the A or B coefficient */
3841 /* then the result must be calculated into a temporary buffer. In */
3842 /* this case a local (stack) buffer is used if possible, and only if */
3843 /* too long for that does malloc become the final resort. */
3844 /* */
3845 /* Misalignment is handled as follows: */
3846 /* Apad: (AExp>BExp) Swap operands and proceed as for BExp>AExp. */
3847 /* BPad: Apply the padding by a combination of shifting (whole */
3848 /* units) and multiplication (part units). */
3849 /* */
3850 /* Addition, especially x=x+1, is speed-critical. */
3851 /* The static buffer is larger than might be expected to allow for */
3852 /* calls from higher-level functions (notably exp). */
3853 /* ------------------------------------------------------------------ */
3854 static decNumber * decAddOp(decNumber *res, const decNumber *lhs,
3855 const decNumber *rhs, decContext *set,
3856 uByte negate, uInt *status) {
3857 #if DECSUBSET
3858 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */
3859 decNumber *allocrhs=NULL; /* .., rhs */
3860 #endif
3861 Int rhsshift; /* working shift (in Units) */
3862 Int maxdigits; /* longest logical length */
3863 Int mult; /* multiplier */
3864 Int residue; /* rounding accumulator */
3865 uByte bits; /* result bits */
3866 Flag diffsign; /* non-0 if arguments have different sign */
3867 Unit *acc; /* accumulator for result */
3868 Unit accbuff[SD2U(DECBUFFER*2+20)]; /* local buffer [*2+20 reduces many */
3869 /* allocations when called from */
3870 /* other operations, notable exp] */
3871 Unit *allocacc=NULL; /* -> allocated acc buffer, iff allocated */
3872 Int reqdigits=set->digits; /* local copy; requested DIGITS */
3873 Int padding; /* work */
3875 #if DECCHECK
3876 if (decCheckOperands(res, lhs, rhs, set)) return res;
3877 #endif
3879 do { /* protect allocated storage */
3880 #if DECSUBSET
3881 if (!set->extended) {
3882 /* reduce operands and set lostDigits status, as needed */
3883 if (lhs->digits>reqdigits) {
3884 alloclhs=decRoundOperand(lhs, set, status);
3885 if (alloclhs==NULL) break;
3886 lhs=alloclhs;
3888 if (rhs->digits>reqdigits) {
3889 allocrhs=decRoundOperand(rhs, set, status);
3890 if (allocrhs==NULL) break;
3891 rhs=allocrhs;
3894 #endif
3895 /* [following code does not require input rounding] */
3897 /* note whether signs differ [used all paths] */
3898 diffsign=(Flag)((lhs->bits^rhs->bits^negate)&DECNEG);
3900 /* handle infinities and NaNs */
3901 if (SPECIALARGS) { /* a special bit set */
3902 if (SPECIALARGS & (DECSNAN | DECNAN)) /* a NaN */
3903 decNaNs(res, lhs, rhs, set, status);
3904 else { /* one or two infinities */
3905 if (decNumberIsInfinite(lhs)) { /* LHS is infinity */
3906 /* two infinities with different signs is invalid */
3907 if (decNumberIsInfinite(rhs) && diffsign) {
3908 *status|=DEC_Invalid_operation;
3909 break;
3911 bits=lhs->bits & DECNEG; /* get sign from LHS */
3913 else bits=(rhs->bits^negate) & DECNEG;/* RHS must be Infinity */
3914 bits|=DECINF;
3915 decNumberZero(res);
3916 res->bits=bits; /* set +/- infinity */
3917 } /* an infinity */
3918 break;
3921 /* Quick exit for add 0s; return the non-0, modified as need be */
3922 if (ISZERO(lhs)) {
3923 Int adjust; /* work */
3924 Int lexp=lhs->exponent; /* save in case LHS==RES */
3925 bits=lhs->bits; /* .. */
3926 residue=0; /* clear accumulator */
3927 decCopyFit(res, rhs, set, &residue, status); /* copy (as needed) */
3928 res->bits^=negate; /* flip if rhs was negated */
3929 #if DECSUBSET
3930 if (set->extended) { /* exponents on zeros count */
3931 #endif
3932 /* exponent will be the lower of the two */
3933 adjust=lexp-res->exponent; /* adjustment needed [if -ve] */
3934 if (ISZERO(res)) { /* both 0: special IEEE 854 rules */
3935 if (adjust<0) res->exponent=lexp; /* set exponent */
3936 /* 0-0 gives +0 unless rounding to -infinity, and -0-0 gives -0 */
3937 if (diffsign) {
3938 if (set->round!=DEC_ROUND_FLOOR) res->bits=0;
3939 else res->bits=DECNEG; /* preserve 0 sign */
3942 else { /* non-0 res */
3943 if (adjust<0) { /* 0-padding needed */
3944 if ((res->digits-adjust)>set->digits) {
3945 adjust=res->digits-set->digits; /* to fit exactly */
3946 *status|=DEC_Rounded; /* [but exact] */
3948 res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
3949 res->exponent+=adjust; /* set the exponent. */
3951 } /* non-0 res */
3952 #if DECSUBSET
3953 } /* extended */
3954 #endif
3955 decFinish(res, set, &residue, status); /* clean and finalize */
3956 break;}
3958 if (ISZERO(rhs)) { /* [lhs is non-zero] */
3959 Int adjust; /* work */
3960 Int rexp=rhs->exponent; /* save in case RHS==RES */
3961 bits=rhs->bits; /* be clean */
3962 residue=0; /* clear accumulator */
3963 decCopyFit(res, lhs, set, &residue, status); /* copy (as needed) */
3964 #if DECSUBSET
3965 if (set->extended) { /* exponents on zeros count */
3966 #endif
3967 /* exponent will be the lower of the two */
3968 /* [0-0 case handled above] */
3969 adjust=rexp-res->exponent; /* adjustment needed [if -ve] */
3970 if (adjust<0) { /* 0-padding needed */
3971 if ((res->digits-adjust)>set->digits) {
3972 adjust=res->digits-set->digits; /* to fit exactly */
3973 *status|=DEC_Rounded; /* [but exact] */
3975 res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
3976 res->exponent+=adjust; /* set the exponent. */
3978 #if DECSUBSET
3979 } /* extended */
3980 #endif
3981 decFinish(res, set, &residue, status); /* clean and finalize */
3982 break;}
3984 /* [NB: both fastpath and mainpath code below assume these cases */
3985 /* (notably 0-0) have already been handled] */
3987 /* calculate the padding needed to align the operands */
3988 padding=rhs->exponent-lhs->exponent;
3990 /* Fastpath cases where the numbers are aligned and normal, the RHS */
3991 /* is all in one unit, no operand rounding is needed, and no carry, */
3992 /* lengthening, or borrow is needed */
3993 if (padding==0
3994 && rhs->digits<=DECDPUN
3995 && rhs->exponent>=set->emin /* [some normals drop through] */
3996 && rhs->exponent<=set->emax-set->digits+1 /* [could clamp] */
3997 && rhs->digits<=reqdigits
3998 && lhs->digits<=reqdigits) {
3999 Int partial=*lhs->lsu;
4000 if (!diffsign) { /* adding */
4001 partial+=*rhs->lsu;
4002 if ((partial<=DECDPUNMAX) /* result fits in unit */
4003 && (lhs->digits>=DECDPUN || /* .. and no digits-count change */
4004 partial<(Int)powers[lhs->digits])) { /* .. */
4005 if (res!=lhs) decNumberCopy(res, lhs); /* not in place */
4006 *res->lsu=(Unit)partial; /* [copy could have overwritten RHS] */
4007 break;
4009 /* else drop out for careful add */
4011 else { /* signs differ */
4012 partial-=*rhs->lsu;
4013 if (partial>0) { /* no borrow needed, and non-0 result */
4014 if (res!=lhs) decNumberCopy(res, lhs); /* not in place */
4015 *res->lsu=(Unit)partial;
4016 /* this could have reduced digits [but result>0] */
4017 res->digits=decGetDigits(res->lsu, D2U(res->digits));
4018 break;
4020 /* else drop out for careful subtract */
4024 /* Now align (pad) the lhs or rhs so they can be added or */
4025 /* subtracted, as necessary. If one number is much larger than */
4026 /* the other (that is, if in plain form there is a least one */
4027 /* digit between the lowest digit of one and the highest of the */
4028 /* other) padding with up to DIGITS-1 trailing zeros may be */
4029 /* needed; then apply rounding (as exotic rounding modes may be */
4030 /* affected by the residue). */
4031 rhsshift=0; /* rhs shift to left (padding) in Units */
4032 bits=lhs->bits; /* assume sign is that of LHS */
4033 mult=1; /* likely multiplier */
4035 /* [if padding==0 the operands are aligned; no padding is needed] */
4036 if (padding!=0) {
4037 /* some padding needed; always pad the RHS, as any required */
4038 /* padding can then be effected by a simple combination of */
4039 /* shifts and a multiply */
4040 Flag swapped=0;
4041 if (padding<0) { /* LHS needs the padding */
4042 const decNumber *t;
4043 padding=-padding; /* will be +ve */
4044 bits=(uByte)(rhs->bits^negate); /* assumed sign is now that of RHS */
4045 t=lhs; lhs=rhs; rhs=t;
4046 swapped=1;
4049 /* If, after pad, rhs would be longer than lhs by digits+1 or */
4050 /* more then lhs cannot affect the answer, except as a residue, */
4051 /* so only need to pad up to a length of DIGITS+1. */
4052 if (rhs->digits+padding > lhs->digits+reqdigits+1) {
4053 /* The RHS is sufficient */
4054 /* for residue use the relative sign indication... */
4055 Int shift=reqdigits-rhs->digits; /* left shift needed */
4056 residue=1; /* residue for rounding */
4057 if (diffsign) residue=-residue; /* signs differ */
4058 /* copy, shortening if necessary */
4059 decCopyFit(res, rhs, set, &residue, status);
4060 /* if it was already shorter, then need to pad with zeros */
4061 if (shift>0) {
4062 res->digits=decShiftToMost(res->lsu, res->digits, shift);
4063 res->exponent-=shift; /* adjust the exponent. */
4065 /* flip the result sign if unswapped and rhs was negated */
4066 if (!swapped) res->bits^=negate;
4067 decFinish(res, set, &residue, status); /* done */
4068 break;}
4070 /* LHS digits may affect result */
4071 rhsshift=D2U(padding+1)-1; /* this much by Unit shift .. */
4072 mult=powers[padding-(rhsshift*DECDPUN)]; /* .. this by multiplication */
4073 } /* padding needed */
4075 if (diffsign) mult=-mult; /* signs differ */
4077 /* determine the longer operand */
4078 maxdigits=rhs->digits+padding; /* virtual length of RHS */
4079 if (lhs->digits>maxdigits) maxdigits=lhs->digits;
4081 /* Decide on the result buffer to use; if possible place directly */
4082 /* into result. */
4083 acc=res->lsu; /* assume add direct to result */
4084 /* If destructive overlap, or the number is too long, or a carry or */
4085 /* borrow to DIGITS+1 might be possible, a buffer must be used. */
4086 /* [Might be worth more sophisticated tests when maxdigits==reqdigits] */
4087 if ((maxdigits>=reqdigits) /* is, or could be, too large */
4088 || (res==rhs && rhsshift>0)) { /* destructive overlap */
4089 /* buffer needed, choose it; units for maxdigits digits will be */
4090 /* needed, +1 Unit for carry or borrow */
4091 Int need=D2U(maxdigits)+1;
4092 acc=accbuff; /* assume use local buffer */
4093 if (need*sizeof(Unit)>sizeof(accbuff)) {
4094 /* printf("malloc add %ld %ld\n", need, sizeof(accbuff)); */
4095 allocacc=(Unit *)malloc(need*sizeof(Unit));
4096 if (allocacc==NULL) { /* hopeless -- abandon */
4097 *status|=DEC_Insufficient_storage;
4098 break;}
4099 acc=allocacc;
4103 res->bits=(uByte)(bits&DECNEG); /* it's now safe to overwrite.. */
4104 res->exponent=lhs->exponent; /* .. operands (even if aliased) */
4106 #if DECTRACE
4107 decDumpAr('A', lhs->lsu, D2U(lhs->digits));
4108 decDumpAr('B', rhs->lsu, D2U(rhs->digits));
4109 printf(" :h: %ld %ld\n", rhsshift, mult);
4110 #endif
4112 /* add [A+B*m] or subtract [A+B*(-m)] */
4113 res->digits=decUnitAddSub(lhs->lsu, D2U(lhs->digits),
4114 rhs->lsu, D2U(rhs->digits),
4115 rhsshift, acc, mult)
4116 *DECDPUN; /* [units -> digits] */
4117 if (res->digits<0) { /* borrowed... */
4118 res->digits=-res->digits;
4119 res->bits^=DECNEG; /* flip the sign */
4121 #if DECTRACE
4122 decDumpAr('+', acc, D2U(res->digits));
4123 #endif
4125 /* If a buffer was used the result must be copied back, possibly */
4126 /* shortening. (If no buffer was used then the result must have */
4127 /* fit, so can't need rounding and residue must be 0.) */
4128 residue=0; /* clear accumulator */
4129 if (acc!=res->lsu) {
4130 #if DECSUBSET
4131 if (set->extended) { /* round from first significant digit */
4132 #endif
4133 /* remove leading zeros that were added due to rounding up to */
4134 /* integral Units -- before the test for rounding. */
4135 if (res->digits>reqdigits)
4136 res->digits=decGetDigits(acc, D2U(res->digits));
4137 decSetCoeff(res, set, acc, res->digits, &residue, status);
4138 #if DECSUBSET
4140 else { /* subset arithmetic rounds from original significant digit */
4141 /* May have an underestimate. This only occurs when both */
4142 /* numbers fit in DECDPUN digits and are padding with a */
4143 /* negative multiple (-10, -100...) and the top digit(s) become */
4144 /* 0. (This only matters when using X3.274 rules where the */
4145 /* leading zero could be included in the rounding.) */
4146 if (res->digits<maxdigits) {
4147 *(acc+D2U(res->digits))=0; /* ensure leading 0 is there */
4148 res->digits=maxdigits;
4150 else {
4151 /* remove leading zeros that added due to rounding up to */
4152 /* integral Units (but only those in excess of the original */
4153 /* maxdigits length, unless extended) before test for rounding. */
4154 if (res->digits>reqdigits) {
4155 res->digits=decGetDigits(acc, D2U(res->digits));
4156 if (res->digits<maxdigits) res->digits=maxdigits;
4159 decSetCoeff(res, set, acc, res->digits, &residue, status);
4160 /* Now apply rounding if needed before removing leading zeros. */
4161 /* This is safe because subnormals are not a possibility */
4162 if (residue!=0) {
4163 decApplyRound(res, set, residue, status);
4164 residue=0; /* did what needed to be done */
4166 } /* subset */
4167 #endif
4168 } /* used buffer */
4170 /* strip leading zeros [these were left on in case of subset subtract] */
4171 res->digits=decGetDigits(res->lsu, D2U(res->digits));
4173 /* apply checks and rounding */
4174 decFinish(res, set, &residue, status);
4176 /* "When the sum of two operands with opposite signs is exactly */
4177 /* zero, the sign of that sum shall be '+' in all rounding modes */
4178 /* except round toward -Infinity, in which mode that sign shall be */
4179 /* '-'." [Subset zeros also never have '-', set by decFinish.] */
4180 if (ISZERO(res) && diffsign
4181 #if DECSUBSET
4182 && set->extended
4183 #endif
4184 && (*status&DEC_Inexact)==0) {
4185 if (set->round==DEC_ROUND_FLOOR) res->bits|=DECNEG; /* sign - */
4186 else res->bits&=~DECNEG; /* sign + */
4188 } while(0); /* end protected */
4190 if (allocacc!=NULL) free(allocacc); /* drop any storage used */
4191 #if DECSUBSET
4192 if (allocrhs!=NULL) free(allocrhs); /* .. */
4193 if (alloclhs!=NULL) free(alloclhs); /* .. */
4194 #endif
4195 return res;
4196 } /* decAddOp */
4198 /* ------------------------------------------------------------------ */
4199 /* decDivideOp -- division operation */
4200 /* */
4201 /* This routine performs the calculations for all four division */
4202 /* operators (divide, divideInteger, remainder, remainderNear). */
4203 /* */
4204 /* C=A op B */
4205 /* */
4206 /* res is C, the result. C may be A and/or B (e.g., X=X/X) */
4207 /* lhs is A */
4208 /* rhs is B */
4209 /* set is the context */
4210 /* op is DIVIDE, DIVIDEINT, REMAINDER, or REMNEAR respectively. */
4211 /* status is the usual accumulator */
4212 /* */
4213 /* C must have space for set->digits digits. */
4214 /* */
4215 /* ------------------------------------------------------------------ */
4216 /* The underlying algorithm of this routine is the same as in the */
4217 /* 1981 S/370 implementation, that is, non-restoring long division */
4218 /* with bi-unit (rather than bi-digit) estimation for each unit */
4219 /* multiplier. In this pseudocode overview, complications for the */
4220 /* Remainder operators and division residues for exact rounding are */
4221 /* omitted for clarity. */
4222 /* */
4223 /* Prepare operands and handle special values */
4224 /* Test for x/0 and then 0/x */
4225 /* Exp =Exp1 - Exp2 */
4226 /* Exp =Exp +len(var1) -len(var2) */
4227 /* Sign=Sign1 * Sign2 */
4228 /* Pad accumulator (Var1) to double-length with 0's (pad1) */
4229 /* Pad Var2 to same length as Var1 */
4230 /* msu2pair/plus=1st 2 or 1 units of var2, +1 to allow for round */
4231 /* have=0 */
4232 /* Do until (have=digits+1 OR residue=0) */
4233 /* if exp<0 then if integer divide/residue then leave */
4234 /* this_unit=0 */
4235 /* Do forever */
4236 /* compare numbers */
4237 /* if <0 then leave inner_loop */
4238 /* if =0 then (* quick exit without subtract *) do */
4239 /* this_unit=this_unit+1; output this_unit */
4240 /* leave outer_loop; end */
4241 /* Compare lengths of numbers (mantissae): */
4242 /* If same then tops2=msu2pair -- {units 1&2 of var2} */
4243 /* else tops2=msu2plus -- {0, unit 1 of var2} */
4244 /* tops1=first_unit_of_Var1*10**DECDPUN +second_unit_of_var1 */
4245 /* mult=tops1/tops2 -- Good and safe guess at divisor */
4246 /* if mult=0 then mult=1 */
4247 /* this_unit=this_unit+mult */
4248 /* subtract */
4249 /* end inner_loop */
4250 /* if have\=0 | this_unit\=0 then do */
4251 /* output this_unit */
4252 /* have=have+1; end */
4253 /* var2=var2/10 */
4254 /* exp=exp-1 */
4255 /* end outer_loop */
4256 /* exp=exp+1 -- set the proper exponent */
4257 /* if have=0 then generate answer=0 */
4258 /* Return (Result is defined by Var1) */
4259 /* */
4260 /* ------------------------------------------------------------------ */
4261 /* Two working buffers are needed during the division; one (digits+ */
4262 /* 1) to accumulate the result, and the other (up to 2*digits+1) for */
4263 /* long subtractions. These are acc and var1 respectively. */
4264 /* var1 is a copy of the lhs coefficient, var2 is the rhs coefficient.*/
4265 /* The static buffers may be larger than might be expected to allow */
4266 /* for calls from higher-level functions (notably exp). */
4267 /* ------------------------------------------------------------------ */
4268 static decNumber * decDivideOp(decNumber *res,
4269 const decNumber *lhs, const decNumber *rhs,
4270 decContext *set, Flag op, uInt *status) {
4271 #if DECSUBSET
4272 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */
4273 decNumber *allocrhs=NULL; /* .., rhs */
4274 #endif
4275 Unit accbuff[SD2U(DECBUFFER+DECDPUN+10)]; /* local buffer */
4276 Unit *acc=accbuff; /* -> accumulator array for result */
4277 Unit *allocacc=NULL; /* -> allocated buffer, iff allocated */
4278 Unit *accnext; /* -> where next digit will go */
4279 Int acclength; /* length of acc needed [Units] */
4280 Int accunits; /* count of units accumulated */
4281 Int accdigits; /* count of digits accumulated */
4283 Unit varbuff[SD2U(DECBUFFER*2+DECDPUN)*sizeof(Unit)]; /* buffer for var1 */
4284 Unit *var1=varbuff; /* -> var1 array for long subtraction */
4285 Unit *varalloc=NULL; /* -> allocated buffer, iff used */
4286 Unit *msu1; /* -> msu of var1 */
4288 const Unit *var2; /* -> var2 array */
4289 const Unit *msu2; /* -> msu of var2 */
4290 Int msu2plus; /* msu2 plus one [does not vary] */
4291 eInt msu2pair; /* msu2 pair plus one [does not vary] */
4293 Int var1units, var2units; /* actual lengths */
4294 Int var2ulen; /* logical length (units) */
4295 Int var1initpad=0; /* var1 initial padding (digits) */
4296 Int maxdigits; /* longest LHS or required acc length */
4297 Int mult; /* multiplier for subtraction */
4298 Unit thisunit; /* current unit being accumulated */
4299 Int residue; /* for rounding */
4300 Int reqdigits=set->digits; /* requested DIGITS */
4301 Int exponent; /* working exponent */
4302 Int maxexponent=0; /* DIVIDE maximum exponent if unrounded */
4303 uByte bits; /* working sign */
4304 Unit *target; /* work */
4305 const Unit *source; /* .. */
4306 uLong const *pow; /* .. */
4307 Int shift, cut; /* .. */
4308 #if DECSUBSET
4309 Int dropped; /* work */
4310 #endif
4312 #if DECCHECK
4313 if (decCheckOperands(res, lhs, rhs, set)) return res;
4314 #endif
4316 do { /* protect allocated storage */
4317 #if DECSUBSET
4318 if (!set->extended) {
4319 /* reduce operands and set lostDigits status, as needed */
4320 if (lhs->digits>reqdigits) {
4321 alloclhs=decRoundOperand(lhs, set, status);
4322 if (alloclhs==NULL) break;
4323 lhs=alloclhs;
4325 if (rhs->digits>reqdigits) {
4326 allocrhs=decRoundOperand(rhs, set, status);
4327 if (allocrhs==NULL) break;
4328 rhs=allocrhs;
4331 #endif
4332 /* [following code does not require input rounding] */
4334 bits=(lhs->bits^rhs->bits)&DECNEG; /* assumed sign for divisions */
4336 /* handle infinities and NaNs */
4337 if (SPECIALARGS) { /* a special bit set */
4338 if (SPECIALARGS & (DECSNAN | DECNAN)) { /* one or two NaNs */
4339 decNaNs(res, lhs, rhs, set, status);
4340 break;
4342 /* one or two infinities */
4343 if (decNumberIsInfinite(lhs)) { /* LHS (dividend) is infinite */
4344 if (decNumberIsInfinite(rhs) || /* two infinities are invalid .. */
4345 op & (REMAINDER | REMNEAR)) { /* as is remainder of infinity */
4346 *status|=DEC_Invalid_operation;
4347 break;
4349 /* [Note that infinity/0 raises no exceptions] */
4350 decNumberZero(res);
4351 res->bits=bits|DECINF; /* set +/- infinity */
4352 break;
4354 else { /* RHS (divisor) is infinite */
4355 residue=0;
4356 if (op&(REMAINDER|REMNEAR)) {
4357 /* result is [finished clone of] lhs */
4358 decCopyFit(res, lhs, set, &residue, status);
4360 else { /* a division */
4361 decNumberZero(res);
4362 res->bits=bits; /* set +/- zero */
4363 /* for DIVIDEINT the exponent is always 0. For DIVIDE, result */
4364 /* is a 0 with infinitely negative exponent, clamped to minimum */
4365 if (op&DIVIDE) {
4366 res->exponent=set->emin-set->digits+1;
4367 *status|=DEC_Clamped;
4370 decFinish(res, set, &residue, status);
4371 break;
4375 /* handle 0 rhs (x/0) */
4376 if (ISZERO(rhs)) { /* x/0 is always exceptional */
4377 if (ISZERO(lhs)) {
4378 decNumberZero(res); /* [after lhs test] */
4379 *status|=DEC_Division_undefined;/* 0/0 will become NaN */
4381 else {
4382 decNumberZero(res);
4383 if (op&(REMAINDER|REMNEAR)) *status|=DEC_Invalid_operation;
4384 else {
4385 *status|=DEC_Division_by_zero; /* x/0 */
4386 res->bits=bits|DECINF; /* .. is +/- Infinity */
4389 break;}
4391 /* handle 0 lhs (0/x) */
4392 if (ISZERO(lhs)) { /* 0/x [x!=0] */
4393 #if DECSUBSET
4394 if (!set->extended) decNumberZero(res);
4395 else {
4396 #endif
4397 if (op&DIVIDE) {
4398 residue=0;
4399 exponent=lhs->exponent-rhs->exponent; /* ideal exponent */
4400 decNumberCopy(res, lhs); /* [zeros always fit] */
4401 res->bits=bits; /* sign as computed */
4402 res->exponent=exponent; /* exponent, too */
4403 decFinalize(res, set, &residue, status); /* check exponent */
4405 else if (op&DIVIDEINT) {
4406 decNumberZero(res); /* integer 0 */
4407 res->bits=bits; /* sign as computed */
4409 else { /* a remainder */
4410 exponent=rhs->exponent; /* [save in case overwrite] */
4411 decNumberCopy(res, lhs); /* [zeros always fit] */
4412 if (exponent<res->exponent) res->exponent=exponent; /* use lower */
4414 #if DECSUBSET
4416 #endif
4417 break;}
4419 /* Precalculate exponent. This starts off adjusted (and hence fits */
4420 /* in 31 bits) and becomes the usual unadjusted exponent as the */
4421 /* division proceeds. The order of evaluation is important, here, */
4422 /* to avoid wrap. */
4423 exponent=(lhs->exponent+lhs->digits)-(rhs->exponent+rhs->digits);
4425 /* If the working exponent is -ve, then some quick exits are */
4426 /* possible because the quotient is known to be <1 */
4427 /* [for REMNEAR, it needs to be < -1, as -0.5 could need work] */
4428 if (exponent<0 && !(op==DIVIDE)) {
4429 if (op&DIVIDEINT) {
4430 decNumberZero(res); /* integer part is 0 */
4431 #if DECSUBSET
4432 if (set->extended)
4433 #endif
4434 res->bits=bits; /* set +/- zero */
4435 break;}
4436 /* fastpath remainders so long as the lhs has the smaller */
4437 /* (or equal) exponent */
4438 if (lhs->exponent<=rhs->exponent) {
4439 if (op&REMAINDER || exponent<-1) {
4440 /* It is REMAINDER or safe REMNEAR; result is [finished */
4441 /* clone of] lhs (r = x - 0*y) */
4442 residue=0;
4443 decCopyFit(res, lhs, set, &residue, status);
4444 decFinish(res, set, &residue, status);
4445 break;
4447 /* [unsafe REMNEAR drops through] */
4449 } /* fastpaths */
4451 /* Long (slow) division is needed; roll up the sleeves... */
4453 /* The accumulator will hold the quotient of the division. */
4454 /* If it needs to be too long for stack storage, then allocate. */
4455 acclength=D2U(reqdigits+DECDPUN); /* in Units */
4456 if (acclength*sizeof(Unit)>sizeof(accbuff)) {
4457 /* printf("malloc dvacc %ld units\n", acclength); */
4458 allocacc=(Unit *)malloc(acclength*sizeof(Unit));
4459 if (allocacc==NULL) { /* hopeless -- abandon */
4460 *status|=DEC_Insufficient_storage;
4461 break;}
4462 acc=allocacc; /* use the allocated space */
4465 /* var1 is the padded LHS ready for subtractions. */
4466 /* If it needs to be too long for stack storage, then allocate. */
4467 /* The maximum units needed for var1 (long subtraction) is: */
4468 /* Enough for */
4469 /* (rhs->digits+reqdigits-1) -- to allow full slide to right */
4470 /* or (lhs->digits) -- to allow for long lhs */
4471 /* whichever is larger */
4472 /* +1 -- for rounding of slide to right */
4473 /* +1 -- for leading 0s */
4474 /* +1 -- for pre-adjust if a remainder or DIVIDEINT */
4475 /* [Note: unused units do not participate in decUnitAddSub data] */
4476 maxdigits=rhs->digits+reqdigits-1;
4477 if (lhs->digits>maxdigits) maxdigits=lhs->digits;
4478 var1units=D2U(maxdigits)+2;
4479 /* allocate a guard unit above msu1 for REMAINDERNEAR */
4480 if (!(op&DIVIDE)) var1units++;
4481 if ((var1units+1)*sizeof(Unit)>sizeof(varbuff)) {
4482 /* printf("malloc dvvar %ld units\n", var1units+1); */
4483 varalloc=(Unit *)malloc((var1units+1)*sizeof(Unit));
4484 if (varalloc==NULL) { /* hopeless -- abandon */
4485 *status|=DEC_Insufficient_storage;
4486 break;}
4487 var1=varalloc; /* use the allocated space */
4490 /* Extend the lhs and rhs to full long subtraction length. The lhs */
4491 /* is truly extended into the var1 buffer, with 0 padding, so a */
4492 /* subtract in place is always possible. The rhs (var2) has */
4493 /* virtual padding (implemented by decUnitAddSub). */
4494 /* One guard unit was allocated above msu1 for rem=rem+rem in */
4495 /* REMAINDERNEAR. */
4496 msu1=var1+var1units-1; /* msu of var1 */
4497 source=lhs->lsu+D2U(lhs->digits)-1; /* msu of input array */
4498 for (target=msu1; source>=lhs->lsu; source--, target--) *target=*source;
4499 for (; target>=var1; target--) *target=0;
4501 /* rhs (var2) is left-aligned with var1 at the start */
4502 var2ulen=var1units; /* rhs logical length (units) */
4503 var2units=D2U(rhs->digits); /* rhs actual length (units) */
4504 var2=rhs->lsu; /* -> rhs array */
4505 msu2=var2+var2units-1; /* -> msu of var2 [never changes] */
4506 /* now set up the variables which will be used for estimating the */
4507 /* multiplication factor. If these variables are not exact, add */
4508 /* 1 to make sure that the multiplier is never overestimated. */
4509 msu2plus=*msu2; /* it's value .. */
4510 if (var2units>1) msu2plus++; /* .. +1 if any more */
4511 msu2pair=(eInt)*msu2*(DECDPUNMAX+1);/* top two pair .. */
4512 if (var2units>1) { /* .. [else treat 2nd as 0] */
4513 msu2pair+=*(msu2-1); /* .. */
4514 if (var2units>2) msu2pair++; /* .. +1 if any more */
4517 /* The calculation is working in units, which may have leading zeros, */
4518 /* but the exponent was calculated on the assumption that they are */
4519 /* both left-aligned. Adjust the exponent to compensate: add the */
4520 /* number of leading zeros in var1 msu and subtract those in var2 msu. */
4521 /* [This is actually done by counting the digits and negating, as */
4522 /* lead1=DECDPUN-digits1, and similarly for lead2.] */
4523 for (pow=&powers[1]; *msu1>=*pow; pow++) exponent--;
4524 for (pow=&powers[1]; *msu2>=*pow; pow++) exponent++;
4526 /* Now, if doing an integer divide or remainder, ensure that */
4527 /* the result will be Unit-aligned. To do this, shift the var1 */
4528 /* accumulator towards least if need be. (It's much easier to */
4529 /* do this now than to reassemble the residue afterwards, if */
4530 /* doing a remainder.) Also ensure the exponent is not negative. */
4531 if (!(op&DIVIDE)) {
4532 Unit *u; /* work */
4533 /* save the initial 'false' padding of var1, in digits */
4534 var1initpad=(var1units-D2U(lhs->digits))*DECDPUN;
4535 /* Determine the shift to do. */
4536 if (exponent<0) cut=-exponent;
4537 else cut=DECDPUN-exponent%DECDPUN;
4538 decShiftToLeast(var1, var1units, cut);
4539 exponent+=cut; /* maintain numerical value */
4540 var1initpad-=cut; /* .. and reduce padding */
4541 /* clean any most-significant units which were just emptied */
4542 for (u=msu1; cut>=DECDPUN; cut-=DECDPUN, u--) *u=0;
4543 } /* align */
4544 else { /* is DIVIDE */
4545 maxexponent=lhs->exponent-rhs->exponent; /* save */
4546 /* optimization: if the first iteration will just produce 0, */
4547 /* preadjust to skip it [valid for DIVIDE only] */
4548 if (*msu1<*msu2) {
4549 var2ulen--; /* shift down */
4550 exponent-=DECDPUN; /* update the exponent */
4554 /* ---- start the long-division loops ------------------------------ */
4555 accunits=0; /* no units accumulated yet */
4556 accdigits=0; /* .. or digits */
4557 accnext=acc+acclength-1; /* -> msu of acc [NB: allows digits+1] */
4558 for (;;) { /* outer forever loop */
4559 thisunit=0; /* current unit assumed 0 */
4560 /* find the next unit */
4561 for (;;) { /* inner forever loop */
4562 /* strip leading zero units [from either pre-adjust or from */
4563 /* subtract last time around]. Leave at least one unit. */
4564 for (; *msu1==0 && msu1>var1; msu1--) var1units--;
4566 if (var1units<var2ulen) break; /* var1 too low for subtract */
4567 if (var1units==var2ulen) { /* unit-by-unit compare needed */
4568 /* compare the two numbers, from msu */
4569 const Unit *pv1, *pv2;
4570 Unit v2; /* units to compare */
4571 pv2=msu2; /* -> msu */
4572 for (pv1=msu1; ; pv1--, pv2--) {
4573 /* v1=*pv1 -- always OK */
4574 v2=0; /* assume in padding */
4575 if (pv2>=var2) v2=*pv2; /* in range */
4576 if (*pv1!=v2) break; /* no longer the same */
4577 if (pv1==var1) break; /* done; leave pv1 as is */
4579 /* here when all inspected or a difference seen */
4580 if (*pv1<v2) break; /* var1 too low to subtract */
4581 if (*pv1==v2) { /* var1 == var2 */
4582 /* reach here if var1 and var2 are identical; subtraction */
4583 /* would increase digit by one, and the residue will be 0 so */
4584 /* the calculation is done; leave the loop with residue=0. */
4585 thisunit++; /* as though subtracted */
4586 *var1=0; /* set var1 to 0 */
4587 var1units=1; /* .. */
4588 break; /* from inner */
4589 } /* var1 == var2 */
4590 /* *pv1>v2. Prepare for real subtraction; the lengths are equal */
4591 /* Estimate the multiplier (there's always a msu1-1)... */
4592 /* Bring in two units of var2 to provide a good estimate. */
4593 mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2pair);
4594 } /* lengths the same */
4595 else { /* var1units > var2ulen, so subtraction is safe */
4596 /* The var2 msu is one unit towards the lsu of the var1 msu, */
4597 /* so only one unit for var2 can be used. */
4598 mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2plus);
4600 if (mult==0) mult=1; /* must always be at least 1 */
4601 /* subtraction needed; var1 is > var2 */
4602 thisunit=(Unit)(thisunit+mult); /* accumulate */
4603 /* subtract var1-var2, into var1; only the overlap needs */
4604 /* processing, as this is an in-place calculation */
4605 shift=var2ulen-var2units;
4606 #if DECTRACE
4607 decDumpAr('1', &var1[shift], var1units-shift);
4608 decDumpAr('2', var2, var2units);
4609 printf("m=%ld\n", -mult);
4610 #endif
4611 decUnitAddSub(&var1[shift], var1units-shift,
4612 var2, var2units, 0,
4613 &var1[shift], -mult);
4614 #if DECTRACE
4615 decDumpAr('#', &var1[shift], var1units-shift);
4616 #endif
4617 /* var1 now probably has leading zeros; these are removed at the */
4618 /* top of the inner loop. */
4619 } /* inner loop */
4621 /* The next unit has been calculated in full; unless it's a */
4622 /* leading zero, add to acc */
4623 if (accunits!=0 || thisunit!=0) { /* is first or non-zero */
4624 *accnext=thisunit; /* store in accumulator */
4625 /* account exactly for the new digits */
4626 if (accunits==0) {
4627 accdigits++; /* at least one */
4628 for (pow=&powers[1]; thisunit>=*pow; pow++) accdigits++;
4630 else accdigits+=DECDPUN;
4631 accunits++; /* update count */
4632 accnext--; /* ready for next */
4633 if (accdigits>reqdigits) break; /* have enough digits */
4636 /* if the residue is zero, the operation is done (unless divide */
4637 /* or divideInteger and still not enough digits yet) */
4638 if (*var1==0 && var1units==1) { /* residue is 0 */
4639 if (op&(REMAINDER|REMNEAR)) break;
4640 if ((op&DIVIDE) && (exponent<=maxexponent)) break;
4641 /* [drop through if divideInteger] */
4643 /* also done enough if calculating remainder or integer */
4644 /* divide and just did the last ('units') unit */
4645 if (exponent==0 && !(op&DIVIDE)) break;
4647 /* to get here, var1 is less than var2, so divide var2 by the per- */
4648 /* Unit power of ten and go for the next digit */
4649 var2ulen--; /* shift down */
4650 exponent-=DECDPUN; /* update the exponent */
4651 } /* outer loop */
4653 /* ---- division is complete --------------------------------------- */
4654 /* here: acc has at least reqdigits+1 of good results (or fewer */
4655 /* if early stop), starting at accnext+1 (its lsu) */
4656 /* var1 has any residue at the stopping point */
4657 /* accunits is the number of digits collected in acc */
4658 if (accunits==0) { /* acc is 0 */
4659 accunits=1; /* show have a unit .. */
4660 accdigits=1; /* .. */
4661 *accnext=0; /* .. whose value is 0 */
4663 else accnext++; /* back to last placed */
4664 /* accnext now -> lowest unit of result */
4666 residue=0; /* assume no residue */
4667 if (op&DIVIDE) {
4668 /* record the presence of any residue, for rounding */
4669 if (*var1!=0 || var1units>1) residue=1;
4670 else { /* no residue */
4671 /* Had an exact division; clean up spurious trailing 0s. */
4672 /* There will be at most DECDPUN-1, from the final multiply, */
4673 /* and then only if the result is non-0 (and even) and the */
4674 /* exponent is 'loose'. */
4675 #if DECDPUN>1
4676 Unit lsu=*accnext;
4677 if (!(lsu&0x01) && (lsu!=0)) {
4678 /* count the trailing zeros */
4679 Int drop=0;
4680 for (;; drop++) { /* [will terminate because lsu!=0] */
4681 if (exponent>=maxexponent) break; /* don't chop real 0s */
4682 #if DECDPUN<=4
4683 if ((lsu-QUOT10(lsu, drop+1)
4684 *powers[drop+1])!=0) break; /* found non-0 digit */
4685 #else
4686 if (lsu%powers[drop+1]!=0) break; /* found non-0 digit */
4687 #endif
4688 exponent++;
4690 if (drop>0) {
4691 accunits=decShiftToLeast(accnext, accunits, drop);
4692 accdigits=decGetDigits(accnext, accunits);
4693 accunits=D2U(accdigits);
4694 /* [exponent was adjusted in the loop] */
4696 } /* neither odd nor 0 */
4697 #endif
4698 } /* exact divide */
4699 } /* divide */
4700 else /* op!=DIVIDE */ {
4701 /* check for coefficient overflow */
4702 if (accdigits+exponent>reqdigits) {
4703 *status|=DEC_Division_impossible;
4704 break;
4706 if (op & (REMAINDER|REMNEAR)) {
4707 /* [Here, the exponent will be 0, because var1 was adjusted */
4708 /* appropriately.] */
4709 Int postshift; /* work */
4710 Flag wasodd=0; /* integer was odd */
4711 Unit *quotlsu; /* for save */
4712 Int quotdigits; /* .. */
4714 bits=lhs->bits; /* remainder sign is always as lhs */
4716 /* Fastpath when residue is truly 0 is worthwhile [and */
4717 /* simplifies the code below] */
4718 if (*var1==0 && var1units==1) { /* residue is 0 */
4719 Int exp=lhs->exponent; /* save min(exponents) */
4720 if (rhs->exponent<exp) exp=rhs->exponent;
4721 decNumberZero(res); /* 0 coefficient */
4722 #if DECSUBSET
4723 if (set->extended)
4724 #endif
4725 res->exponent=exp; /* .. with proper exponent */
4726 res->bits=(uByte)(bits&DECNEG); /* [cleaned] */
4727 decFinish(res, set, &residue, status); /* might clamp */
4728 break;
4730 /* note if the quotient was odd */
4731 if (*accnext & 0x01) wasodd=1; /* acc is odd */
4732 quotlsu=accnext; /* save in case need to reinspect */
4733 quotdigits=accdigits; /* .. */
4735 /* treat the residue, in var1, as the value to return, via acc */
4736 /* calculate the unused zero digits. This is the smaller of: */
4737 /* var1 initial padding (saved above) */
4738 /* var2 residual padding, which happens to be given by: */
4739 postshift=var1initpad+exponent-lhs->exponent+rhs->exponent;
4740 /* [the 'exponent' term accounts for the shifts during divide] */
4741 if (var1initpad<postshift) postshift=var1initpad;
4743 /* shift var1 the requested amount, and adjust its digits */
4744 var1units=decShiftToLeast(var1, var1units, postshift);
4745 accnext=var1;
4746 accdigits=decGetDigits(var1, var1units);
4747 accunits=D2U(accdigits);
4749 exponent=lhs->exponent; /* exponent is smaller of lhs & rhs */
4750 if (rhs->exponent<exponent) exponent=rhs->exponent;
4752 /* Now correct the result if doing remainderNear; if it */
4753 /* (looking just at coefficients) is > rhs/2, or == rhs/2 and */
4754 /* the integer was odd then the result should be rem-rhs. */
4755 if (op&REMNEAR) {
4756 Int compare, tarunits; /* work */
4757 Unit *up; /* .. */
4758 /* calculate remainder*2 into the var1 buffer (which has */
4759 /* 'headroom' of an extra unit and hence enough space) */
4760 /* [a dedicated 'double' loop would be faster, here] */
4761 tarunits=decUnitAddSub(accnext, accunits, accnext, accunits,
4762 0, accnext, 1);
4763 /* decDumpAr('r', accnext, tarunits); */
4765 /* Here, accnext (var1) holds tarunits Units with twice the */
4766 /* remainder's coefficient, which must now be compared to the */
4767 /* RHS. The remainder's exponent may be smaller than the RHS's. */
4768 compare=decUnitCompare(accnext, tarunits, rhs->lsu, D2U(rhs->digits),
4769 rhs->exponent-exponent);
4770 if (compare==BADINT) { /* deep trouble */
4771 *status|=DEC_Insufficient_storage;
4772 break;}
4774 /* now restore the remainder by dividing by two; the lsu */
4775 /* is known to be even. */
4776 for (up=accnext; up<accnext+tarunits; up++) {
4777 Int half; /* half to add to lower unit */
4778 half=*up & 0x01;
4779 *up/=2; /* [shift] */
4780 if (!half) continue;
4781 *(up-1)+=(DECDPUNMAX+1)/2;
4783 /* [accunits still describes the original remainder length] */
4785 if (compare>0 || (compare==0 && wasodd)) { /* adjustment needed */
4786 Int exp, expunits, exprem; /* work */
4787 /* This is effectively causing round-up of the quotient, */
4788 /* so if it was the rare case where it was full and all */
4789 /* nines, it would overflow and hence division-impossible */
4790 /* should be raised */
4791 Flag allnines=0; /* 1 if quotient all nines */
4792 if (quotdigits==reqdigits) { /* could be borderline */
4793 for (up=quotlsu; ; up++) {
4794 if (quotdigits>DECDPUN) {
4795 if (*up!=DECDPUNMAX) break;/* non-nines */
4797 else { /* this is the last Unit */
4798 if (*up==powers[quotdigits]-1) allnines=1;
4799 break;
4801 quotdigits-=DECDPUN; /* checked those digits */
4802 } /* up */
4803 } /* borderline check */
4804 if (allnines) {
4805 *status|=DEC_Division_impossible;
4806 break;}
4808 /* rem-rhs is needed; the sign will invert. Again, var1 */
4809 /* can safely be used for the working Units array. */
4810 exp=rhs->exponent-exponent; /* RHS padding needed */
4811 /* Calculate units and remainder from exponent. */
4812 expunits=exp/DECDPUN;
4813 exprem=exp%DECDPUN;
4814 /* subtract [A+B*(-m)]; the result will always be negative */
4815 accunits=-decUnitAddSub(accnext, accunits,
4816 rhs->lsu, D2U(rhs->digits),
4817 expunits, accnext, -(Int)powers[exprem]);
4818 accdigits=decGetDigits(accnext, accunits); /* count digits exactly */
4819 accunits=D2U(accdigits); /* and recalculate the units for copy */
4820 /* [exponent is as for original remainder] */
4821 bits^=DECNEG; /* flip the sign */
4823 } /* REMNEAR */
4824 } /* REMAINDER or REMNEAR */
4825 } /* not DIVIDE */
4827 /* Set exponent and bits */
4828 res->exponent=exponent;
4829 res->bits=(uByte)(bits&DECNEG); /* [cleaned] */
4831 /* Now the coefficient. */
4832 decSetCoeff(res, set, accnext, accdigits, &residue, status);
4834 decFinish(res, set, &residue, status); /* final cleanup */
4836 #if DECSUBSET
4837 /* If a divide then strip trailing zeros if subset [after round] */
4838 if (!set->extended && (op==DIVIDE)) decTrim(res, set, 0, &dropped);
4839 #endif
4840 } while(0); /* end protected */
4842 if (varalloc!=NULL) free(varalloc); /* drop any storage used */
4843 if (allocacc!=NULL) free(allocacc); /* .. */
4844 #if DECSUBSET
4845 if (allocrhs!=NULL) free(allocrhs); /* .. */
4846 if (alloclhs!=NULL) free(alloclhs); /* .. */
4847 #endif
4848 return res;
4849 } /* decDivideOp */
4851 /* ------------------------------------------------------------------ */
4852 /* decMultiplyOp -- multiplication operation */
4853 /* */
4854 /* This routine performs the multiplication C=A x B. */
4855 /* */
4856 /* res is C, the result. C may be A and/or B (e.g., X=X*X) */
4857 /* lhs is A */
4858 /* rhs is B */
4859 /* set is the context */
4860 /* status is the usual accumulator */
4861 /* */
4862 /* C must have space for set->digits digits. */
4863 /* */
4864 /* ------------------------------------------------------------------ */
4865 /* 'Classic' multiplication is used rather than Karatsuba, as the */
4866 /* latter would give only a minor improvement for the short numbers */
4867 /* expected to be handled most (and uses much more memory). */
4868 /* */
4869 /* There are two major paths here: the general-purpose ('old code') */
4870 /* path which handles all DECDPUN values, and a fastpath version */
4871 /* which is used if 64-bit ints are available, DECDPUN<=4, and more */
4872 /* than two calls to decUnitAddSub would be made. */
4873 /* */
4874 /* The fastpath version lumps units together into 8-digit or 9-digit */
4875 /* chunks, and also uses a lazy carry strategy to minimise expensive */
4876 /* 64-bit divisions. The chunks are then broken apart again into */
4877 /* units for continuing processing. Despite this overhead, the */
4878 /* fastpath can speed up some 16-digit operations by 10x (and much */
4879 /* more for higher-precision calculations). */
4880 /* */
4881 /* A buffer always has to be used for the accumulator; in the */
4882 /* fastpath, buffers are also always needed for the chunked copies of */
4883 /* of the operand coefficients. */
4884 /* Static buffers are larger than needed just for multiply, to allow */
4885 /* for calls from other operations (notably exp). */
4886 /* ------------------------------------------------------------------ */
4887 #define FASTMUL (DECUSE64 && DECDPUN<5)
4888 static decNumber * decMultiplyOp(decNumber *res, const decNumber *lhs,
4889 const decNumber *rhs, decContext *set,
4890 uInt *status) {
4891 Int accunits; /* Units of accumulator in use */
4892 Int exponent; /* work */
4893 Int residue=0; /* rounding residue */
4894 uByte bits; /* result sign */
4895 Unit *acc; /* -> accumulator Unit array */
4896 Int needbytes; /* size calculator */
4897 void *allocacc=NULL; /* -> allocated accumulator, iff allocated */
4898 Unit accbuff[SD2U(DECBUFFER*4+1)]; /* buffer (+1 for DECBUFFER==0, */
4899 /* *4 for calls from other operations) */
4900 const Unit *mer, *mermsup; /* work */
4901 Int madlength; /* Units in multiplicand */
4902 Int shift; /* Units to shift multiplicand by */
4904 #if FASTMUL
4905 /* if DECDPUN is 1 or 3 work in base 10**9, otherwise */
4906 /* (DECDPUN is 2 or 4) then work in base 10**8 */
4907 #if DECDPUN & 1 /* odd */
4908 #define FASTBASE 1000000000 /* base */
4909 #define FASTDIGS 9 /* digits in base */
4910 #define FASTLAZY 18 /* carry resolution point [1->18] */
4911 #else
4912 #define FASTBASE 100000000
4913 #define FASTDIGS 8
4914 #define FASTLAZY 1844 /* carry resolution point [1->1844] */
4915 #endif
4916 /* three buffers are used, two for chunked copies of the operands */
4917 /* (base 10**8 or base 10**9) and one base 2**64 accumulator with */
4918 /* lazy carry evaluation */
4919 uInt zlhibuff[(DECBUFFER*2+1)/8+1]; /* buffer (+1 for DECBUFFER==0) */
4920 uInt *zlhi=zlhibuff; /* -> lhs array */
4921 uInt *alloclhi=NULL; /* -> allocated buffer, iff allocated */
4922 uInt zrhibuff[(DECBUFFER*2+1)/8+1]; /* buffer (+1 for DECBUFFER==0) */
4923 uInt *zrhi=zrhibuff; /* -> rhs array */
4924 uInt *allocrhi=NULL; /* -> allocated buffer, iff allocated */
4925 uLong zaccbuff[(DECBUFFER*2+1)/4+2]; /* buffer (+1 for DECBUFFER==0) */
4926 /* [allocacc is shared for both paths, as only one will run] */
4927 uLong *zacc=zaccbuff; /* -> accumulator array for exact result */
4928 #if DECDPUN==1
4929 Int zoff; /* accumulator offset */
4930 #endif
4931 uInt *lip, *rip; /* item pointers */
4932 uInt *lmsi, *rmsi; /* most significant items */
4933 Int ilhs, irhs, iacc; /* item counts in the arrays */
4934 Int lazy; /* lazy carry counter */
4935 uLong lcarry; /* uLong carry */
4936 uInt carry; /* carry (NB not uLong) */
4937 Int count; /* work */
4938 const Unit *cup; /* .. */
4939 Unit *up; /* .. */
4940 uLong *lp; /* .. */
4941 Int p; /* .. */
4942 #endif
4944 #if DECSUBSET
4945 decNumber *alloclhs=NULL; /* -> allocated buffer, iff allocated */
4946 decNumber *allocrhs=NULL; /* -> allocated buffer, iff allocated */
4947 #endif
4949 #if DECCHECK
4950 if (decCheckOperands(res, lhs, rhs, set)) return res;
4951 #endif
4953 /* precalculate result sign */
4954 bits=(uByte)((lhs->bits^rhs->bits)&DECNEG);
4956 /* handle infinities and NaNs */
4957 if (SPECIALARGS) { /* a special bit set */
4958 if (SPECIALARGS & (DECSNAN | DECNAN)) { /* one or two NaNs */
4959 decNaNs(res, lhs, rhs, set, status);
4960 return res;}
4961 /* one or two infinities; Infinity * 0 is invalid */
4962 if (((lhs->bits & DECINF)==0 && ISZERO(lhs))
4963 ||((rhs->bits & DECINF)==0 && ISZERO(rhs))) {
4964 *status|=DEC_Invalid_operation;
4965 return res;}
4966 decNumberZero(res);
4967 res->bits=bits|DECINF; /* infinity */
4968 return res;}
4970 /* For best speed, as in DMSRCN [the original Rexx numerics */
4971 /* module], use the shorter number as the multiplier (rhs) and */
4972 /* the longer as the multiplicand (lhs) to minimise the number of */
4973 /* adds (partial products) */
4974 if (lhs->digits<rhs->digits) { /* swap... */
4975 const decNumber *hold=lhs;
4976 lhs=rhs;
4977 rhs=hold;
4980 do { /* protect allocated storage */
4981 #if DECSUBSET
4982 if (!set->extended) {
4983 /* reduce operands and set lostDigits status, as needed */
4984 if (lhs->digits>set->digits) {
4985 alloclhs=decRoundOperand(lhs, set, status);
4986 if (alloclhs==NULL) break;
4987 lhs=alloclhs;
4989 if (rhs->digits>set->digits) {
4990 allocrhs=decRoundOperand(rhs, set, status);
4991 if (allocrhs==NULL) break;
4992 rhs=allocrhs;
4995 #endif
4996 /* [following code does not require input rounding] */
4998 #if FASTMUL /* fastpath can be used */
4999 /* use the fast path if there are enough digits in the shorter */
5000 /* operand to make the setup and takedown worthwhile */
5001 #define NEEDTWO (DECDPUN*2) /* within two decUnitAddSub calls */
5002 if (rhs->digits>NEEDTWO) { /* use fastpath... */
5003 /* calculate the number of elements in each array */
5004 ilhs=(lhs->digits+FASTDIGS-1)/FASTDIGS; /* [ceiling] */
5005 irhs=(rhs->digits+FASTDIGS-1)/FASTDIGS; /* .. */
5006 iacc=ilhs+irhs;
5008 /* allocate buffers if required, as usual */
5009 needbytes=ilhs*sizeof(uInt);
5010 if (needbytes>(Int)sizeof(zlhibuff)) {
5011 alloclhi=(uInt *)malloc(needbytes);
5012 zlhi=alloclhi;}
5013 needbytes=irhs*sizeof(uInt);
5014 if (needbytes>(Int)sizeof(zrhibuff)) {
5015 allocrhi=(uInt *)malloc(needbytes);
5016 zrhi=allocrhi;}
5018 /* Allocating the accumulator space needs a special case when */
5019 /* DECDPUN=1 because when converting the accumulator to Units */
5020 /* after the multiplication each 8-byte item becomes 9 1-byte */
5021 /* units. Therefore iacc extra bytes are needed at the front */
5022 /* (rounded up to a multiple of 8 bytes), and the uLong */
5023 /* accumulator starts offset the appropriate number of units */
5024 /* to the right to avoid overwrite during the unchunking. */
5025 needbytes=iacc*sizeof(uLong);
5026 #if DECDPUN==1
5027 zoff=(iacc+7)/8; /* items to offset by */
5028 needbytes+=zoff*8;
5029 #endif
5030 if (needbytes>(Int)sizeof(zaccbuff)) {
5031 allocacc=(uLong *)malloc(needbytes);
5032 zacc=(uLong *)allocacc;}
5033 if (zlhi==NULL||zrhi==NULL||zacc==NULL) {
5034 *status|=DEC_Insufficient_storage;
5035 break;}
5037 acc=(Unit *)zacc; /* -> target Unit array */
5038 #if DECDPUN==1
5039 zacc+=zoff; /* start uLong accumulator to right */
5040 #endif
5042 /* assemble the chunked copies of the left and right sides */
5043 for (count=lhs->digits, cup=lhs->lsu, lip=zlhi; count>0; lip++)
5044 for (p=0, *lip=0; p<FASTDIGS && count>0;
5045 p+=DECDPUN, cup++, count-=DECDPUN)
5046 *lip+=*cup*powers[p];
5047 lmsi=lip-1; /* save -> msi */
5048 for (count=rhs->digits, cup=rhs->lsu, rip=zrhi; count>0; rip++)
5049 for (p=0, *rip=0; p<FASTDIGS && count>0;
5050 p+=DECDPUN, cup++, count-=DECDPUN)
5051 *rip+=*cup*powers[p];
5052 rmsi=rip-1; /* save -> msi */
5054 /* zero the accumulator */
5055 for (lp=zacc; lp<zacc+iacc; lp++) *lp=0;
5057 /* Start the multiplication */
5058 /* Resolving carries can dominate the cost of accumulating the */
5059 /* partial products, so this is only done when necessary. */
5060 /* Each uLong item in the accumulator can hold values up to */
5061 /* 2**64-1, and each partial product can be as large as */
5062 /* (10**FASTDIGS-1)**2. When FASTDIGS=9, this can be added to */
5063 /* itself 18.4 times in a uLong without overflowing, so during */
5064 /* the main calculation resolution is carried out every 18th */
5065 /* add -- every 162 digits. Similarly, when FASTDIGS=8, the */
5066 /* partial products can be added to themselves 1844.6 times in */
5067 /* a uLong without overflowing, so intermediate carry */
5068 /* resolution occurs only every 14752 digits. Hence for common */
5069 /* short numbers usually only the one final carry resolution */
5070 /* occurs. */
5071 /* (The count is set via FASTLAZY to simplify experiments to */
5072 /* measure the value of this approach: a 35% improvement on a */
5073 /* [34x34] multiply.) */
5074 lazy=FASTLAZY; /* carry delay count */
5075 for (rip=zrhi; rip<=rmsi; rip++) { /* over each item in rhs */
5076 lp=zacc+(rip-zrhi); /* where to add the lhs */
5077 for (lip=zlhi; lip<=lmsi; lip++, lp++) { /* over each item in lhs */
5078 *lp+=(uLong)(*lip)*(*rip); /* [this should in-line] */
5079 } /* lip loop */
5080 lazy--;
5081 if (lazy>0 && rip!=rmsi) continue;
5082 lazy=FASTLAZY; /* reset delay count */
5083 /* spin up the accumulator resolving overflows */
5084 for (lp=zacc; lp<zacc+iacc; lp++) {
5085 if (*lp<FASTBASE) continue; /* it fits */
5086 lcarry=*lp/FASTBASE; /* top part [slow divide] */
5087 /* lcarry can exceed 2**32-1, so check again; this check */
5088 /* and occasional extra divide (slow) is well worth it, as */
5089 /* it allows FASTLAZY to be increased to 18 rather than 4 */
5090 /* in the FASTDIGS=9 case */
5091 if (lcarry<FASTBASE) carry=(uInt)lcarry; /* [usual] */
5092 else { /* two-place carry [fairly rare] */
5093 uInt carry2=(uInt)(lcarry/FASTBASE); /* top top part */
5094 *(lp+2)+=carry2; /* add to item+2 */
5095 *lp-=((uLong)FASTBASE*FASTBASE*carry2); /* [slow] */
5096 carry=(uInt)(lcarry-((uLong)FASTBASE*carry2)); /* [inline] */
5098 *(lp+1)+=carry; /* add to item above [inline] */
5099 *lp-=((uLong)FASTBASE*carry); /* [inline] */
5100 } /* carry resolution */
5101 } /* rip loop */
5103 /* The multiplication is complete; time to convert back into */
5104 /* units. This can be done in-place in the accumulator and in */
5105 /* 32-bit operations, because carries were resolved after the */
5106 /* final add. This needs N-1 divides and multiplies for */
5107 /* each item in the accumulator (which will become up to N */
5108 /* units, where 2<=N<=9). */
5109 for (lp=zacc, up=acc; lp<zacc+iacc; lp++) {
5110 uInt item=(uInt)*lp; /* decapitate to uInt */
5111 for (p=0; p<FASTDIGS-DECDPUN; p+=DECDPUN, up++) {
5112 uInt part=item/(DECDPUNMAX+1);
5113 *up=(Unit)(item-(part*(DECDPUNMAX+1)));
5114 item=part;
5115 } /* p */
5116 *up=(Unit)item; up++; /* [final needs no division] */
5117 } /* lp */
5118 accunits=up-acc; /* count of units */
5120 else { /* here to use units directly, without chunking ['old code'] */
5121 #endif
5123 /* if accumulator will be too long for local storage, then allocate */
5124 acc=accbuff; /* -> assume buffer for accumulator */
5125 needbytes=(D2U(lhs->digits)+D2U(rhs->digits))*sizeof(Unit);
5126 if (needbytes>(Int)sizeof(accbuff)) {
5127 allocacc=(Unit *)malloc(needbytes);
5128 if (allocacc==NULL) {*status|=DEC_Insufficient_storage; break;}
5129 acc=(Unit *)allocacc; /* use the allocated space */
5132 /* Now the main long multiplication loop */
5133 /* Unlike the equivalent in the IBM Java implementation, there */
5134 /* is no advantage in calculating from msu to lsu. So, do it */
5135 /* by the book, as it were. */
5136 /* Each iteration calculates ACC=ACC+MULTAND*MULT */
5137 accunits=1; /* accumulator starts at '0' */
5138 *acc=0; /* .. (lsu=0) */
5139 shift=0; /* no multiplicand shift at first */
5140 madlength=D2U(lhs->digits); /* this won't change */
5141 mermsup=rhs->lsu+D2U(rhs->digits); /* -> msu+1 of multiplier */
5143 for (mer=rhs->lsu; mer<mermsup; mer++) {
5144 /* Here, *mer is the next Unit in the multiplier to use */
5145 /* If non-zero [optimization] add it... */
5146 if (*mer!=0) accunits=decUnitAddSub(&acc[shift], accunits-shift,
5147 lhs->lsu, madlength, 0,
5148 &acc[shift], *mer)
5149 + shift;
5150 else { /* extend acc with a 0; it will be used shortly */
5151 *(acc+accunits)=0; /* [this avoids length of <=0 later] */
5152 accunits++;
5154 /* multiply multiplicand by 10**DECDPUN for next Unit to left */
5155 shift++; /* add this for 'logical length' */
5156 } /* n */
5157 #if FASTMUL
5158 } /* unchunked units */
5159 #endif
5160 /* common end-path */
5161 #if DECTRACE
5162 decDumpAr('*', acc, accunits); /* Show exact result */
5163 #endif
5165 /* acc now contains the exact result of the multiplication, */
5166 /* possibly with a leading zero unit; build the decNumber from */
5167 /* it, noting if any residue */
5168 res->bits=bits; /* set sign */
5169 res->digits=decGetDigits(acc, accunits); /* count digits exactly */
5171 /* There can be a 31-bit wrap in calculating the exponent. */
5172 /* This can only happen if both input exponents are negative and */
5173 /* both their magnitudes are large. If there was a wrap, set a */
5174 /* safe very negative exponent, from which decFinalize() will */
5175 /* raise a hard underflow shortly. */
5176 exponent=lhs->exponent+rhs->exponent; /* calculate exponent */
5177 if (lhs->exponent<0 && rhs->exponent<0 && exponent>0)
5178 exponent=-2*DECNUMMAXE; /* force underflow */
5179 res->exponent=exponent; /* OK to overwrite now */
5182 /* Set the coefficient. If any rounding, residue records */
5183 decSetCoeff(res, set, acc, res->digits, &residue, status);
5184 decFinish(res, set, &residue, status); /* final cleanup */
5185 } while(0); /* end protected */
5187 if (allocacc!=NULL) free(allocacc); /* drop any storage used */
5188 #if DECSUBSET
5189 if (allocrhs!=NULL) free(allocrhs); /* .. */
5190 if (alloclhs!=NULL) free(alloclhs); /* .. */
5191 #endif
5192 #if FASTMUL
5193 if (allocrhi!=NULL) free(allocrhi); /* .. */
5194 if (alloclhi!=NULL) free(alloclhi); /* .. */
5195 #endif
5196 return res;
5197 } /* decMultiplyOp */
5199 /* ------------------------------------------------------------------ */
5200 /* decExpOp -- effect exponentiation */
5201 /* */
5202 /* This computes C = exp(A) */
5203 /* */
5204 /* res is C, the result. C may be A */
5205 /* rhs is A */
5206 /* set is the context; note that rounding mode has no effect */
5207 /* */
5208 /* C must have space for set->digits digits. status is updated but */
5209 /* not set. */
5210 /* */
5211 /* Restrictions: */
5212 /* */
5213 /* digits, emax, and -emin in the context must be less than */
5214 /* 2*DEC_MAX_MATH (1999998), and the rhs must be within these */
5215 /* bounds or a zero. This is an internal routine, so these */
5216 /* restrictions are contractual and not enforced. */
5217 /* */
5218 /* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will */
5219 /* almost always be correctly rounded, but may be up to 1 ulp in */
5220 /* error in rare cases. */
5221 /* */
5222 /* Finite results will always be full precision and Inexact, except */
5223 /* when A is a zero or -Infinity (giving 1 or 0 respectively). */
5224 /* ------------------------------------------------------------------ */
5225 /* This approach used here is similar to the algorithm described in */
5226 /* */
5227 /* Variable Precision Exponential Function, T. E. Hull and */
5228 /* A. Abrham, ACM Transactions on Mathematical Software, Vol 12 #2, */
5229 /* pp79-91, ACM, June 1986. */
5230 /* */
5231 /* with the main difference being that the iterations in the series */
5232 /* evaluation are terminated dynamically (which does not require the */
5233 /* extra variable-precision variables which are expensive in this */
5234 /* context). */
5235 /* */
5236 /* The error analysis in Hull & Abrham's paper applies except for the */
5237 /* round-off error accumulation during the series evaluation. This */
5238 /* code does not precalculate the number of iterations and so cannot */
5239 /* use Horner's scheme. Instead, the accumulation is done at double- */
5240 /* precision, which ensures that the additions of the terms are exact */
5241 /* and do not accumulate round-off (and any round-off errors in the */
5242 /* terms themselves move 'to the right' faster than they can */
5243 /* accumulate). This code also extends the calculation by allowing, */
5244 /* in the spirit of other decNumber operators, the input to be more */
5245 /* precise than the result (the precision used is based on the more */
5246 /* precise of the input or requested result). */
5247 /* */
5248 /* Implementation notes: */
5249 /* */
5250 /* 1. This is separated out as decExpOp so it can be called from */
5251 /* other Mathematical functions (notably Ln) with a wider range */
5252 /* than normal. In particular, it can handle the slightly wider */
5253 /* (double) range needed by Ln (which has to be able to calculate */
5254 /* exp(-x) where x can be the tiniest number (Ntiny). */
5255 /* */
5256 /* 2. Normalizing x to be <=0.1 (instead of <=1) reduces loop */
5257 /* iterations by approximately a third with additional (although */
5258 /* diminishing) returns as the range is reduced to even smaller */
5259 /* fractions. However, h (the power of 10 used to correct the */
5260 /* result at the end, see below) must be kept <=8 as otherwise */
5261 /* the final result cannot be computed. Hence the leverage is a */
5262 /* sliding value (8-h), where potentially the range is reduced */
5263 /* more for smaller values. */
5264 /* */
5265 /* The leverage that can be applied in this way is severely */
5266 /* limited by the cost of the raise-to-the power at the end, */
5267 /* which dominates when the number of iterations is small (less */
5268 /* than ten) or when rhs is short. As an example, the adjustment */
5269 /* x**10,000,000 needs 31 multiplications, all but one full-width. */
5270 /* */
5271 /* 3. The restrictions (especially precision) could be raised with */
5272 /* care, but the full decNumber range seems very hard within the */
5273 /* 32-bit limits. */
5274 /* */
5275 /* 4. The working precisions for the static buffers are twice the */
5276 /* obvious size to allow for calls from decNumberPower. */
5277 /* ------------------------------------------------------------------ */
5278 static decNumber *decExpOp(decNumber *res, const decNumber *rhs,
5279 decContext *set, uInt *status) {
5280 uInt ignore=0; /* working status */
5281 Int h; /* adjusted exponent for 0.xxxx */
5282 Int p; /* working precision */
5283 Int residue; /* rounding residue */
5284 uInt needbytes; /* for space calculations */
5285 const decNumber *x=rhs; /* (may point to safe copy later) */
5286 decContext aset, tset, dset; /* working contexts */
5287 Int comp; /* work */
5289 /* the argument is often copied to normalize it, so (unusually) it */
5290 /* is treated like other buffers, using DECBUFFER, +1 in case */
5291 /* DECBUFFER is 0 */
5292 decNumber bufr[D2N(DECBUFFER*2+1)];
5293 decNumber *allocrhs=NULL; /* non-NULL if rhs buffer allocated */
5295 /* the working precision will be no more than set->digits+8+1 */
5296 /* so for on-stack buffers DECBUFFER+9 is used, +1 in case DECBUFFER */
5297 /* is 0 (and twice that for the accumulator) */
5299 /* buffer for t, term (working precision plus) */
5300 decNumber buft[D2N(DECBUFFER*2+9+1)];
5301 decNumber *allocbuft=NULL; /* -> allocated buft, iff allocated */
5302 decNumber *t=buft; /* term */
5303 /* buffer for a, accumulator (working precision * 2), at least 9 */
5304 decNumber bufa[D2N(DECBUFFER*4+18+1)];
5305 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
5306 decNumber *a=bufa; /* accumulator */
5307 /* decNumber for the divisor term; this needs at most 9 digits */
5308 /* and so can be fixed size [16 so can use standard context] */
5309 decNumber bufd[D2N(16)];
5310 decNumber *d=bufd; /* divisor */
5311 decNumber numone; /* constant 1 */
5313 #if DECCHECK
5314 Int iterations=0; /* for later sanity check */
5315 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
5316 #endif
5318 do { /* protect allocated storage */
5319 if (SPECIALARG) { /* handle infinities and NaNs */
5320 if (decNumberIsInfinite(rhs)) { /* an infinity */
5321 if (decNumberIsNegative(rhs)) /* -Infinity -> +0 */
5322 decNumberZero(res);
5323 else decNumberCopy(res, rhs); /* +Infinity -> self */
5325 else decNaNs(res, rhs, NULL, set, status); /* a NaN */
5326 break;}
5328 if (ISZERO(rhs)) { /* zeros -> exact 1 */
5329 decNumberZero(res); /* make clean 1 */
5330 *res->lsu=1; /* .. */
5331 break;} /* [no status to set] */
5333 /* e**x when 0 < x < 0.66 is < 1+3x/2, hence can fast-path */
5334 /* positive and negative tiny cases which will result in inexact */
5335 /* 1. This also allows the later add-accumulate to always be */
5336 /* exact (because its length will never be more than twice the */
5337 /* working precision). */
5338 /* The comparator (tiny) needs just one digit, so use the */
5339 /* decNumber d for it (reused as the divisor, etc., below); its */
5340 /* exponent is such that if x is positive it will have */
5341 /* set->digits-1 zeros between the decimal point and the digit, */
5342 /* which is 4, and if x is negative one more zero there as the */
5343 /* more precise result will be of the form 0.9999999 rather than */
5344 /* 1.0000001. Hence, tiny will be 0.0000004 if digits=7 and x>0 */
5345 /* or 0.00000004 if digits=7 and x<0. If RHS not larger than */
5346 /* this then the result will be 1.000000 */
5347 decNumberZero(d); /* clean */
5348 *d->lsu=4; /* set 4 .. */
5349 d->exponent=-set->digits; /* * 10**(-d) */
5350 if (decNumberIsNegative(rhs)) d->exponent--; /* negative case */
5351 comp=decCompare(d, rhs, 1); /* signless compare */
5352 if (comp==BADINT) {
5353 *status|=DEC_Insufficient_storage;
5354 break;}
5355 if (comp>=0) { /* rhs < d */
5356 Int shift=set->digits-1;
5357 decNumberZero(res); /* set 1 */
5358 *res->lsu=1; /* .. */
5359 res->digits=decShiftToMost(res->lsu, 1, shift);
5360 res->exponent=-shift; /* make 1.0000... */
5361 *status|=DEC_Inexact | DEC_Rounded; /* .. inexactly */
5362 break;} /* tiny */
5364 /* set up the context to be used for calculating a, as this is */
5365 /* used on both paths below */
5366 decContextDefault(&aset, DEC_INIT_DECIMAL64);
5367 /* accumulator bounds are as requested (could underflow) */
5368 aset.emax=set->emax; /* usual bounds */
5369 aset.emin=set->emin; /* .. */
5370 aset.clamp=0; /* and no concrete format */
5372 /* calculate the adjusted (Hull & Abrham) exponent (where the */
5373 /* decimal point is just to the left of the coefficient msd) */
5374 h=rhs->exponent+rhs->digits;
5375 /* if h>8 then 10**h cannot be calculated safely; however, when */
5376 /* h=8 then exp(|rhs|) will be at least exp(1E+7) which is at */
5377 /* least 6.59E+4342944, so (due to the restriction on Emax/Emin) */
5378 /* overflow (or underflow to 0) is guaranteed -- so this case can */
5379 /* be handled by simply forcing the appropriate excess */
5380 if (h>8) { /* overflow/underflow */
5381 /* set up here so Power call below will over or underflow to */
5382 /* zero; set accumulator to either 2 or 0.02 */
5383 /* [stack buffer for a is always big enough for this] */
5384 decNumberZero(a);
5385 *a->lsu=2; /* not 1 but < exp(1) */
5386 if (decNumberIsNegative(rhs)) a->exponent=-2; /* make 0.02 */
5387 h=8; /* clamp so 10**h computable */
5388 p=9; /* set a working precision */
5390 else { /* h<=8 */
5391 Int maxlever=(rhs->digits>8?1:0);
5392 /* [could/should increase this for precisions >40 or so, too] */
5394 /* if h is 8, cannot normalize to a lower upper limit because */
5395 /* the final result will not be computable (see notes above), */
5396 /* but leverage can be applied whenever h is less than 8. */
5397 /* Apply as much as possible, up to a MAXLEVER digits, which */
5398 /* sets the tradeoff against the cost of the later a**(10**h). */
5399 /* As h is increased, the working precision below also */
5400 /* increases to compensate for the "constant digits at the */
5401 /* front" effect. */
5402 Int lever=MINI(8-h, maxlever); /* leverage attainable */
5403 Int use=-rhs->digits-lever; /* exponent to use for RHS */
5404 h+=lever; /* apply leverage selected */
5405 if (h<0) { /* clamp */
5406 use+=h; /* [may end up subnormal] */
5407 h=0;
5409 /* Take a copy of RHS if it needs normalization (true whenever x>=1) */
5410 if (rhs->exponent!=use) {
5411 decNumber *newrhs=bufr; /* assume will fit on stack */
5412 needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
5413 if (needbytes>sizeof(bufr)) { /* need malloc space */
5414 allocrhs=(decNumber *)malloc(needbytes);
5415 if (allocrhs==NULL) { /* hopeless -- abandon */
5416 *status|=DEC_Insufficient_storage;
5417 break;}
5418 newrhs=allocrhs; /* use the allocated space */
5420 decNumberCopy(newrhs, rhs); /* copy to safe space */
5421 newrhs->exponent=use; /* normalize; now <1 */
5422 x=newrhs; /* ready for use */
5423 /* decNumberShow(x); */
5426 /* Now use the usual power series to evaluate exp(x). The */
5427 /* series starts as 1 + x + x^2/2 ... so prime ready for the */
5428 /* third term by setting the term variable t=x, the accumulator */
5429 /* a=1, and the divisor d=2. */
5431 /* First determine the working precision. From Hull & Abrham */
5432 /* this is set->digits+h+2. However, if x is 'over-precise' we */
5433 /* need to allow for all its digits to potentially participate */
5434 /* (consider an x where all the excess digits are 9s) so in */
5435 /* this case use x->digits+h+2 */
5436 p=MAXI(x->digits, set->digits)+h+2; /* [h<=8] */
5438 /* a and t are variable precision, and depend on p, so space */
5439 /* must be allocated for them if necessary */
5441 /* the accumulator needs to be able to hold 2p digits so that */
5442 /* the additions on the second and subsequent iterations are */
5443 /* sufficiently exact. */
5444 needbytes=sizeof(decNumber)+(D2U(p*2)-1)*sizeof(Unit);
5445 if (needbytes>sizeof(bufa)) { /* need malloc space */
5446 allocbufa=(decNumber *)malloc(needbytes);
5447 if (allocbufa==NULL) { /* hopeless -- abandon */
5448 *status|=DEC_Insufficient_storage;
5449 break;}
5450 a=allocbufa; /* use the allocated space */
5452 /* the term needs to be able to hold p digits (which is */
5453 /* guaranteed to be larger than x->digits, so the initial copy */
5454 /* is safe); it may also be used for the raise-to-power */
5455 /* calculation below, which needs an extra two digits */
5456 needbytes=sizeof(decNumber)+(D2U(p+2)-1)*sizeof(Unit);
5457 if (needbytes>sizeof(buft)) { /* need malloc space */
5458 allocbuft=(decNumber *)malloc(needbytes);
5459 if (allocbuft==NULL) { /* hopeless -- abandon */
5460 *status|=DEC_Insufficient_storage;
5461 break;}
5462 t=allocbuft; /* use the allocated space */
5465 decNumberCopy(t, x); /* term=x */
5466 decNumberZero(a); *a->lsu=1; /* accumulator=1 */
5467 decNumberZero(d); *d->lsu=2; /* divisor=2 */
5468 decNumberZero(&numone); *numone.lsu=1; /* constant 1 for increment */
5470 /* set up the contexts for calculating a, t, and d */
5471 decContextDefault(&tset, DEC_INIT_DECIMAL64);
5472 dset=tset;
5473 /* accumulator bounds are set above, set precision now */
5474 aset.digits=p*2; /* double */
5475 /* term bounds avoid any underflow or overflow */
5476 tset.digits=p;
5477 tset.emin=DEC_MIN_EMIN; /* [emax is plenty] */
5478 /* [dset.digits=16, etc., are sufficient] */
5480 /* finally ready to roll */
5481 for (;;) {
5482 #if DECCHECK
5483 iterations++;
5484 #endif
5485 /* only the status from the accumulation is interesting */
5486 /* [but it should remain unchanged after first add] */
5487 decAddOp(a, a, t, &aset, 0, status); /* a=a+t */
5488 decMultiplyOp(t, t, x, &tset, &ignore); /* t=t*x */
5489 decDivideOp(t, t, d, &tset, DIVIDE, &ignore); /* t=t/d */
5490 /* the iteration ends when the term cannot affect the result, */
5491 /* if rounded to p digits, which is when its value is smaller */
5492 /* than the accumulator by p+1 digits. There must also be */
5493 /* full precision in a. */
5494 if (((a->digits+a->exponent)>=(t->digits+t->exponent+p+1))
5495 && (a->digits>=p)) break;
5496 decAddOp(d, d, &numone, &dset, 0, &ignore); /* d=d+1 */
5497 } /* iterate */
5499 #if DECCHECK
5500 /* just a sanity check; comment out test to show always */
5501 if (iterations>p+3)
5502 printf("Exp iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
5503 iterations, *status, p, x->digits);
5504 #endif
5505 } /* h<=8 */
5507 /* apply postconditioning: a=a**(10**h) -- this is calculated */
5508 /* at a slightly higher precision than Hull & Abrham suggest */
5509 if (h>0) {
5510 Int seenbit=0; /* set once a 1-bit is seen */
5511 Int i; /* counter */
5512 Int n=powers[h]; /* always positive */
5513 aset.digits=p+2; /* sufficient precision */
5514 /* avoid the overhead and many extra digits of decNumberPower */
5515 /* as all that is needed is the short 'multipliers' loop; here */
5516 /* accumulate the answer into t */
5517 decNumberZero(t); *t->lsu=1; /* acc=1 */
5518 for (i=1;;i++){ /* for each bit [top bit ignored] */
5519 /* abandon if have had overflow or terminal underflow */
5520 if (*status & (DEC_Overflow|DEC_Underflow)) { /* interesting? */
5521 if (*status&DEC_Overflow || ISZERO(t)) break;}
5522 n=n<<1; /* move next bit to testable position */
5523 if (n<0) { /* top bit is set */
5524 seenbit=1; /* OK, have a significant bit */
5525 decMultiplyOp(t, t, a, &aset, status); /* acc=acc*x */
5527 if (i==31) break; /* that was the last bit */
5528 if (!seenbit) continue; /* no need to square 1 */
5529 decMultiplyOp(t, t, t, &aset, status); /* acc=acc*acc [square] */
5530 } /*i*/ /* 32 bits */
5531 /* decNumberShow(t); */
5532 a=t; /* and carry on using t instead of a */
5535 /* Copy and round the result to res */
5536 residue=1; /* indicate dirt to right .. */
5537 if (ISZERO(a)) residue=0; /* .. unless underflowed to 0 */
5538 aset.digits=set->digits; /* [use default rounding] */
5539 decCopyFit(res, a, &aset, &residue, status); /* copy & shorten */
5540 decFinish(res, set, &residue, status); /* cleanup/set flags */
5541 } while(0); /* end protected */
5543 if (allocrhs !=NULL) free(allocrhs); /* drop any storage used */
5544 if (allocbufa!=NULL) free(allocbufa); /* .. */
5545 if (allocbuft!=NULL) free(allocbuft); /* .. */
5546 /* [status is handled by caller] */
5547 return res;
5548 } /* decExpOp */
5550 /* ------------------------------------------------------------------ */
5551 /* Initial-estimate natural logarithm table */
5552 /* */
5553 /* LNnn -- 90-entry 16-bit table for values from .10 through .99. */
5554 /* The result is a 4-digit encode of the coefficient (c=the */
5555 /* top 14 bits encoding 0-9999) and a 2-digit encode of the */
5556 /* exponent (e=the bottom 2 bits encoding 0-3) */
5557 /* */
5558 /* The resulting value is given by: */
5559 /* */
5560 /* v = -c * 10**(-e-3) */
5561 /* */
5562 /* where e and c are extracted from entry k = LNnn[x-10] */
5563 /* where x is truncated (NB) into the range 10 through 99, */
5564 /* and then c = k>>2 and e = k&3. */
5565 /* ------------------------------------------------------------------ */
5566 static const uShort LNnn[90] = {
5567 9016, 8652, 8316, 8008, 7724, 7456, 7208,
5568 6972, 6748, 6540, 6340, 6148, 5968, 5792, 5628, 5464, 5312,
5569 5164, 5020, 4884, 4748, 4620, 4496, 4376, 4256, 4144, 4032,
5570 39233, 38181, 37157, 36157, 35181, 34229, 33297, 32389, 31501, 30629,
5571 29777, 28945, 28129, 27329, 26545, 25777, 25021, 24281, 23553, 22837,
5572 22137, 21445, 20769, 20101, 19445, 18801, 18165, 17541, 16925, 16321,
5573 15721, 15133, 14553, 13985, 13421, 12865, 12317, 11777, 11241, 10717,
5574 10197, 9685, 9177, 8677, 8185, 7697, 7213, 6737, 6269, 5801,
5575 5341, 4889, 4437, 39930, 35534, 31186, 26886, 22630, 18418, 14254,
5576 10130, 6046, 20055};
5578 /* ------------------------------------------------------------------ */
5579 /* decLnOp -- effect natural logarithm */
5580 /* */
5581 /* This computes C = ln(A) */
5582 /* */
5583 /* res is C, the result. C may be A */
5584 /* rhs is A */
5585 /* set is the context; note that rounding mode has no effect */
5586 /* */
5587 /* C must have space for set->digits digits. */
5588 /* */
5589 /* Notable cases: */
5590 /* A<0 -> Invalid */
5591 /* A=0 -> -Infinity (Exact) */
5592 /* A=+Infinity -> +Infinity (Exact) */
5593 /* A=1 exactly -> 0 (Exact) */
5594 /* */
5595 /* Restrictions (as for Exp): */
5596 /* */
5597 /* digits, emax, and -emin in the context must be less than */
5598 /* DEC_MAX_MATH+11 (1000010), and the rhs must be within these */
5599 /* bounds or a zero. This is an internal routine, so these */
5600 /* restrictions are contractual and not enforced. */
5601 /* */
5602 /* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will */
5603 /* almost always be correctly rounded, but may be up to 1 ulp in */
5604 /* error in rare cases. */
5605 /* ------------------------------------------------------------------ */
5606 /* The result is calculated using Newton's method, with each */
5607 /* iteration calculating a' = a + x * exp(-a) - 1. See, for example, */
5608 /* Epperson 1989. */
5609 /* */
5610 /* The iteration ends when the adjustment x*exp(-a)-1 is tiny enough. */
5611 /* This has to be calculated at the sum of the precision of x and the */
5612 /* working precision. */
5613 /* */
5614 /* Implementation notes: */
5615 /* */
5616 /* 1. This is separated out as decLnOp so it can be called from */
5617 /* other Mathematical functions (e.g., Log 10) with a wider range */
5618 /* than normal. In particular, it can handle the slightly wider */
5619 /* (+9+2) range needed by a power function. */
5620 /* */
5621 /* 2. The speed of this function is about 10x slower than exp, as */
5622 /* it typically needs 4-6 iterations for short numbers, and the */
5623 /* extra precision needed adds a squaring effect, twice. */
5624 /* */
5625 /* 3. Fastpaths are included for ln(10) and ln(2), up to length 40, */
5626 /* as these are common requests. ln(10) is used by log10(x). */
5627 /* */
5628 /* 4. An iteration might be saved by widening the LNnn table, and */
5629 /* would certainly save at least one if it were made ten times */
5630 /* bigger, too (for truncated fractions 0.100 through 0.999). */
5631 /* However, for most practical evaluations, at least four or five */
5632 /* iterations will be neede -- so this would only speed up by */
5633 /* 20-25% and that probably does not justify increasing the table */
5634 /* size. */
5635 /* */
5636 /* 5. The static buffers are larger than might be expected to allow */
5637 /* for calls from decNumberPower. */
5638 /* ------------------------------------------------------------------ */
5639 static decNumber *decLnOp(decNumber *res, const decNumber *rhs,
5640 decContext *set, uInt *status) {
5641 uInt ignore=0; /* working status accumulator */
5642 uInt needbytes; /* for space calculations */
5643 Int residue; /* rounding residue */
5644 Int r; /* rhs=f*10**r [see below] */
5645 Int p; /* working precision */
5646 Int pp; /* precision for iteration */
5647 Int t; /* work */
5649 /* buffers for a (accumulator, typically precision+2) and b */
5650 /* (adjustment calculator, same size) */
5651 decNumber bufa[D2N(DECBUFFER+12)];
5652 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
5653 decNumber *a=bufa; /* accumulator/work */
5654 decNumber bufb[D2N(DECBUFFER*2+2)];
5655 decNumber *allocbufb=NULL; /* -> allocated bufa, iff allocated */
5656 decNumber *b=bufb; /* adjustment/work */
5658 decNumber numone; /* constant 1 */
5659 decNumber cmp; /* work */
5660 decContext aset, bset; /* working contexts */
5662 #if DECCHECK
5663 Int iterations=0; /* for later sanity check */
5664 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
5665 #endif
5667 do { /* protect allocated storage */
5668 if (SPECIALARG) { /* handle infinities and NaNs */
5669 if (decNumberIsInfinite(rhs)) { /* an infinity */
5670 if (decNumberIsNegative(rhs)) /* -Infinity -> error */
5671 *status|=DEC_Invalid_operation;
5672 else decNumberCopy(res, rhs); /* +Infinity -> self */
5674 else decNaNs(res, rhs, NULL, set, status); /* a NaN */
5675 break;}
5677 if (ISZERO(rhs)) { /* +/- zeros -> -Infinity */
5678 decNumberZero(res); /* make clean */
5679 res->bits=DECINF|DECNEG; /* set - infinity */
5680 break;} /* [no status to set] */
5682 /* Non-zero negatives are bad... */
5683 if (decNumberIsNegative(rhs)) { /* -x -> error */
5684 *status|=DEC_Invalid_operation;
5685 break;}
5687 /* Here, rhs is positive, finite, and in range */
5689 /* lookaside fastpath code for ln(2) and ln(10) at common lengths */
5690 if (rhs->exponent==0 && set->digits<=40) {
5691 #if DECDPUN==1
5692 if (rhs->lsu[0]==0 && rhs->lsu[1]==1 && rhs->digits==2) { /* ln(10) */
5693 #else
5694 if (rhs->lsu[0]==10 && rhs->digits==2) { /* ln(10) */
5695 #endif
5696 aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
5697 #define LN10 "2.302585092994045684017991454684364207601"
5698 decNumberFromString(res, LN10, &aset);
5699 *status|=(DEC_Inexact | DEC_Rounded); /* is inexact */
5700 break;}
5701 if (rhs->lsu[0]==2 && rhs->digits==1) { /* ln(2) */
5702 aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
5703 #define LN2 "0.6931471805599453094172321214581765680755"
5704 decNumberFromString(res, LN2, &aset);
5705 *status|=(DEC_Inexact | DEC_Rounded);
5706 break;}
5707 } /* integer and short */
5709 /* Determine the working precision. This is normally the */
5710 /* requested precision + 2, with a minimum of 9. However, if */
5711 /* the rhs is 'over-precise' then allow for all its digits to */
5712 /* potentially participate (consider an rhs where all the excess */
5713 /* digits are 9s) so in this case use rhs->digits+2. */
5714 p=MAXI(rhs->digits, MAXI(set->digits, 7))+2;
5716 /* Allocate space for the accumulator and the high-precision */
5717 /* adjustment calculator, if necessary. The accumulator must */
5718 /* be able to hold p digits, and the adjustment up to */
5719 /* rhs->digits+p digits. They are also made big enough for 16 */
5720 /* digits so that they can be used for calculating the initial */
5721 /* estimate. */
5722 needbytes=sizeof(decNumber)+(D2U(MAXI(p,16))-1)*sizeof(Unit);
5723 if (needbytes>sizeof(bufa)) { /* need malloc space */
5724 allocbufa=(decNumber *)malloc(needbytes);
5725 if (allocbufa==NULL) { /* hopeless -- abandon */
5726 *status|=DEC_Insufficient_storage;
5727 break;}
5728 a=allocbufa; /* use the allocated space */
5730 pp=p+rhs->digits;
5731 needbytes=sizeof(decNumber)+(D2U(MAXI(pp,16))-1)*sizeof(Unit);
5732 if (needbytes>sizeof(bufb)) { /* need malloc space */
5733 allocbufb=(decNumber *)malloc(needbytes);
5734 if (allocbufb==NULL) { /* hopeless -- abandon */
5735 *status|=DEC_Insufficient_storage;
5736 break;}
5737 b=allocbufb; /* use the allocated space */
5740 /* Prepare an initial estimate in acc. Calculate this by */
5741 /* considering the coefficient of x to be a normalized fraction, */
5742 /* f, with the decimal point at far left and multiplied by */
5743 /* 10**r. Then, rhs=f*10**r and 0.1<=f<1, and */
5744 /* ln(x) = ln(f) + ln(10)*r */
5745 /* Get the initial estimate for ln(f) from a small lookup */
5746 /* table (see above) indexed by the first two digits of f, */
5747 /* truncated. */
5749 decContextDefault(&aset, DEC_INIT_DECIMAL64); /* 16-digit extended */
5750 r=rhs->exponent+rhs->digits; /* 'normalised' exponent */
5751 decNumberFromInt32(a, r); /* a=r */
5752 decNumberFromInt32(b, 2302585); /* b=ln(10) (2.302585) */
5753 b->exponent=-6; /* .. */
5754 decMultiplyOp(a, a, b, &aset, &ignore); /* a=a*b */
5755 /* now get top two digits of rhs into b by simple truncate and */
5756 /* force to integer */
5757 residue=0; /* (no residue) */
5758 aset.digits=2; aset.round=DEC_ROUND_DOWN;
5759 decCopyFit(b, rhs, &aset, &residue, &ignore); /* copy & shorten */
5760 b->exponent=0; /* make integer */
5761 t=decGetInt(b); /* [cannot fail] */
5762 if (t<10) t=X10(t); /* adjust single-digit b */
5763 t=LNnn[t-10]; /* look up ln(b) */
5764 decNumberFromInt32(b, t>>2); /* b=ln(b) coefficient */
5765 b->exponent=-(t&3)-3; /* set exponent */
5766 b->bits=DECNEG; /* ln(0.10)->ln(0.99) always -ve */
5767 aset.digits=16; aset.round=DEC_ROUND_HALF_EVEN; /* restore */
5768 decAddOp(a, a, b, &aset, 0, &ignore); /* acc=a+b */
5769 /* the initial estimate is now in a, with up to 4 digits correct. */
5770 /* When rhs is at or near Nmax the estimate will be low, so we */
5771 /* will approach it from below, avoiding overflow when calling exp. */
5773 decNumberZero(&numone); *numone.lsu=1; /* constant 1 for adjustment */
5775 /* accumulator bounds are as requested (could underflow, but */
5776 /* cannot overflow) */
5777 aset.emax=set->emax;
5778 aset.emin=set->emin;
5779 aset.clamp=0; /* no concrete format */
5780 /* set up a context to be used for the multiply and subtract */
5781 bset=aset;
5782 bset.emax=DEC_MAX_MATH*2; /* use double bounds for the */
5783 bset.emin=-DEC_MAX_MATH*2; /* adjustment calculation */
5784 /* [see decExpOp call below] */
5785 /* for each iteration double the number of digits to calculate, */
5786 /* up to a maximum of p */
5787 pp=9; /* initial precision */
5788 /* [initially 9 as then the sequence starts 7+2, 16+2, and */
5789 /* 34+2, which is ideal for standard-sized numbers] */
5790 aset.digits=pp; /* working context */
5791 bset.digits=pp+rhs->digits; /* wider context */
5792 for (;;) { /* iterate */
5793 #if DECCHECK
5794 iterations++;
5795 if (iterations>24) break; /* consider 9 * 2**24 */
5796 #endif
5797 /* calculate the adjustment (exp(-a)*x-1) into b. This is a */
5798 /* catastrophic subtraction but it really is the difference */
5799 /* from 1 that is of interest. */
5800 /* Use the internal entry point to Exp as it allows the double */
5801 /* range for calculating exp(-a) when a is the tiniest subnormal. */
5802 a->bits^=DECNEG; /* make -a */
5803 decExpOp(b, a, &bset, &ignore); /* b=exp(-a) */
5804 a->bits^=DECNEG; /* restore sign of a */
5805 /* now multiply by rhs and subtract 1, at the wider precision */
5806 decMultiplyOp(b, b, rhs, &bset, &ignore); /* b=b*rhs */
5807 decAddOp(b, b, &numone, &bset, DECNEG, &ignore); /* b=b-1 */
5809 /* the iteration ends when the adjustment cannot affect the */
5810 /* result by >=0.5 ulp (at the requested digits), which */
5811 /* is when its value is smaller than the accumulator by */
5812 /* set->digits+1 digits (or it is zero) -- this is a looser */
5813 /* requirement than for Exp because all that happens to the */
5814 /* accumulator after this is the final rounding (but note that */
5815 /* there must also be full precision in a, or a=0). */
5817 if (decNumberIsZero(b) ||
5818 (a->digits+a->exponent)>=(b->digits+b->exponent+set->digits+1)) {
5819 if (a->digits==p) break;
5820 if (decNumberIsZero(a)) {
5821 decCompareOp(&cmp, rhs, &numone, &aset, COMPARE, &ignore); /* rhs=1 ? */
5822 if (cmp.lsu[0]==0) a->exponent=0; /* yes, exact 0 */
5823 else *status|=(DEC_Inexact | DEC_Rounded); /* no, inexact */
5824 break;
5826 /* force padding if adjustment has gone to 0 before full length */
5827 if (decNumberIsZero(b)) b->exponent=a->exponent-p;
5830 /* not done yet ... */
5831 decAddOp(a, a, b, &aset, 0, &ignore); /* a=a+b for next estimate */
5832 if (pp==p) continue; /* precision is at maximum */
5833 /* lengthen the next calculation */
5834 pp=pp*2; /* double precision */
5835 if (pp>p) pp=p; /* clamp to maximum */
5836 aset.digits=pp; /* working context */
5837 bset.digits=pp+rhs->digits; /* wider context */
5838 } /* Newton's iteration */
5840 #if DECCHECK
5841 /* just a sanity check; remove the test to show always */
5842 if (iterations>24)
5843 printf("Ln iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
5844 iterations, *status, p, rhs->digits);
5845 #endif
5847 /* Copy and round the result to res */
5848 residue=1; /* indicate dirt to right */
5849 if (ISZERO(a)) residue=0; /* .. unless underflowed to 0 */
5850 aset.digits=set->digits; /* [use default rounding] */
5851 decCopyFit(res, a, &aset, &residue, status); /* copy & shorten */
5852 decFinish(res, set, &residue, status); /* cleanup/set flags */
5853 } while(0); /* end protected */
5855 if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */
5856 if (allocbufb!=NULL) free(allocbufb); /* .. */
5857 /* [status is handled by caller] */
5858 return res;
5859 } /* decLnOp */
5861 /* ------------------------------------------------------------------ */
5862 /* decQuantizeOp -- force exponent to requested value */
5863 /* */
5864 /* This computes C = op(A, B), where op adjusts the coefficient */
5865 /* of C (by rounding or shifting) such that the exponent (-scale) */
5866 /* of C has the value B or matches the exponent of B. */
5867 /* The numerical value of C will equal A, except for the effects of */
5868 /* any rounding that occurred. */
5869 /* */
5870 /* res is C, the result. C may be A or B */
5871 /* lhs is A, the number to adjust */
5872 /* rhs is B, the requested exponent */
5873 /* set is the context */
5874 /* quant is 1 for quantize or 0 for rescale */
5875 /* status is the status accumulator (this can be called without */
5876 /* risk of control loss) */
5877 /* */
5878 /* C must have space for set->digits digits. */
5879 /* */
5880 /* Unless there is an error or the result is infinite, the exponent */
5881 /* after the operation is guaranteed to be that requested. */
5882 /* ------------------------------------------------------------------ */
5883 static decNumber * decQuantizeOp(decNumber *res, const decNumber *lhs,
5884 const decNumber *rhs, decContext *set,
5885 Flag quant, uInt *status) {
5886 #if DECSUBSET
5887 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */
5888 decNumber *allocrhs=NULL; /* .., rhs */
5889 #endif
5890 const decNumber *inrhs=rhs; /* save original rhs */
5891 Int reqdigits=set->digits; /* requested DIGITS */
5892 Int reqexp; /* requested exponent [-scale] */
5893 Int residue=0; /* rounding residue */
5894 Int etiny=set->emin-(reqdigits-1);
5896 #if DECCHECK
5897 if (decCheckOperands(res, lhs, rhs, set)) return res;
5898 #endif
5900 do { /* protect allocated storage */
5901 #if DECSUBSET
5902 if (!set->extended) {
5903 /* reduce operands and set lostDigits status, as needed */
5904 if (lhs->digits>reqdigits) {
5905 alloclhs=decRoundOperand(lhs, set, status);
5906 if (alloclhs==NULL) break;
5907 lhs=alloclhs;
5909 if (rhs->digits>reqdigits) { /* [this only checks lostDigits] */
5910 allocrhs=decRoundOperand(rhs, set, status);
5911 if (allocrhs==NULL) break;
5912 rhs=allocrhs;
5915 #endif
5916 /* [following code does not require input rounding] */
5918 /* Handle special values */
5919 if (SPECIALARGS) {
5920 /* NaNs get usual processing */
5921 if (SPECIALARGS & (DECSNAN | DECNAN))
5922 decNaNs(res, lhs, rhs, set, status);
5923 /* one infinity but not both is bad */
5924 else if ((lhs->bits ^ rhs->bits) & DECINF)
5925 *status|=DEC_Invalid_operation;
5926 /* both infinity: return lhs */
5927 else decNumberCopy(res, lhs); /* [nop if in place] */
5928 break;
5931 /* set requested exponent */
5932 if (quant) reqexp=inrhs->exponent; /* quantize -- match exponents */
5933 else { /* rescale -- use value of rhs */
5934 /* Original rhs must be an integer that fits and is in range, */
5935 /* which could be from -1999999997 to +999999999, thanks to */
5936 /* subnormals */
5937 reqexp=decGetInt(inrhs); /* [cannot fail] */
5940 #if DECSUBSET
5941 if (!set->extended) etiny=set->emin; /* no subnormals */
5942 #endif
5944 if (reqexp==BADINT /* bad (rescale only) or .. */
5945 || reqexp==BIGODD || reqexp==BIGEVEN /* very big (ditto) or .. */
5946 || (reqexp<etiny) /* < lowest */
5947 || (reqexp>set->emax)) { /* > emax */
5948 *status|=DEC_Invalid_operation;
5949 break;}
5951 /* the RHS has been processed, so it can be overwritten now if necessary */
5952 if (ISZERO(lhs)) { /* zero coefficient unchanged */
5953 decNumberCopy(res, lhs); /* [nop if in place] */
5954 res->exponent=reqexp; /* .. just set exponent */
5955 #if DECSUBSET
5956 if (!set->extended) res->bits=0; /* subset specification; no -0 */
5957 #endif
5959 else { /* non-zero lhs */
5960 Int adjust=reqexp-lhs->exponent; /* digit adjustment needed */
5961 /* if adjusted coefficient will definitely not fit, give up now */
5962 if ((lhs->digits-adjust)>reqdigits) {
5963 *status|=DEC_Invalid_operation;
5964 break;
5967 if (adjust>0) { /* increasing exponent */
5968 /* this will decrease the length of the coefficient by adjust */
5969 /* digits, and must round as it does so */
5970 decContext workset; /* work */
5971 workset=*set; /* clone rounding, etc. */
5972 workset.digits=lhs->digits-adjust; /* set requested length */
5973 /* [note that the latter can be <1, here] */
5974 decCopyFit(res, lhs, &workset, &residue, status); /* fit to result */
5975 decApplyRound(res, &workset, residue, status); /* .. and round */
5976 residue=0; /* [used] */
5977 /* If just rounded a 999s case, exponent will be off by one; */
5978 /* adjust back (after checking space), if so. */
5979 if (res->exponent>reqexp) {
5980 /* re-check needed, e.g., for quantize(0.9999, 0.001) under */
5981 /* set->digits==3 */
5982 if (res->digits==reqdigits) { /* cannot shift by 1 */
5983 *status&=~(DEC_Inexact | DEC_Rounded); /* [clean these] */
5984 *status|=DEC_Invalid_operation;
5985 break;
5987 res->digits=decShiftToMost(res->lsu, res->digits, 1); /* shift */
5988 res->exponent--; /* (re)adjust the exponent. */
5990 #if DECSUBSET
5991 if (ISZERO(res) && !set->extended) res->bits=0; /* subset; no -0 */
5992 #endif
5993 } /* increase */
5994 else /* adjust<=0 */ { /* decreasing or = exponent */
5995 /* this will increase the length of the coefficient by -adjust */
5996 /* digits, by adding zero or more trailing zeros; this is */
5997 /* already checked for fit, above */
5998 decNumberCopy(res, lhs); /* [it will fit] */
5999 /* if padding needed (adjust<0), add it now... */
6000 if (adjust<0) {
6001 res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
6002 res->exponent+=adjust; /* adjust the exponent */
6004 } /* decrease */
6005 } /* non-zero */
6007 /* Check for overflow [do not use Finalize in this case, as an */
6008 /* overflow here is a "don't fit" situation] */
6009 if (res->exponent>set->emax-res->digits+1) { /* too big */
6010 *status|=DEC_Invalid_operation;
6011 break;
6013 else {
6014 decFinalize(res, set, &residue, status); /* set subnormal flags */
6015 *status&=~DEC_Underflow; /* suppress Underflow [754r] */
6017 } while(0); /* end protected */
6019 #if DECSUBSET
6020 if (allocrhs!=NULL) free(allocrhs); /* drop any storage used */
6021 if (alloclhs!=NULL) free(alloclhs); /* .. */
6022 #endif
6023 return res;
6024 } /* decQuantizeOp */
6026 /* ------------------------------------------------------------------ */
6027 /* decCompareOp -- compare, min, or max two Numbers */
6028 /* */
6029 /* This computes C = A ? B and carries out one of four operations: */
6030 /* COMPARE -- returns the signum (as a number) giving the */
6031 /* result of a comparison unless one or both */
6032 /* operands is a NaN (in which case a NaN results) */
6033 /* COMPSIG -- as COMPARE except that a quiet NaN raises */
6034 /* Invalid operation. */
6035 /* COMPMAX -- returns the larger of the operands, using the */
6036 /* 754r maxnum operation */
6037 /* COMPMAXMAG -- ditto, comparing absolute values */
6038 /* COMPMIN -- the 754r minnum operation */
6039 /* COMPMINMAG -- ditto, comparing absolute values */
6040 /* COMTOTAL -- returns the signum (as a number) giving the */
6041 /* result of a comparison using 754r total ordering */
6042 /* */
6043 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
6044 /* lhs is A */
6045 /* rhs is B */
6046 /* set is the context */
6047 /* op is the operation flag */
6048 /* status is the usual accumulator */
6049 /* */
6050 /* C must have space for one digit for COMPARE or set->digits for */
6051 /* COMPMAX, COMPMIN, COMPMAXMAG, or COMPMINMAG. */
6052 /* ------------------------------------------------------------------ */
6053 /* The emphasis here is on speed for common cases, and avoiding */
6054 /* coefficient comparison if possible. */
6055 /* ------------------------------------------------------------------ */
6056 static decNumber *decCompareOp(decNumber *res, const decNumber *lhs,
6057 const decNumber *rhs, decContext *set,
6058 Flag op, uInt *status) {
6059 #if DECSUBSET
6060 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */
6061 decNumber *allocrhs=NULL; /* .., rhs */
6062 #endif
6063 Int result=0; /* default result value */
6064 uByte merged; /* work */
6066 #if DECCHECK
6067 if (decCheckOperands(res, lhs, rhs, set)) return res;
6068 #endif
6070 do { /* protect allocated storage */
6071 #if DECSUBSET
6072 if (!set->extended) {
6073 /* reduce operands and set lostDigits status, as needed */
6074 if (lhs->digits>set->digits) {
6075 alloclhs=decRoundOperand(lhs, set, status);
6076 if (alloclhs==NULL) {result=BADINT; break;}
6077 lhs=alloclhs;
6079 if (rhs->digits>set->digits) {
6080 allocrhs=decRoundOperand(rhs, set, status);
6081 if (allocrhs==NULL) {result=BADINT; break;}
6082 rhs=allocrhs;
6085 #endif
6086 /* [following code does not require input rounding] */
6088 /* If total ordering then handle differing signs 'up front' */
6089 if (op==COMPTOTAL) { /* total ordering */
6090 if (decNumberIsNegative(lhs) && !decNumberIsNegative(rhs)) {
6091 result=-1;
6092 break;
6094 if (!decNumberIsNegative(lhs) && decNumberIsNegative(rhs)) {
6095 result=+1;
6096 break;
6100 /* handle NaNs specially; let infinities drop through */
6101 /* This assumes sNaN (even just one) leads to NaN. */
6102 merged=(lhs->bits | rhs->bits) & (DECSNAN | DECNAN);
6103 if (merged) { /* a NaN bit set */
6104 if (op==COMPARE); /* result will be NaN */
6105 else if (op==COMPSIG) /* treat qNaN as sNaN */
6106 *status|=DEC_Invalid_operation | DEC_sNaN;
6107 else if (op==COMPTOTAL) { /* total ordering, always finite */
6108 /* signs are known to be the same; compute the ordering here */
6109 /* as if the signs are both positive, then invert for negatives */
6110 if (!decNumberIsNaN(lhs)) result=-1;
6111 else if (!decNumberIsNaN(rhs)) result=+1;
6112 /* here if both NaNs */
6113 else if (decNumberIsSNaN(lhs) && decNumberIsQNaN(rhs)) result=-1;
6114 else if (decNumberIsQNaN(lhs) && decNumberIsSNaN(rhs)) result=+1;
6115 else { /* both NaN or both sNaN */
6116 /* now it just depends on the payload */
6117 result=decUnitCompare(lhs->lsu, D2U(lhs->digits),
6118 rhs->lsu, D2U(rhs->digits), 0);
6119 /* [Error not possible, as these are 'aligned'] */
6120 } /* both same NaNs */
6121 if (decNumberIsNegative(lhs)) result=-result;
6122 break;
6123 } /* total order */
6125 else if (merged & DECSNAN); /* sNaN -> qNaN */
6126 else { /* here if MIN or MAX and one or two quiet NaNs */
6127 /* min or max -- 754r rules ignore single NaN */
6128 if (!decNumberIsNaN(lhs) || !decNumberIsNaN(rhs)) {
6129 /* just one NaN; force choice to be the non-NaN operand */
6130 op=COMPMAX;
6131 if (lhs->bits & DECNAN) result=-1; /* pick rhs */
6132 else result=+1; /* pick lhs */
6133 break;
6135 } /* max or min */
6136 op=COMPNAN; /* use special path */
6137 decNaNs(res, lhs, rhs, set, status); /* propagate NaN */
6138 break;
6140 /* have numbers */
6141 if (op==COMPMAXMAG || op==COMPMINMAG) result=decCompare(lhs, rhs, 1);
6142 else result=decCompare(lhs, rhs, 0); /* sign matters */
6143 } while(0); /* end protected */
6145 if (result==BADINT) *status|=DEC_Insufficient_storage; /* rare */
6146 else {
6147 if (op==COMPARE || op==COMPSIG ||op==COMPTOTAL) { /* returning signum */
6148 if (op==COMPTOTAL && result==0) {
6149 /* operands are numerically equal or same NaN (and same sign, */
6150 /* tested first); if identical, leave result 0 */
6151 if (lhs->exponent!=rhs->exponent) {
6152 if (lhs->exponent<rhs->exponent) result=-1;
6153 else result=+1;
6154 if (decNumberIsNegative(lhs)) result=-result;
6155 } /* lexp!=rexp */
6156 } /* total-order by exponent */
6157 decNumberZero(res); /* [always a valid result] */
6158 if (result!=0) { /* must be -1 or +1 */
6159 *res->lsu=1;
6160 if (result<0) res->bits=DECNEG;
6163 else if (op==COMPNAN); /* special, drop through */
6164 else { /* MAX or MIN, non-NaN result */
6165 Int residue=0; /* rounding accumulator */
6166 /* choose the operand for the result */
6167 const decNumber *choice;
6168 if (result==0) { /* operands are numerically equal */
6169 /* choose according to sign then exponent (see 754r) */
6170 uByte slhs=(lhs->bits & DECNEG);
6171 uByte srhs=(rhs->bits & DECNEG);
6172 #if DECSUBSET
6173 if (!set->extended) { /* subset: force left-hand */
6174 op=COMPMAX;
6175 result=+1;
6177 else
6178 #endif
6179 if (slhs!=srhs) { /* signs differ */
6180 if (slhs) result=-1; /* rhs is max */
6181 else result=+1; /* lhs is max */
6183 else if (slhs && srhs) { /* both negative */
6184 if (lhs->exponent<rhs->exponent) result=+1;
6185 else result=-1;
6186 /* [if equal, use lhs, technically identical] */
6188 else { /* both positive */
6189 if (lhs->exponent>rhs->exponent) result=+1;
6190 else result=-1;
6191 /* [ditto] */
6193 } /* numerically equal */
6194 /* here result will be non-0; reverse if looking for MIN */
6195 if (op==COMPMIN || op==COMPMINMAG) result=-result;
6196 choice=(result>0 ? lhs : rhs); /* choose */
6197 /* copy chosen to result, rounding if need be */
6198 decCopyFit(res, choice, set, &residue, status);
6199 decFinish(res, set, &residue, status);
6202 #if DECSUBSET
6203 if (allocrhs!=NULL) free(allocrhs); /* free any storage used */
6204 if (alloclhs!=NULL) free(alloclhs); /* .. */
6205 #endif
6206 return res;
6207 } /* decCompareOp */
6209 /* ------------------------------------------------------------------ */
6210 /* decCompare -- compare two decNumbers by numerical value */
6211 /* */
6212 /* This routine compares A ? B without altering them. */
6213 /* */
6214 /* Arg1 is A, a decNumber which is not a NaN */
6215 /* Arg2 is B, a decNumber which is not a NaN */
6216 /* Arg3 is 1 for a sign-independent compare, 0 otherwise */
6217 /* */
6218 /* returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure */
6219 /* (the only possible failure is an allocation error) */
6220 /* ------------------------------------------------------------------ */
6221 static Int decCompare(const decNumber *lhs, const decNumber *rhs,
6222 Flag abs) {
6223 Int result; /* result value */
6224 Int sigr; /* rhs signum */
6225 Int compare; /* work */
6227 result=1; /* assume signum(lhs) */
6228 if (ISZERO(lhs)) result=0;
6229 if (abs) {
6230 if (ISZERO(rhs)) return result; /* LHS wins or both 0 */
6231 /* RHS is non-zero */
6232 if (result==0) return -1; /* LHS is 0; RHS wins */
6233 /* [here, both non-zero, result=1] */
6235 else { /* signs matter */
6236 if (result && decNumberIsNegative(lhs)) result=-1;
6237 sigr=1; /* compute signum(rhs) */
6238 if (ISZERO(rhs)) sigr=0;
6239 else if (decNumberIsNegative(rhs)) sigr=-1;
6240 if (result > sigr) return +1; /* L > R, return 1 */
6241 if (result < sigr) return -1; /* L < R, return -1 */
6242 if (result==0) return 0; /* both 0 */
6245 /* signums are the same; both are non-zero */
6246 if ((lhs->bits | rhs->bits) & DECINF) { /* one or more infinities */
6247 if (decNumberIsInfinite(rhs)) {
6248 if (decNumberIsInfinite(lhs)) result=0;/* both infinite */
6249 else result=-result; /* only rhs infinite */
6251 return result;
6253 /* must compare the coefficients, allowing for exponents */
6254 if (lhs->exponent>rhs->exponent) { /* LHS exponent larger */
6255 /* swap sides, and sign */
6256 const decNumber *temp=lhs;
6257 lhs=rhs;
6258 rhs=temp;
6259 result=-result;
6261 compare=decUnitCompare(lhs->lsu, D2U(lhs->digits),
6262 rhs->lsu, D2U(rhs->digits),
6263 rhs->exponent-lhs->exponent);
6264 if (compare!=BADINT) compare*=result; /* comparison succeeded */
6265 return compare;
6266 } /* decCompare */
6268 /* ------------------------------------------------------------------ */
6269 /* decUnitCompare -- compare two >=0 integers in Unit arrays */
6270 /* */
6271 /* This routine compares A ? B*10**E where A and B are unit arrays */
6272 /* A is a plain integer */
6273 /* B has an exponent of E (which must be non-negative) */
6274 /* */
6275 /* Arg1 is A first Unit (lsu) */
6276 /* Arg2 is A length in Units */
6277 /* Arg3 is B first Unit (lsu) */
6278 /* Arg4 is B length in Units */
6279 /* Arg5 is E (0 if the units are aligned) */
6280 /* */
6281 /* returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure */
6282 /* (the only possible failure is an allocation error, which can */
6283 /* only occur if E!=0) */
6284 /* ------------------------------------------------------------------ */
6285 static Int decUnitCompare(const Unit *a, Int alength,
6286 const Unit *b, Int blength, Int exp) {
6287 Unit *acc; /* accumulator for result */
6288 Unit accbuff[SD2U(DECBUFFER*2+1)]; /* local buffer */
6289 Unit *allocacc=NULL; /* -> allocated acc buffer, iff allocated */
6290 Int accunits, need; /* units in use or needed for acc */
6291 const Unit *l, *r, *u; /* work */
6292 Int expunits, exprem, result; /* .. */
6294 if (exp==0) { /* aligned; fastpath */
6295 if (alength>blength) return 1;
6296 if (alength<blength) return -1;
6297 /* same number of units in both -- need unit-by-unit compare */
6298 l=a+alength-1;
6299 r=b+alength-1;
6300 for (;l>=a; l--, r--) {
6301 if (*l>*r) return 1;
6302 if (*l<*r) return -1;
6304 return 0; /* all units match */
6305 } /* aligned */
6307 /* Unaligned. If one is >1 unit longer than the other, padded */
6308 /* approximately, then can return easily */
6309 if (alength>blength+(Int)D2U(exp)) return 1;
6310 if (alength+1<blength+(Int)D2U(exp)) return -1;
6312 /* Need to do a real subtract. For this, a result buffer is needed */
6313 /* even though only the sign is of interest. Its length needs */
6314 /* to be the larger of alength and padded blength, +2 */
6315 need=blength+D2U(exp); /* maximum real length of B */
6316 if (need<alength) need=alength;
6317 need+=2;
6318 acc=accbuff; /* assume use local buffer */
6319 if (need*sizeof(Unit)>sizeof(accbuff)) {
6320 allocacc=(Unit *)malloc(need*sizeof(Unit));
6321 if (allocacc==NULL) return BADINT; /* hopeless -- abandon */
6322 acc=allocacc;
6324 /* Calculate units and remainder from exponent. */
6325 expunits=exp/DECDPUN;
6326 exprem=exp%DECDPUN;
6327 /* subtract [A+B*(-m)] */
6328 accunits=decUnitAddSub(a, alength, b, blength, expunits, acc,
6329 -(Int)powers[exprem]);
6330 /* [UnitAddSub result may have leading zeros, even on zero] */
6331 if (accunits<0) result=-1; /* negative result */
6332 else { /* non-negative result */
6333 /* check units of the result before freeing any storage */
6334 for (u=acc; u<acc+accunits-1 && *u==0;) u++;
6335 result=(*u==0 ? 0 : +1);
6337 /* clean up and return the result */
6338 if (allocacc!=NULL) free(allocacc); /* drop any storage used */
6339 return result;
6340 } /* decUnitCompare */
6342 /* ------------------------------------------------------------------ */
6343 /* decUnitAddSub -- add or subtract two >=0 integers in Unit arrays */
6344 /* */
6345 /* This routine performs the calculation: */
6346 /* */
6347 /* C=A+(B*M) */
6348 /* */
6349 /* Where M is in the range -DECDPUNMAX through +DECDPUNMAX. */
6350 /* */
6351 /* A may be shorter or longer than B. */
6352 /* */
6353 /* Leading zeros are not removed after a calculation. The result is */
6354 /* either the same length as the longer of A and B (adding any */
6355 /* shift), or one Unit longer than that (if a Unit carry occurred). */
6356 /* */
6357 /* A and B content are not altered unless C is also A or B. */
6358 /* C may be the same array as A or B, but only if no zero padding is */
6359 /* requested (that is, C may be B only if bshift==0). */
6360 /* C is filled from the lsu; only those units necessary to complete */
6361 /* the calculation are referenced. */
6362 /* */
6363 /* Arg1 is A first Unit (lsu) */
6364 /* Arg2 is A length in Units */
6365 /* Arg3 is B first Unit (lsu) */
6366 /* Arg4 is B length in Units */
6367 /* Arg5 is B shift in Units (>=0; pads with 0 units if positive) */
6368 /* Arg6 is C first Unit (lsu) */
6369 /* Arg7 is M, the multiplier */
6370 /* */
6371 /* returns the count of Units written to C, which will be non-zero */
6372 /* and negated if the result is negative. That is, the sign of the */
6373 /* returned Int is the sign of the result (positive for zero) and */
6374 /* the absolute value of the Int is the count of Units. */
6375 /* */
6376 /* It is the caller's responsibility to make sure that C size is */
6377 /* safe, allowing space if necessary for a one-Unit carry. */
6378 /* */
6379 /* This routine is severely performance-critical; *any* change here */
6380 /* must be measured (timed) to assure no performance degradation. */
6381 /* In particular, trickery here tends to be counter-productive, as */
6382 /* increased complexity of code hurts register optimizations on */
6383 /* register-poor architectures. Avoiding divisions is nearly */
6384 /* always a Good Idea, however. */
6385 /* */
6386 /* Special thanks to Rick McGuire (IBM Cambridge, MA) and Dave Clark */
6387 /* (IBM Warwick, UK) for some of the ideas used in this routine. */
6388 /* ------------------------------------------------------------------ */
6389 static Int decUnitAddSub(const Unit *a, Int alength,
6390 const Unit *b, Int blength, Int bshift,
6391 Unit *c, Int m) {
6392 const Unit *alsu=a; /* A lsu [need to remember it] */
6393 Unit *clsu=c; /* C ditto */
6394 Unit *minC; /* low water mark for C */
6395 Unit *maxC; /* high water mark for C */
6396 eInt carry=0; /* carry integer (could be Long) */
6397 Int add; /* work */
6398 #if DECDPUN<=4 /* myriadal, millenary, etc. */
6399 Int est; /* estimated quotient */
6400 #endif
6402 #if DECTRACE
6403 if (alength<1 || blength<1)
6404 printf("decUnitAddSub: alen blen m %ld %ld [%ld]\n", alength, blength, m);
6405 #endif
6407 maxC=c+alength; /* A is usually the longer */
6408 minC=c+blength; /* .. and B the shorter */
6409 if (bshift!=0) { /* B is shifted; low As copy across */
6410 minC+=bshift;
6411 /* if in place [common], skip copy unless there's a gap [rare] */
6412 if (a==c && bshift<=alength) {
6413 c+=bshift;
6414 a+=bshift;
6416 else for (; c<clsu+bshift; a++, c++) { /* copy needed */
6417 if (a<alsu+alength) *c=*a;
6418 else *c=0;
6421 if (minC>maxC) { /* swap */
6422 Unit *hold=minC;
6423 minC=maxC;
6424 maxC=hold;
6427 /* For speed, do the addition as two loops; the first where both A */
6428 /* and B contribute, and the second (if necessary) where only one or */
6429 /* other of the numbers contribute. */
6430 /* Carry handling is the same (i.e., duplicated) in each case. */
6431 for (; c<minC; c++) {
6432 carry+=*a;
6433 a++;
6434 carry+=((eInt)*b)*m; /* [special-casing m=1/-1 */
6435 b++; /* here is not a win] */
6436 /* here carry is new Unit of digits; it could be +ve or -ve */
6437 if ((ueInt)carry<=DECDPUNMAX) { /* fastpath 0-DECDPUNMAX */
6438 *c=(Unit)carry;
6439 carry=0;
6440 continue;
6442 #if DECDPUN==4 /* use divide-by-multiply */
6443 if (carry>=0) {
6444 est=(((ueInt)carry>>11)*53687)>>18;
6445 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6446 carry=est; /* likely quotient [89%] */
6447 if (*c<DECDPUNMAX+1) continue; /* estimate was correct */
6448 carry++;
6449 *c-=DECDPUNMAX+1;
6450 continue;
6452 /* negative case */
6453 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6454 est=(((ueInt)carry>>11)*53687)>>18;
6455 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6456 carry=est-(DECDPUNMAX+1); /* correctly negative */
6457 if (*c<DECDPUNMAX+1) continue; /* was OK */
6458 carry++;
6459 *c-=DECDPUNMAX+1;
6460 #elif DECDPUN==3
6461 if (carry>=0) {
6462 est=(((ueInt)carry>>3)*16777)>>21;
6463 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6464 carry=est; /* likely quotient [99%] */
6465 if (*c<DECDPUNMAX+1) continue; /* estimate was correct */
6466 carry++;
6467 *c-=DECDPUNMAX+1;
6468 continue;
6470 /* negative case */
6471 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6472 est=(((ueInt)carry>>3)*16777)>>21;
6473 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6474 carry=est-(DECDPUNMAX+1); /* correctly negative */
6475 if (*c<DECDPUNMAX+1) continue; /* was OK */
6476 carry++;
6477 *c-=DECDPUNMAX+1;
6478 #elif DECDPUN<=2
6479 /* Can use QUOT10 as carry <= 4 digits */
6480 if (carry>=0) {
6481 est=QUOT10(carry, DECDPUN);
6482 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6483 carry=est; /* quotient */
6484 continue;
6486 /* negative case */
6487 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6488 est=QUOT10(carry, DECDPUN);
6489 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6490 carry=est-(DECDPUNMAX+1); /* correctly negative */
6491 #else
6492 /* remainder operator is undefined if negative, so must test */
6493 if ((ueInt)carry<(DECDPUNMAX+1)*2) { /* fastpath carry +1 */
6494 *c=(Unit)(carry-(DECDPUNMAX+1)); /* [helps additions] */
6495 carry=1;
6496 continue;
6498 if (carry>=0) {
6499 *c=(Unit)(carry%(DECDPUNMAX+1));
6500 carry=carry/(DECDPUNMAX+1);
6501 continue;
6503 /* negative case */
6504 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6505 *c=(Unit)(carry%(DECDPUNMAX+1));
6506 carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
6507 #endif
6508 } /* c */
6510 /* now may have one or other to complete */
6511 /* [pretest to avoid loop setup/shutdown] */
6512 if (c<maxC) for (; c<maxC; c++) {
6513 if (a<alsu+alength) { /* still in A */
6514 carry+=*a;
6515 a++;
6517 else { /* inside B */
6518 carry+=((eInt)*b)*m;
6519 b++;
6521 /* here carry is new Unit of digits; it could be +ve or -ve and */
6522 /* magnitude up to DECDPUNMAX squared */
6523 if ((ueInt)carry<=DECDPUNMAX) { /* fastpath 0-DECDPUNMAX */
6524 *c=(Unit)carry;
6525 carry=0;
6526 continue;
6528 /* result for this unit is negative or >DECDPUNMAX */
6529 #if DECDPUN==4 /* use divide-by-multiply */
6530 if (carry>=0) {
6531 est=(((ueInt)carry>>11)*53687)>>18;
6532 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6533 carry=est; /* likely quotient [79.7%] */
6534 if (*c<DECDPUNMAX+1) continue; /* estimate was correct */
6535 carry++;
6536 *c-=DECDPUNMAX+1;
6537 continue;
6539 /* negative case */
6540 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6541 est=(((ueInt)carry>>11)*53687)>>18;
6542 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6543 carry=est-(DECDPUNMAX+1); /* correctly negative */
6544 if (*c<DECDPUNMAX+1) continue; /* was OK */
6545 carry++;
6546 *c-=DECDPUNMAX+1;
6547 #elif DECDPUN==3
6548 if (carry>=0) {
6549 est=(((ueInt)carry>>3)*16777)>>21;
6550 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6551 carry=est; /* likely quotient [99%] */
6552 if (*c<DECDPUNMAX+1) continue; /* estimate was correct */
6553 carry++;
6554 *c-=DECDPUNMAX+1;
6555 continue;
6557 /* negative case */
6558 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6559 est=(((ueInt)carry>>3)*16777)>>21;
6560 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6561 carry=est-(DECDPUNMAX+1); /* correctly negative */
6562 if (*c<DECDPUNMAX+1) continue; /* was OK */
6563 carry++;
6564 *c-=DECDPUNMAX+1;
6565 #elif DECDPUN<=2
6566 if (carry>=0) {
6567 est=QUOT10(carry, DECDPUN);
6568 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6569 carry=est; /* quotient */
6570 continue;
6572 /* negative case */
6573 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6574 est=QUOT10(carry, DECDPUN);
6575 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6576 carry=est-(DECDPUNMAX+1); /* correctly negative */
6577 #else
6578 if ((ueInt)carry<(DECDPUNMAX+1)*2){ /* fastpath carry 1 */
6579 *c=(Unit)(carry-(DECDPUNMAX+1));
6580 carry=1;
6581 continue;
6583 /* remainder operator is undefined if negative, so must test */
6584 if (carry>=0) {
6585 *c=(Unit)(carry%(DECDPUNMAX+1));
6586 carry=carry/(DECDPUNMAX+1);
6587 continue;
6589 /* negative case */
6590 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6591 *c=(Unit)(carry%(DECDPUNMAX+1));
6592 carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
6593 #endif
6594 } /* c */
6596 /* OK, all A and B processed; might still have carry or borrow */
6597 /* return number of Units in the result, negated if a borrow */
6598 if (carry==0) return c-clsu; /* no carry, so no more to do */
6599 if (carry>0) { /* positive carry */
6600 *c=(Unit)carry; /* place as new unit */
6601 c++; /* .. */
6602 return c-clsu;
6604 /* -ve carry: it's a borrow; complement needed */
6605 add=1; /* temporary carry... */
6606 for (c=clsu; c<maxC; c++) {
6607 add=DECDPUNMAX+add-*c;
6608 if (add<=DECDPUNMAX) {
6609 *c=(Unit)add;
6610 add=0;
6612 else {
6613 *c=0;
6614 add=1;
6617 /* add an extra unit iff it would be non-zero */
6618 #if DECTRACE
6619 printf("UAS borrow: add %ld, carry %ld\n", add, carry);
6620 #endif
6621 if ((add-carry-1)!=0) {
6622 *c=(Unit)(add-carry-1);
6623 c++; /* interesting, include it */
6625 return clsu-c; /* -ve result indicates borrowed */
6626 } /* decUnitAddSub */
6628 /* ------------------------------------------------------------------ */
6629 /* decTrim -- trim trailing zeros or normalize */
6630 /* */
6631 /* dn is the number to trim or normalize */
6632 /* set is the context to use to check for clamp */
6633 /* all is 1 to remove all trailing zeros, 0 for just fraction ones */
6634 /* dropped returns the number of discarded trailing zeros */
6635 /* returns dn */
6636 /* */
6637 /* If clamp is set in the context then the number of zeros trimmed */
6638 /* may be limited if the exponent is high. */
6639 /* All fields are updated as required. This is a utility operation, */
6640 /* so special values are unchanged and no error is possible. */
6641 /* ------------------------------------------------------------------ */
6642 static decNumber * decTrim(decNumber *dn, decContext *set, Flag all,
6643 Int *dropped) {
6644 Int d, exp; /* work */
6645 uInt cut; /* .. */
6646 Unit *up; /* -> current Unit */
6648 #if DECCHECK
6649 if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
6650 #endif
6652 *dropped=0; /* assume no zeros dropped */
6653 if ((dn->bits & DECSPECIAL) /* fast exit if special .. */
6654 || (*dn->lsu & 0x01)) return dn; /* .. or odd */
6655 if (ISZERO(dn)) { /* .. or 0 */
6656 dn->exponent=0; /* (sign is preserved) */
6657 return dn;
6660 /* have a finite number which is even */
6661 exp=dn->exponent;
6662 cut=1; /* digit (1-DECDPUN) in Unit */
6663 up=dn->lsu; /* -> current Unit */
6664 for (d=0; d<dn->digits-1; d++) { /* [don't strip the final digit] */
6665 /* slice by powers */
6666 #if DECDPUN<=4
6667 uInt quot=QUOT10(*up, cut);
6668 if ((*up-quot*powers[cut])!=0) break; /* found non-0 digit */
6669 #else
6670 if (*up%powers[cut]!=0) break; /* found non-0 digit */
6671 #endif
6672 /* have a trailing 0 */
6673 if (!all) { /* trimming */
6674 /* [if exp>0 then all trailing 0s are significant for trim] */
6675 if (exp<=0) { /* if digit might be significant */
6676 if (exp==0) break; /* then quit */
6677 exp++; /* next digit might be significant */
6680 cut++; /* next power */
6681 if (cut>DECDPUN) { /* need new Unit */
6682 up++;
6683 cut=1;
6685 } /* d */
6686 if (d==0) return dn; /* none to drop */
6688 /* may need to limit drop if clamping */
6689 if (set->clamp) {
6690 Int maxd=set->emax-set->digits+1-dn->exponent;
6691 if (maxd<=0) return dn; /* nothing possible */
6692 if (d>maxd) d=maxd;
6695 /* effect the drop */
6696 decShiftToLeast(dn->lsu, D2U(dn->digits), d);
6697 dn->exponent+=d; /* maintain numerical value */
6698 dn->digits-=d; /* new length */
6699 *dropped=d; /* report the count */
6700 return dn;
6701 } /* decTrim */
6703 /* ------------------------------------------------------------------ */
6704 /* decReverse -- reverse a Unit array in place */
6705 /* */
6706 /* ulo is the start of the array */
6707 /* uhi is the end of the array (highest Unit to include) */
6708 /* */
6709 /* The units ulo through uhi are reversed in place (if the number */
6710 /* of units is odd, the middle one is untouched). Note that the */
6711 /* digit(s) in each unit are unaffected. */
6712 /* ------------------------------------------------------------------ */
6713 static void decReverse(Unit *ulo, Unit *uhi) {
6714 Unit temp;
6715 for (; ulo<uhi; ulo++, uhi--) {
6716 temp=*ulo;
6717 *ulo=*uhi;
6718 *uhi=temp;
6720 return;
6721 } /* decReverse */
6723 /* ------------------------------------------------------------------ */
6724 /* decShiftToMost -- shift digits in array towards most significant */
6725 /* */
6726 /* uar is the array */
6727 /* digits is the count of digits in use in the array */
6728 /* shift is the number of zeros to pad with (least significant); */
6729 /* it must be zero or positive */
6730 /* */
6731 /* returns the new length of the integer in the array, in digits */
6732 /* */
6733 /* No overflow is permitted (that is, the uar array must be known to */
6734 /* be large enough to hold the result, after shifting). */
6735 /* ------------------------------------------------------------------ */
6736 static Int decShiftToMost(Unit *uar, Int digits, Int shift) {
6737 Unit *target, *source, *first; /* work */
6738 Int cut; /* odd 0's to add */
6739 uInt next; /* work */
6741 if (shift==0) return digits; /* [fastpath] nothing to do */
6742 if ((digits+shift)<=DECDPUN) { /* [fastpath] single-unit case */
6743 *uar=(Unit)(*uar*powers[shift]);
6744 return digits+shift;
6747 next=0; /* all paths */
6748 source=uar+D2U(digits)-1; /* where msu comes from */
6749 target=source+D2U(shift); /* where upper part of first cut goes */
6750 cut=DECDPUN-MSUDIGITS(shift); /* where to slice */
6751 if (cut==0) { /* unit-boundary case */
6752 for (; source>=uar; source--, target--) *target=*source;
6754 else {
6755 first=uar+D2U(digits+shift)-1; /* where msu of source will end up */
6756 for (; source>=uar; source--, target--) {
6757 /* split the source Unit and accumulate remainder for next */
6758 #if DECDPUN<=4
6759 uInt quot=QUOT10(*source, cut);
6760 uInt rem=*source-quot*powers[cut];
6761 next+=quot;
6762 #else
6763 uInt rem=*source%powers[cut];
6764 next+=*source/powers[cut];
6765 #endif
6766 if (target<=first) *target=(Unit)next; /* write to target iff valid */
6767 next=rem*powers[DECDPUN-cut]; /* save remainder for next Unit */
6769 } /* shift-move */
6771 /* propagate any partial unit to one below and clear the rest */
6772 for (; target>=uar; target--) {
6773 *target=(Unit)next;
6774 next=0;
6776 return digits+shift;
6777 } /* decShiftToMost */
6779 /* ------------------------------------------------------------------ */
6780 /* decShiftToLeast -- shift digits in array towards least significant */
6781 /* */
6782 /* uar is the array */
6783 /* units is length of the array, in units */
6784 /* shift is the number of digits to remove from the lsu end; it */
6785 /* must be zero or positive and <= than units*DECDPUN. */
6786 /* */
6787 /* returns the new length of the integer in the array, in units */
6788 /* */
6789 /* Removed digits are discarded (lost). Units not required to hold */
6790 /* the final result are unchanged. */
6791 /* ------------------------------------------------------------------ */
6792 static Int decShiftToLeast(Unit *uar, Int units, Int shift) {
6793 Unit *target, *up; /* work */
6794 Int cut, count; /* work */
6795 Int quot, rem; /* for division */
6797 if (shift==0) return units; /* [fastpath] nothing to do */
6798 if (shift==units*DECDPUN) { /* [fastpath] little to do */
6799 *uar=0; /* all digits cleared gives zero */
6800 return 1; /* leaves just the one */
6803 target=uar; /* both paths */
6804 cut=MSUDIGITS(shift);
6805 if (cut==DECDPUN) { /* unit-boundary case; easy */
6806 up=uar+D2U(shift);
6807 for (; up<uar+units; target++, up++) *target=*up;
6808 return target-uar;
6811 /* messier */
6812 up=uar+D2U(shift-cut); /* source; correct to whole Units */
6813 count=units*DECDPUN-shift; /* the maximum new length */
6814 #if DECDPUN<=4
6815 quot=QUOT10(*up, cut);
6816 #else
6817 quot=*up/powers[cut];
6818 #endif
6819 for (; ; target++) {
6820 *target=(Unit)quot;
6821 count-=(DECDPUN-cut);
6822 if (count<=0) break;
6823 up++;
6824 quot=*up;
6825 #if DECDPUN<=4
6826 quot=QUOT10(quot, cut);
6827 rem=*up-quot*powers[cut];
6828 #else
6829 rem=quot%powers[cut];
6830 quot=quot/powers[cut];
6831 #endif
6832 *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
6833 count-=cut;
6834 if (count<=0) break;
6836 return target-uar+1;
6837 } /* decShiftToLeast */
6839 #if DECSUBSET
6840 /* ------------------------------------------------------------------ */
6841 /* decRoundOperand -- round an operand [used for subset only] */
6842 /* */
6843 /* dn is the number to round (dn->digits is > set->digits) */
6844 /* set is the relevant context */
6845 /* status is the status accumulator */
6846 /* */
6847 /* returns an allocated decNumber with the rounded result. */
6848 /* */
6849 /* lostDigits and other status may be set by this. */
6850 /* */
6851 /* Since the input is an operand, it must not be modified. */
6852 /* Instead, return an allocated decNumber, rounded as required. */
6853 /* It is the caller's responsibility to free the allocated storage. */
6854 /* */
6855 /* If no storage is available then the result cannot be used, so NULL */
6856 /* is returned. */
6857 /* ------------------------------------------------------------------ */
6858 static decNumber *decRoundOperand(const decNumber *dn, decContext *set,
6859 uInt *status) {
6860 decNumber *res; /* result structure */
6861 uInt newstatus=0; /* status from round */
6862 Int residue=0; /* rounding accumulator */
6864 /* Allocate storage for the returned decNumber, big enough for the */
6865 /* length specified by the context */
6866 res=(decNumber *)malloc(sizeof(decNumber)
6867 +(D2U(set->digits)-1)*sizeof(Unit));
6868 if (res==NULL) {
6869 *status|=DEC_Insufficient_storage;
6870 return NULL;
6872 decCopyFit(res, dn, set, &residue, &newstatus);
6873 decApplyRound(res, set, residue, &newstatus);
6875 /* If that set Inexact then "lost digits" is raised... */
6876 if (newstatus & DEC_Inexact) newstatus|=DEC_Lost_digits;
6877 *status|=newstatus;
6878 return res;
6879 } /* decRoundOperand */
6880 #endif
6882 /* ------------------------------------------------------------------ */
6883 /* decCopyFit -- copy a number, truncating the coefficient if needed */
6884 /* */
6885 /* dest is the target decNumber */
6886 /* src is the source decNumber */
6887 /* set is the context [used for length (digits) and rounding mode] */
6888 /* residue is the residue accumulator */
6889 /* status contains the current status to be updated */
6890 /* */
6891 /* (dest==src is allowed and will be a no-op if fits) */
6892 /* All fields are updated as required. */
6893 /* ------------------------------------------------------------------ */
6894 static void decCopyFit(decNumber *dest, const decNumber *src,
6895 decContext *set, Int *residue, uInt *status) {
6896 dest->bits=src->bits;
6897 dest->exponent=src->exponent;
6898 decSetCoeff(dest, set, src->lsu, src->digits, residue, status);
6899 } /* decCopyFit */
6901 /* ------------------------------------------------------------------ */
6902 /* decSetCoeff -- set the coefficient of a number */
6903 /* */
6904 /* dn is the number whose coefficient array is to be set. */
6905 /* It must have space for set->digits digits */
6906 /* set is the context [for size] */
6907 /* lsu -> lsu of the source coefficient [may be dn->lsu] */
6908 /* len is digits in the source coefficient [may be dn->digits] */
6909 /* residue is the residue accumulator. This has values as in */
6910 /* decApplyRound, and will be unchanged unless the */
6911 /* target size is less than len. In this case, the */
6912 /* coefficient is truncated and the residue is updated to */
6913 /* reflect the previous residue and the dropped digits. */
6914 /* status is the status accumulator, as usual */
6915 /* */
6916 /* The coefficient may already be in the number, or it can be an */
6917 /* external intermediate array. If it is in the number, lsu must == */
6918 /* dn->lsu and len must == dn->digits. */
6919 /* */
6920 /* Note that the coefficient length (len) may be < set->digits, and */
6921 /* in this case this merely copies the coefficient (or is a no-op */
6922 /* if dn->lsu==lsu). */
6923 /* */
6924 /* Note also that (only internally, from decQuantizeOp and */
6925 /* decSetSubnormal) the value of set->digits may be less than one, */
6926 /* indicating a round to left. This routine handles that case */
6927 /* correctly; caller ensures space. */
6928 /* */
6929 /* dn->digits, dn->lsu (and as required), and dn->exponent are */
6930 /* updated as necessary. dn->bits (sign) is unchanged. */
6931 /* */
6932 /* DEC_Rounded status is set if any digits are discarded. */
6933 /* DEC_Inexact status is set if any non-zero digits are discarded, or */
6934 /* incoming residue was non-0 (implies rounded) */
6935 /* ------------------------------------------------------------------ */
6936 /* mapping array: maps 0-9 to canonical residues, so that a residue */
6937 /* can be adjusted in the range [-1, +1] and achieve correct rounding */
6938 /* 0 1 2 3 4 5 6 7 8 9 */
6939 static const uByte resmap[10]={0, 3, 3, 3, 3, 5, 7, 7, 7, 7};
6940 static void decSetCoeff(decNumber *dn, decContext *set, const Unit *lsu,
6941 Int len, Int *residue, uInt *status) {
6942 Int discard; /* number of digits to discard */
6943 uInt cut; /* cut point in Unit */
6944 const Unit *up; /* work */
6945 Unit *target; /* .. */
6946 Int count; /* .. */
6947 #if DECDPUN<=4
6948 uInt temp; /* .. */
6949 #endif
6951 discard=len-set->digits; /* digits to discard */
6952 if (discard<=0) { /* no digits are being discarded */
6953 if (dn->lsu!=lsu) { /* copy needed */
6954 /* copy the coefficient array to the result number; no shift needed */
6955 count=len; /* avoids D2U */
6956 up=lsu;
6957 for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
6958 *target=*up;
6959 dn->digits=len; /* set the new length */
6961 /* dn->exponent and residue are unchanged, record any inexactitude */
6962 if (*residue!=0) *status|=(DEC_Inexact | DEC_Rounded);
6963 return;
6966 /* some digits must be discarded ... */
6967 dn->exponent+=discard; /* maintain numerical value */
6968 *status|=DEC_Rounded; /* accumulate Rounded status */
6969 if (*residue>1) *residue=1; /* previous residue now to right, so reduce */
6971 if (discard>len) { /* everything, +1, is being discarded */
6972 /* guard digit is 0 */
6973 /* residue is all the number [NB could be all 0s] */
6974 if (*residue<=0) { /* not already positive */
6975 count=len; /* avoids D2U */
6976 for (up=lsu; count>0; up++, count-=DECDPUN) if (*up!=0) { /* found non-0 */
6977 *residue=1;
6978 break; /* no need to check any others */
6981 if (*residue!=0) *status|=DEC_Inexact; /* record inexactitude */
6982 *dn->lsu=0; /* coefficient will now be 0 */
6983 dn->digits=1; /* .. */
6984 return;
6985 } /* total discard */
6987 /* partial discard [most common case] */
6988 /* here, at least the first (most significant) discarded digit exists */
6990 /* spin up the number, noting residue during the spin, until get to */
6991 /* the Unit with the first discarded digit. When reach it, extract */
6992 /* it and remember its position */
6993 count=0;
6994 for (up=lsu;; up++) {
6995 count+=DECDPUN;
6996 if (count>=discard) break; /* full ones all checked */
6997 if (*up!=0) *residue=1;
6998 } /* up */
7000 /* here up -> Unit with first discarded digit */
7001 cut=discard-(count-DECDPUN)-1;
7002 if (cut==DECDPUN-1) { /* unit-boundary case (fast) */
7003 Unit half=(Unit)powers[DECDPUN]>>1;
7004 /* set residue directly */
7005 if (*up>=half) {
7006 if (*up>half) *residue=7;
7007 else *residue+=5; /* add sticky bit */
7009 else { /* <half */
7010 if (*up!=0) *residue=3; /* [else is 0, leave as sticky bit] */
7012 if (set->digits<=0) { /* special for Quantize/Subnormal :-( */
7013 *dn->lsu=0; /* .. result is 0 */
7014 dn->digits=1; /* .. */
7016 else { /* shift to least */
7017 count=set->digits; /* now digits to end up with */
7018 dn->digits=count; /* set the new length */
7019 up++; /* move to next */
7020 /* on unit boundary, so shift-down copy loop is simple */
7021 for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
7022 *target=*up;
7024 } /* unit-boundary case */
7026 else { /* discard digit is in low digit(s), and not top digit */
7027 uInt discard1; /* first discarded digit */
7028 uInt quot, rem; /* for divisions */
7029 if (cut==0) quot=*up; /* is at bottom of unit */
7030 else /* cut>0 */ { /* it's not at bottom of unit */
7031 #if DECDPUN<=4
7032 quot=QUOT10(*up, cut);
7033 rem=*up-quot*powers[cut];
7034 #else
7035 rem=*up%powers[cut];
7036 quot=*up/powers[cut];
7037 #endif
7038 if (rem!=0) *residue=1;
7040 /* discard digit is now at bottom of quot */
7041 #if DECDPUN<=4
7042 temp=(quot*6554)>>16; /* fast /10 */
7043 /* Vowels algorithm here not a win (9 instructions) */
7044 discard1=quot-X10(temp);
7045 quot=temp;
7046 #else
7047 discard1=quot%10;
7048 quot=quot/10;
7049 #endif
7050 /* here, discard1 is the guard digit, and residue is everything */
7051 /* else [use mapping array to accumulate residue safely] */
7052 *residue+=resmap[discard1];
7053 cut++; /* update cut */
7054 /* here: up -> Unit of the array with bottom digit */
7055 /* cut is the division point for each Unit */
7056 /* quot holds the uncut high-order digits for the current unit */
7057 if (set->digits<=0) { /* special for Quantize/Subnormal :-( */
7058 *dn->lsu=0; /* .. result is 0 */
7059 dn->digits=1; /* .. */
7061 else { /* shift to least needed */
7062 count=set->digits; /* now digits to end up with */
7063 dn->digits=count; /* set the new length */
7064 /* shift-copy the coefficient array to the result number */
7065 for (target=dn->lsu; ; target++) {
7066 *target=(Unit)quot;
7067 count-=(DECDPUN-cut);
7068 if (count<=0) break;
7069 up++;
7070 quot=*up;
7071 #if DECDPUN<=4
7072 quot=QUOT10(quot, cut);
7073 rem=*up-quot*powers[cut];
7074 #else
7075 rem=quot%powers[cut];
7076 quot=quot/powers[cut];
7077 #endif
7078 *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
7079 count-=cut;
7080 if (count<=0) break;
7081 } /* shift-copy loop */
7082 } /* shift to least */
7083 } /* not unit boundary */
7085 if (*residue!=0) *status|=DEC_Inexact; /* record inexactitude */
7086 return;
7087 } /* decSetCoeff */
7089 /* ------------------------------------------------------------------ */
7090 /* decApplyRound -- apply pending rounding to a number */
7091 /* */
7092 /* dn is the number, with space for set->digits digits */
7093 /* set is the context [for size and rounding mode] */
7094 /* residue indicates pending rounding, being any accumulated */
7095 /* guard and sticky information. It may be: */
7096 /* 6-9: rounding digit is >5 */
7097 /* 5: rounding digit is exactly half-way */
7098 /* 1-4: rounding digit is <5 and >0 */
7099 /* 0: the coefficient is exact */
7100 /* -1: as 1, but the hidden digits are subtractive, that */
7101 /* is, of the opposite sign to dn. In this case the */
7102 /* coefficient must be non-0. This case occurs when */
7103 /* subtracting a small number (which can be reduced to */
7104 /* a sticky bit); see decAddOp. */
7105 /* status is the status accumulator, as usual */
7106 /* */
7107 /* This routine applies rounding while keeping the length of the */
7108 /* coefficient constant. The exponent and status are unchanged */
7109 /* except if: */
7110 /* */
7111 /* -- the coefficient was increased and is all nines (in which */
7112 /* case Overflow could occur, and is handled directly here so */
7113 /* the caller does not need to re-test for overflow) */
7114 /* */
7115 /* -- the coefficient was decreased and becomes all nines (in which */
7116 /* case Underflow could occur, and is also handled directly). */
7117 /* */
7118 /* All fields in dn are updated as required. */
7119 /* */
7120 /* ------------------------------------------------------------------ */
7121 static void decApplyRound(decNumber *dn, decContext *set, Int residue,
7122 uInt *status) {
7123 Int bump; /* 1 if coefficient needs to be incremented */
7124 /* -1 if coefficient needs to be decremented */
7126 if (residue==0) return; /* nothing to apply */
7128 bump=0; /* assume a smooth ride */
7130 /* now decide whether, and how, to round, depending on mode */
7131 switch (set->round) {
7132 case DEC_ROUND_05UP: { /* round zero or five up (for reround) */
7133 /* This is the same as DEC_ROUND_DOWN unless there is a */
7134 /* positive residue and the lsd of dn is 0 or 5, in which case */
7135 /* it is bumped; when residue is <0, the number is therefore */
7136 /* bumped down unless the final digit was 1 or 6 (in which */
7137 /* case it is bumped down and then up -- a no-op) */
7138 Int lsd5=*dn->lsu%5; /* get lsd and quintate */
7139 if (residue<0 && lsd5!=1) bump=-1;
7140 else if (residue>0 && lsd5==0) bump=1;
7141 /* [bump==1 could be applied directly; use common path for clarity] */
7142 break;} /* r-05 */
7144 case DEC_ROUND_DOWN: {
7145 /* no change, except if negative residue */
7146 if (residue<0) bump=-1;
7147 break;} /* r-d */
7149 case DEC_ROUND_HALF_DOWN: {
7150 if (residue>5) bump=1;
7151 break;} /* r-h-d */
7153 case DEC_ROUND_HALF_EVEN: {
7154 if (residue>5) bump=1; /* >0.5 goes up */
7155 else if (residue==5) { /* exactly 0.5000... */
7156 /* 0.5 goes up iff [new] lsd is odd */
7157 if (*dn->lsu & 0x01) bump=1;
7159 break;} /* r-h-e */
7161 case DEC_ROUND_HALF_UP: {
7162 if (residue>=5) bump=1;
7163 break;} /* r-h-u */
7165 case DEC_ROUND_UP: {
7166 if (residue>0) bump=1;
7167 break;} /* r-u */
7169 case DEC_ROUND_CEILING: {
7170 /* same as _UP for positive numbers, and as _DOWN for negatives */
7171 /* [negative residue cannot occur on 0] */
7172 if (decNumberIsNegative(dn)) {
7173 if (residue<0) bump=-1;
7175 else {
7176 if (residue>0) bump=1;
7178 break;} /* r-c */
7180 case DEC_ROUND_FLOOR: {
7181 /* same as _UP for negative numbers, and as _DOWN for positive */
7182 /* [negative residue cannot occur on 0] */
7183 if (!decNumberIsNegative(dn)) {
7184 if (residue<0) bump=-1;
7186 else {
7187 if (residue>0) bump=1;
7189 break;} /* r-f */
7191 default: { /* e.g., DEC_ROUND_MAX */
7192 *status|=DEC_Invalid_context;
7193 #if DECTRACE || (DECCHECK && DECVERB)
7194 printf("Unknown rounding mode: %d\n", set->round);
7195 #endif
7196 break;}
7197 } /* switch */
7199 /* now bump the number, up or down, if need be */
7200 if (bump==0) return; /* no action required */
7202 /* Simply use decUnitAddSub unless bumping up and the number is */
7203 /* all nines. In this special case set to 100... explicitly */
7204 /* and adjust the exponent by one (as otherwise could overflow */
7205 /* the array) */
7206 /* Similarly handle all-nines result if bumping down. */
7207 if (bump>0) {
7208 Unit *up; /* work */
7209 uInt count=dn->digits; /* digits to be checked */
7210 for (up=dn->lsu; ; up++) {
7211 if (count<=DECDPUN) {
7212 /* this is the last Unit (the msu) */
7213 if (*up!=powers[count]-1) break; /* not still 9s */
7214 /* here if it, too, is all nines */
7215 *up=(Unit)powers[count-1]; /* here 999 -> 100 etc. */
7216 for (up=up-1; up>=dn->lsu; up--) *up=0; /* others all to 0 */
7217 dn->exponent++; /* and bump exponent */
7218 /* [which, very rarely, could cause Overflow...] */
7219 if ((dn->exponent+dn->digits)>set->emax+1) {
7220 decSetOverflow(dn, set, status);
7222 return; /* done */
7224 /* a full unit to check, with more to come */
7225 if (*up!=DECDPUNMAX) break; /* not still 9s */
7226 count-=DECDPUN;
7227 } /* up */
7228 } /* bump>0 */
7229 else { /* -1 */
7230 /* here checking for a pre-bump of 1000... (leading 1, all */
7231 /* other digits zero) */
7232 Unit *up, *sup; /* work */
7233 uInt count=dn->digits; /* digits to be checked */
7234 for (up=dn->lsu; ; up++) {
7235 if (count<=DECDPUN) {
7236 /* this is the last Unit (the msu) */
7237 if (*up!=powers[count-1]) break; /* not 100.. */
7238 /* here if have the 1000... case */
7239 sup=up; /* save msu pointer */
7240 *up=(Unit)powers[count]-1; /* here 100 in msu -> 999 */
7241 /* others all to all-nines, too */
7242 for (up=up-1; up>=dn->lsu; up--) *up=(Unit)powers[DECDPUN]-1;
7243 dn->exponent--; /* and bump exponent */
7245 /* iff the number was at the subnormal boundary (exponent=etiny) */
7246 /* then the exponent is now out of range, so it will in fact get */
7247 /* clamped to etiny and the final 9 dropped. */
7248 /* printf(">> emin=%d exp=%d sdig=%d\n", set->emin, */
7249 /* dn->exponent, set->digits); */
7250 if (dn->exponent+1==set->emin-set->digits+1) {
7251 if (count==1 && dn->digits==1) *sup=0; /* here 9 -> 0[.9] */
7252 else {
7253 *sup=(Unit)powers[count-1]-1; /* here 999.. in msu -> 99.. */
7254 dn->digits--;
7256 dn->exponent++;
7257 *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
7259 return; /* done */
7262 /* a full unit to check, with more to come */
7263 if (*up!=0) break; /* not still 0s */
7264 count-=DECDPUN;
7265 } /* up */
7267 } /* bump<0 */
7269 /* Actual bump needed. Do it. */
7270 decUnitAddSub(dn->lsu, D2U(dn->digits), uarrone, 1, 0, dn->lsu, bump);
7271 } /* decApplyRound */
7273 #if DECSUBSET
7274 /* ------------------------------------------------------------------ */
7275 /* decFinish -- finish processing a number */
7276 /* */
7277 /* dn is the number */
7278 /* set is the context */
7279 /* residue is the rounding accumulator (as in decApplyRound) */
7280 /* status is the accumulator */
7281 /* */
7282 /* This finishes off the current number by: */
7283 /* 1. If not extended: */
7284 /* a. Converting a zero result to clean '0' */
7285 /* b. Reducing positive exponents to 0, if would fit in digits */
7286 /* 2. Checking for overflow and subnormals (always) */
7287 /* Note this is just Finalize when no subset arithmetic. */
7288 /* All fields are updated as required. */
7289 /* ------------------------------------------------------------------ */
7290 static void decFinish(decNumber *dn, decContext *set, Int *residue,
7291 uInt *status) {
7292 if (!set->extended) {
7293 if ISZERO(dn) { /* value is zero */
7294 dn->exponent=0; /* clean exponent .. */
7295 dn->bits=0; /* .. and sign */
7296 return; /* no error possible */
7298 if (dn->exponent>=0) { /* non-negative exponent */
7299 /* >0; reduce to integer if possible */
7300 if (set->digits >= (dn->exponent+dn->digits)) {
7301 dn->digits=decShiftToMost(dn->lsu, dn->digits, dn->exponent);
7302 dn->exponent=0;
7305 } /* !extended */
7307 decFinalize(dn, set, residue, status);
7308 } /* decFinish */
7309 #endif
7311 /* ------------------------------------------------------------------ */
7312 /* decFinalize -- final check, clamp, and round of a number */
7313 /* */
7314 /* dn is the number */
7315 /* set is the context */
7316 /* residue is the rounding accumulator (as in decApplyRound) */
7317 /* status is the status accumulator */
7318 /* */
7319 /* This finishes off the current number by checking for subnormal */
7320 /* results, applying any pending rounding, checking for overflow, */
7321 /* and applying any clamping. */
7322 /* Underflow and overflow conditions are raised as appropriate. */
7323 /* All fields are updated as required. */
7324 /* ------------------------------------------------------------------ */
7325 static void decFinalize(decNumber *dn, decContext *set, Int *residue,
7326 uInt *status) {
7327 Int shift; /* shift needed if clamping */
7328 Int tinyexp=set->emin-dn->digits+1; /* precalculate subnormal boundary */
7330 /* Must be careful, here, when checking the exponent as the */
7331 /* adjusted exponent could overflow 31 bits [because it may already */
7332 /* be up to twice the expected]. */
7334 /* First test for subnormal. This must be done before any final */
7335 /* round as the result could be rounded to Nmin or 0. */
7336 if (dn->exponent<=tinyexp) { /* prefilter */
7337 Int comp;
7338 decNumber nmin;
7339 /* A very nasty case here is dn == Nmin and residue<0 */
7340 if (dn->exponent<tinyexp) {
7341 /* Go handle subnormals; this will apply round if needed. */
7342 decSetSubnormal(dn, set, residue, status);
7343 return;
7345 /* Equals case: only subnormal if dn=Nmin and negative residue */
7346 decNumberZero(&nmin);
7347 nmin.lsu[0]=1;
7348 nmin.exponent=set->emin;
7349 comp=decCompare(dn, &nmin, 1); /* (signless compare) */
7350 if (comp==BADINT) { /* oops */
7351 *status|=DEC_Insufficient_storage; /* abandon... */
7352 return;
7354 if (*residue<0 && comp==0) { /* neg residue and dn==Nmin */
7355 decApplyRound(dn, set, *residue, status); /* might force down */
7356 decSetSubnormal(dn, set, residue, status);
7357 return;
7361 /* now apply any pending round (this could raise overflow). */
7362 if (*residue!=0) decApplyRound(dn, set, *residue, status);
7364 /* Check for overflow [redundant in the 'rare' case] or clamp */
7365 if (dn->exponent<=set->emax-set->digits+1) return; /* neither needed */
7368 /* here when might have an overflow or clamp to do */
7369 if (dn->exponent>set->emax-dn->digits+1) { /* too big */
7370 decSetOverflow(dn, set, status);
7371 return;
7373 /* here when the result is normal but in clamp range */
7374 if (!set->clamp) return;
7376 /* here when need to apply the IEEE exponent clamp (fold-down) */
7377 shift=dn->exponent-(set->emax-set->digits+1);
7379 /* shift coefficient (if non-zero) */
7380 if (!ISZERO(dn)) {
7381 dn->digits=decShiftToMost(dn->lsu, dn->digits, shift);
7383 dn->exponent-=shift; /* adjust the exponent to match */
7384 *status|=DEC_Clamped; /* and record the dirty deed */
7385 return;
7386 } /* decFinalize */
7388 /* ------------------------------------------------------------------ */
7389 /* decSetOverflow -- set number to proper overflow value */
7390 /* */
7391 /* dn is the number (used for sign [only] and result) */
7392 /* set is the context [used for the rounding mode, etc.] */
7393 /* status contains the current status to be updated */
7394 /* */
7395 /* This sets the sign of a number and sets its value to either */
7396 /* Infinity or the maximum finite value, depending on the sign of */
7397 /* dn and the rounding mode, following IEEE 854 rules. */
7398 /* ------------------------------------------------------------------ */
7399 static void decSetOverflow(decNumber *dn, decContext *set, uInt *status) {
7400 Flag needmax=0; /* result is maximum finite value */
7401 uByte sign=dn->bits&DECNEG; /* clean and save sign bit */
7403 if (ISZERO(dn)) { /* zero does not overflow magnitude */
7404 Int emax=set->emax; /* limit value */
7405 if (set->clamp) emax-=set->digits-1; /* lower if clamping */
7406 if (dn->exponent>emax) { /* clamp required */
7407 dn->exponent=emax;
7408 *status|=DEC_Clamped;
7410 return;
7413 decNumberZero(dn);
7414 switch (set->round) {
7415 case DEC_ROUND_DOWN: {
7416 needmax=1; /* never Infinity */
7417 break;} /* r-d */
7418 case DEC_ROUND_05UP: {
7419 needmax=1; /* never Infinity */
7420 break;} /* r-05 */
7421 case DEC_ROUND_CEILING: {
7422 if (sign) needmax=1; /* Infinity if non-negative */
7423 break;} /* r-c */
7424 case DEC_ROUND_FLOOR: {
7425 if (!sign) needmax=1; /* Infinity if negative */
7426 break;} /* r-f */
7427 default: break; /* Infinity in all other cases */
7429 if (needmax) {
7430 decSetMaxValue(dn, set);
7431 dn->bits=sign; /* set sign */
7433 else dn->bits=sign|DECINF; /* Value is +/-Infinity */
7434 *status|=DEC_Overflow | DEC_Inexact | DEC_Rounded;
7435 } /* decSetOverflow */
7437 /* ------------------------------------------------------------------ */
7438 /* decSetMaxValue -- set number to +Nmax (maximum normal value) */
7439 /* */
7440 /* dn is the number to set */
7441 /* set is the context [used for digits and emax] */
7442 /* */
7443 /* This sets the number to the maximum positive value. */
7444 /* ------------------------------------------------------------------ */
7445 static void decSetMaxValue(decNumber *dn, decContext *set) {
7446 Unit *up; /* work */
7447 Int count=set->digits; /* nines to add */
7448 dn->digits=count;
7449 /* fill in all nines to set maximum value */
7450 for (up=dn->lsu; ; up++) {
7451 if (count>DECDPUN) *up=DECDPUNMAX; /* unit full o'nines */
7452 else { /* this is the msu */
7453 *up=(Unit)(powers[count]-1);
7454 break;
7456 count-=DECDPUN; /* filled those digits */
7457 } /* up */
7458 dn->bits=0; /* + sign */
7459 dn->exponent=set->emax-set->digits+1;
7460 } /* decSetMaxValue */
7462 /* ------------------------------------------------------------------ */
7463 /* decSetSubnormal -- process value whose exponent is <Emin */
7464 /* */
7465 /* dn is the number (used as input as well as output; it may have */
7466 /* an allowed subnormal value, which may need to be rounded) */
7467 /* set is the context [used for the rounding mode] */
7468 /* residue is any pending residue */
7469 /* status contains the current status to be updated */
7470 /* */
7471 /* If subset mode, set result to zero and set Underflow flags. */
7472 /* */
7473 /* Value may be zero with a low exponent; this does not set Subnormal */
7474 /* but the exponent will be clamped to Etiny. */
7475 /* */
7476 /* Otherwise ensure exponent is not out of range, and round as */
7477 /* necessary. Underflow is set if the result is Inexact. */
7478 /* ------------------------------------------------------------------ */
7479 static void decSetSubnormal(decNumber *dn, decContext *set, Int *residue,
7480 uInt *status) {
7481 decContext workset; /* work */
7482 Int etiny, adjust; /* .. */
7484 #if DECSUBSET
7485 /* simple set to zero and 'hard underflow' for subset */
7486 if (!set->extended) {
7487 decNumberZero(dn);
7488 /* always full overflow */
7489 *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
7490 return;
7492 #endif
7494 /* Full arithmetic -- allow subnormals, rounded to minimum exponent */
7495 /* (Etiny) if needed */
7496 etiny=set->emin-(set->digits-1); /* smallest allowed exponent */
7498 if ISZERO(dn) { /* value is zero */
7499 /* residue can never be non-zero here */
7500 #if DECCHECK
7501 if (*residue!=0) {
7502 printf("++ Subnormal 0 residue %ld\n", (LI)*residue);
7503 *status|=DEC_Invalid_operation;
7505 #endif
7506 if (dn->exponent<etiny) { /* clamp required */
7507 dn->exponent=etiny;
7508 *status|=DEC_Clamped;
7510 return;
7513 *status|=DEC_Subnormal; /* have a non-zero subnormal */
7514 adjust=etiny-dn->exponent; /* calculate digits to remove */
7515 if (adjust<=0) { /* not out of range; unrounded */
7516 /* residue can never be non-zero here, except in the Nmin-residue */
7517 /* case (which is a subnormal result), so can take fast-path here */
7518 /* it may already be inexact (from setting the coefficient) */
7519 if (*status&DEC_Inexact) *status|=DEC_Underflow;
7520 return;
7523 /* adjust>0, so need to rescale the result so exponent becomes Etiny */
7524 /* [this code is similar to that in rescale] */
7525 workset=*set; /* clone rounding, etc. */
7526 workset.digits=dn->digits-adjust; /* set requested length */
7527 workset.emin-=adjust; /* and adjust emin to match */
7528 /* [note that the latter can be <1, here, similar to Rescale case] */
7529 decSetCoeff(dn, &workset, dn->lsu, dn->digits, residue, status);
7530 decApplyRound(dn, &workset, *residue, status);
7532 /* Use 754R/854 default rule: Underflow is set iff Inexact */
7533 /* [independent of whether trapped] */
7534 if (*status&DEC_Inexact) *status|=DEC_Underflow;
7536 /* if rounded up a 999s case, exponent will be off by one; adjust */
7537 /* back if so [it will fit, because it was shortened earlier] */
7538 if (dn->exponent>etiny) {
7539 dn->digits=decShiftToMost(dn->lsu, dn->digits, 1);
7540 dn->exponent--; /* (re)adjust the exponent. */
7543 /* if rounded to zero, it is by definition clamped... */
7544 if (ISZERO(dn)) *status|=DEC_Clamped;
7545 } /* decSetSubnormal */
7547 /* ------------------------------------------------------------------ */
7548 /* decCheckMath - check entry conditions for a math function */
7549 /* */
7550 /* This checks the context and the operand */
7551 /* */
7552 /* rhs is the operand to check */
7553 /* set is the context to check */
7554 /* status is unchanged if both are good */
7555 /* */
7556 /* returns non-zero if status is changed, 0 otherwise */
7557 /* */
7558 /* Restrictions enforced: */
7559 /* */
7560 /* digits, emax, and -emin in the context must be less than */
7561 /* DEC_MAX_MATH (999999), and A must be within these bounds if */
7562 /* non-zero. Invalid_operation is set in the status if a */
7563 /* restriction is violated. */
7564 /* ------------------------------------------------------------------ */
7565 static uInt decCheckMath(const decNumber *rhs, decContext *set,
7566 uInt *status) {
7567 uInt save=*status; /* record */
7568 if (set->digits>DEC_MAX_MATH
7569 || set->emax>DEC_MAX_MATH
7570 || -set->emin>DEC_MAX_MATH) *status|=DEC_Invalid_context;
7571 else if ((rhs->digits>DEC_MAX_MATH
7572 || rhs->exponent+rhs->digits>DEC_MAX_MATH+1
7573 || rhs->exponent+rhs->digits<2*(1-DEC_MAX_MATH))
7574 && !ISZERO(rhs)) *status|=DEC_Invalid_operation;
7575 return (*status!=save);
7576 } /* decCheckMath */
7578 /* ------------------------------------------------------------------ */
7579 /* decGetInt -- get integer from a number */
7580 /* */
7581 /* dn is the number [which will not be altered] */
7582 /* */
7583 /* returns one of: */
7584 /* BADINT if there is a non-zero fraction */
7585 /* the converted integer */
7586 /* BIGEVEN if the integer is even and magnitude > 2*10**9 */
7587 /* BIGODD if the integer is odd and magnitude > 2*10**9 */
7588 /* */
7589 /* This checks and gets a whole number from the input decNumber. */
7590 /* The sign can be determined from dn by the caller when BIGEVEN or */
7591 /* BIGODD is returned. */
7592 /* ------------------------------------------------------------------ */
7593 static Int decGetInt(const decNumber *dn) {
7594 Int theInt; /* result accumulator */
7595 const Unit *up; /* work */
7596 Int got; /* digits (real or not) processed */
7597 Int ilength=dn->digits+dn->exponent; /* integral length */
7598 Flag neg=decNumberIsNegative(dn); /* 1 if -ve */
7600 /* The number must be an integer that fits in 10 digits */
7601 /* Assert, here, that 10 is enough for any rescale Etiny */
7602 #if DEC_MAX_EMAX > 999999999
7603 #error GetInt may need updating [for Emax]
7604 #endif
7605 #if DEC_MIN_EMIN < -999999999
7606 #error GetInt may need updating [for Emin]
7607 #endif
7608 if (ISZERO(dn)) return 0; /* zeros are OK, with any exponent */
7610 up=dn->lsu; /* ready for lsu */
7611 theInt=0; /* ready to accumulate */
7612 if (dn->exponent>=0) { /* relatively easy */
7613 /* no fractional part [usual]; allow for positive exponent */
7614 got=dn->exponent;
7616 else { /* -ve exponent; some fractional part to check and discard */
7617 Int count=-dn->exponent; /* digits to discard */
7618 /* spin up whole units until reach the Unit with the unit digit */
7619 for (; count>=DECDPUN; up++) {
7620 if (*up!=0) return BADINT; /* non-zero Unit to discard */
7621 count-=DECDPUN;
7623 if (count==0) got=0; /* [a multiple of DECDPUN] */
7624 else { /* [not multiple of DECDPUN] */
7625 Int rem; /* work */
7626 /* slice off fraction digits and check for non-zero */
7627 #if DECDPUN<=4
7628 theInt=QUOT10(*up, count);
7629 rem=*up-theInt*powers[count];
7630 #else
7631 rem=*up%powers[count]; /* slice off discards */
7632 theInt=*up/powers[count];
7633 #endif
7634 if (rem!=0) return BADINT; /* non-zero fraction */
7635 /* it looks good */
7636 got=DECDPUN-count; /* number of digits so far */
7637 up++; /* ready for next */
7640 /* now it's known there's no fractional part */
7642 /* tricky code now, to accumulate up to 9.3 digits */
7643 if (got==0) {theInt=*up; got+=DECDPUN; up++;} /* ensure lsu is there */
7645 if (ilength<11) {
7646 Int save=theInt;
7647 /* collect any remaining unit(s) */
7648 for (; got<ilength; up++) {
7649 theInt+=*up*powers[got];
7650 got+=DECDPUN;
7652 if (ilength==10) { /* need to check for wrap */
7653 if (theInt/(Int)powers[got-DECDPUN]!=(Int)*(up-1)) ilength=11;
7654 /* [that test also disallows the BADINT result case] */
7655 else if (neg && theInt>1999999997) ilength=11;
7656 else if (!neg && theInt>999999999) ilength=11;
7657 if (ilength==11) theInt=save; /* restore correct low bit */
7661 if (ilength>10) { /* too big */
7662 if (theInt&1) return BIGODD; /* bottom bit 1 */
7663 return BIGEVEN; /* bottom bit 0 */
7666 if (neg) theInt=-theInt; /* apply sign */
7667 return theInt;
7668 } /* decGetInt */
7670 /* ------------------------------------------------------------------ */
7671 /* decDecap -- decapitate the coefficient of a number */
7672 /* */
7673 /* dn is the number to be decapitated */
7674 /* drop is the number of digits to be removed from the left of dn; */
7675 /* this must be <= dn->digits (if equal, the coefficient is */
7676 /* set to 0) */
7677 /* */
7678 /* Returns dn; dn->digits will be <= the initial digits less drop */
7679 /* (after removing drop digits there may be leading zero digits */
7680 /* which will also be removed). Only dn->lsu and dn->digits change. */
7681 /* ------------------------------------------------------------------ */
7682 static decNumber *decDecap(decNumber *dn, Int drop) {
7683 Unit *msu; /* -> target cut point */
7684 Int cut; /* work */
7685 if (drop>=dn->digits) { /* losing the whole thing */
7686 #if DECCHECK
7687 if (drop>dn->digits)
7688 printf("decDecap called with drop>digits [%ld>%ld]\n",
7689 (LI)drop, (LI)dn->digits);
7690 #endif
7691 dn->lsu[0]=0;
7692 dn->digits=1;
7693 return dn;
7695 msu=dn->lsu+D2U(dn->digits-drop)-1; /* -> likely msu */
7696 cut=MSUDIGITS(dn->digits-drop); /* digits to be in use in msu */
7697 if (cut!=DECDPUN) *msu%=powers[cut]; /* clear left digits */
7698 /* that may have left leading zero digits, so do a proper count... */
7699 dn->digits=decGetDigits(dn->lsu, msu-dn->lsu+1);
7700 return dn;
7701 } /* decDecap */
7703 /* ------------------------------------------------------------------ */
7704 /* decBiStr -- compare string with pairwise options */
7705 /* */
7706 /* targ is the string to compare */
7707 /* str1 is one of the strings to compare against (length may be 0) */
7708 /* str2 is the other; it must be the same length as str1 */
7709 /* */
7710 /* returns 1 if strings compare equal, (that is, it is the same */
7711 /* length as str1 and str2, and each character of targ is in either */
7712 /* str1 or str2 in the corresponding position), or 0 otherwise */
7713 /* */
7714 /* This is used for generic caseless compare, including the awkward */
7715 /* case of the Turkish dotted and dotless Is. Use as (for example): */
7716 /* if (decBiStr(test, "mike", "MIKE")) ... */
7717 /* ------------------------------------------------------------------ */
7718 static Flag decBiStr(const char *targ, const char *str1, const char *str2) {
7719 for (;;targ++, str1++, str2++) {
7720 if (*targ!=*str1 && *targ!=*str2) return 0;
7721 /* *targ has a match in one (or both, if terminator) */
7722 if (*targ=='\0') break;
7723 } /* forever */
7724 return 1;
7725 } /* decBiStr */
7727 /* ------------------------------------------------------------------ */
7728 /* decNaNs -- handle NaN operand or operands */
7729 /* */
7730 /* res is the result number */
7731 /* lhs is the first operand */
7732 /* rhs is the second operand, or NULL if none */
7733 /* context is used to limit payload length */
7734 /* status contains the current status */
7735 /* returns res in case convenient */
7736 /* */
7737 /* Called when one or both operands is a NaN, and propagates the */
7738 /* appropriate result to res. When an sNaN is found, it is changed */
7739 /* to a qNaN and Invalid operation is set. */
7740 /* ------------------------------------------------------------------ */
7741 static decNumber * decNaNs(decNumber *res, const decNumber *lhs,
7742 const decNumber *rhs, decContext *set,
7743 uInt *status) {
7744 /* This decision tree ends up with LHS being the source pointer, */
7745 /* and status updated if need be */
7746 if (lhs->bits & DECSNAN)
7747 *status|=DEC_Invalid_operation | DEC_sNaN;
7748 else if (rhs==NULL);
7749 else if (rhs->bits & DECSNAN) {
7750 lhs=rhs;
7751 *status|=DEC_Invalid_operation | DEC_sNaN;
7753 else if (lhs->bits & DECNAN);
7754 else lhs=rhs;
7756 /* propagate the payload */
7757 if (lhs->digits<=set->digits) decNumberCopy(res, lhs); /* easy */
7758 else { /* too long */
7759 const Unit *ul;
7760 Unit *ur, *uresp1;
7761 /* copy safe number of units, then decapitate */
7762 res->bits=lhs->bits; /* need sign etc. */
7763 uresp1=res->lsu+D2U(set->digits);
7764 for (ur=res->lsu, ul=lhs->lsu; ur<uresp1; ur++, ul++) *ur=*ul;
7765 res->digits=D2U(set->digits)*DECDPUN;
7766 /* maybe still too long */
7767 if (res->digits>set->digits) decDecap(res, res->digits-set->digits);
7770 res->bits&=~DECSNAN; /* convert any sNaN to NaN, while */
7771 res->bits|=DECNAN; /* .. preserving sign */
7772 res->exponent=0; /* clean exponent */
7773 /* [coefficient was copied/decapitated] */
7774 return res;
7775 } /* decNaNs */
7777 /* ------------------------------------------------------------------ */
7778 /* decStatus -- apply non-zero status */
7779 /* */
7780 /* dn is the number to set if error */
7781 /* status contains the current status (not yet in context) */
7782 /* set is the context */
7783 /* */
7784 /* If the status is an error status, the number is set to a NaN, */
7785 /* unless the error was an overflow, divide-by-zero, or underflow, */
7786 /* in which case the number will have already been set. */
7787 /* */
7788 /* The context status is then updated with the new status. Note that */
7789 /* this may raise a signal, so control may never return from this */
7790 /* routine (hence resources must be recovered before it is called). */
7791 /* ------------------------------------------------------------------ */
7792 static void decStatus(decNumber *dn, uInt status, decContext *set) {
7793 if (status & DEC_NaNs) { /* error status -> NaN */
7794 /* if cause was an sNaN, clear and propagate [NaN is already set up] */
7795 if (status & DEC_sNaN) status&=~DEC_sNaN;
7796 else {
7797 decNumberZero(dn); /* other error: clean throughout */
7798 dn->bits=DECNAN; /* and make a quiet NaN */
7801 decContextSetStatus(set, status); /* [may not return] */
7802 return;
7803 } /* decStatus */
7805 /* ------------------------------------------------------------------ */
7806 /* decGetDigits -- count digits in a Units array */
7807 /* */
7808 /* uar is the Unit array holding the number (this is often an */
7809 /* accumulator of some sort) */
7810 /* len is the length of the array in units [>=1] */
7811 /* */
7812 /* returns the number of (significant) digits in the array */
7813 /* */
7814 /* All leading zeros are excluded, except the last if the array has */
7815 /* only zero Units. */
7816 /* ------------------------------------------------------------------ */
7817 /* This may be called twice during some operations. */
7818 static Int decGetDigits(Unit *uar, Int len) {
7819 Unit *up=uar+(len-1); /* -> msu */
7820 Int digits=(len-1)*DECDPUN+1; /* possible digits excluding msu */
7821 #if DECDPUN>4
7822 uInt const *pow; /* work */
7823 #endif
7824 /* (at least 1 in final msu) */
7825 #if DECCHECK
7826 if (len<1) printf("decGetDigits called with len<1 [%ld]\n", (LI)len);
7827 #endif
7829 for (; up>=uar; up--) {
7830 if (*up==0) { /* unit is all 0s */
7831 if (digits==1) break; /* a zero has one digit */
7832 digits-=DECDPUN; /* adjust for 0 unit */
7833 continue;}
7834 /* found the first (most significant) non-zero Unit */
7835 #if DECDPUN>1 /* not done yet */
7836 if (*up<10) break; /* is 1-9 */
7837 digits++;
7838 #if DECDPUN>2 /* not done yet */
7839 if (*up<100) break; /* is 10-99 */
7840 digits++;
7841 #if DECDPUN>3 /* not done yet */
7842 if (*up<1000) break; /* is 100-999 */
7843 digits++;
7844 #if DECDPUN>4 /* count the rest ... */
7845 for (pow=&powers[4]; *up>=*pow; pow++) digits++;
7846 #endif
7847 #endif
7848 #endif
7849 #endif
7850 break;
7851 } /* up */
7852 return digits;
7853 } /* decGetDigits */
7855 #if DECTRACE | DECCHECK
7856 /* ------------------------------------------------------------------ */
7857 /* decNumberShow -- display a number [debug aid] */
7858 /* dn is the number to show */
7859 /* */
7860 /* Shows: sign, exponent, coefficient (msu first), digits */
7861 /* or: sign, special-value */
7862 /* ------------------------------------------------------------------ */
7863 /* this is public so other modules can use it */
7864 void decNumberShow(const decNumber *dn) {
7865 const Unit *up; /* work */
7866 uInt u, d; /* .. */
7867 Int cut; /* .. */
7868 char isign='+'; /* main sign */
7869 if (dn==NULL) {
7870 printf("NULL\n");
7871 return;}
7872 if (decNumberIsNegative(dn)) isign='-';
7873 printf(" >> %c ", isign);
7874 if (dn->bits&DECSPECIAL) { /* Is a special value */
7875 if (decNumberIsInfinite(dn)) printf("Infinity");
7876 else { /* a NaN */
7877 if (dn->bits&DECSNAN) printf("sNaN"); /* signalling NaN */
7878 else printf("NaN");
7880 /* if coefficient and exponent are 0, no more to do */
7881 if (dn->exponent==0 && dn->digits==1 && *dn->lsu==0) {
7882 printf("\n");
7883 return;}
7884 /* drop through to report other information */
7885 printf(" ");
7888 /* now carefully display the coefficient */
7889 up=dn->lsu+D2U(dn->digits)-1; /* msu */
7890 printf("%ld", (LI)*up);
7891 for (up=up-1; up>=dn->lsu; up--) {
7892 u=*up;
7893 printf(":");
7894 for (cut=DECDPUN-1; cut>=0; cut--) {
7895 d=u/powers[cut];
7896 u-=d*powers[cut];
7897 printf("%ld", (LI)d);
7898 } /* cut */
7899 } /* up */
7900 if (dn->exponent!=0) {
7901 char esign='+';
7902 if (dn->exponent<0) esign='-';
7903 printf(" E%c%ld", esign, (LI)abs(dn->exponent));
7905 printf(" [%ld]\n", (LI)dn->digits);
7906 } /* decNumberShow */
7907 #endif
7909 #if DECTRACE || DECCHECK
7910 /* ------------------------------------------------------------------ */
7911 /* decDumpAr -- display a unit array [debug/check aid] */
7912 /* name is a single-character tag name */
7913 /* ar is the array to display */
7914 /* len is the length of the array in Units */
7915 /* ------------------------------------------------------------------ */
7916 static void decDumpAr(char name, const Unit *ar, Int len) {
7917 Int i;
7918 const char *spec;
7919 #if DECDPUN==9
7920 spec="%09d ";
7921 #elif DECDPUN==8
7922 spec="%08d ";
7923 #elif DECDPUN==7
7924 spec="%07d ";
7925 #elif DECDPUN==6
7926 spec="%06d ";
7927 #elif DECDPUN==5
7928 spec="%05d ";
7929 #elif DECDPUN==4
7930 spec="%04d ";
7931 #elif DECDPUN==3
7932 spec="%03d ";
7933 #elif DECDPUN==2
7934 spec="%02d ";
7935 #else
7936 spec="%d ";
7937 #endif
7938 printf(" :%c: ", name);
7939 for (i=len-1; i>=0; i--) {
7940 if (i==len-1) printf("%ld ", (LI)ar[i]);
7941 else printf(spec, ar[i]);
7943 printf("\n");
7944 return;}
7945 #endif
7947 #if DECCHECK
7948 /* ------------------------------------------------------------------ */
7949 /* decCheckOperands -- check operand(s) to a routine */
7950 /* res is the result structure (not checked; it will be set to */
7951 /* quiet NaN if error found (and it is not NULL)) */
7952 /* lhs is the first operand (may be DECUNRESU) */
7953 /* rhs is the second (may be DECUNUSED) */
7954 /* set is the context (may be DECUNCONT) */
7955 /* returns 0 if both operands, and the context are clean, or 1 */
7956 /* otherwise (in which case the context will show an error, */
7957 /* unless NULL). Note that res is not cleaned; caller should */
7958 /* handle this so res=NULL case is safe. */
7959 /* The caller is expected to abandon immediately if 1 is returned. */
7960 /* ------------------------------------------------------------------ */
7961 static Flag decCheckOperands(decNumber *res, const decNumber *lhs,
7962 const decNumber *rhs, decContext *set) {
7963 Flag bad=0;
7964 if (set==NULL) { /* oops; hopeless */
7965 #if DECTRACE || DECVERB
7966 printf("Reference to context is NULL.\n");
7967 #endif
7968 bad=1;
7969 return 1;}
7970 else if (set!=DECUNCONT
7971 && (set->digits<1 || set->round>=DEC_ROUND_MAX)) {
7972 bad=1;
7973 #if DECTRACE || DECVERB
7974 printf("Bad context [digits=%ld round=%ld].\n",
7975 (LI)set->digits, (LI)set->round);
7976 #endif
7978 else {
7979 if (res==NULL) {
7980 bad=1;
7981 #if DECTRACE
7982 /* this one not DECVERB as standard tests include NULL */
7983 printf("Reference to result is NULL.\n");
7984 #endif
7986 if (!bad && lhs!=DECUNUSED) bad=(decCheckNumber(lhs));
7987 if (!bad && rhs!=DECUNUSED) bad=(decCheckNumber(rhs));
7989 if (bad) {
7990 if (set!=DECUNCONT) decContextSetStatus(set, DEC_Invalid_operation);
7991 if (res!=DECUNRESU && res!=NULL) {
7992 decNumberZero(res);
7993 res->bits=DECNAN; /* qNaN */
7996 return bad;
7997 } /* decCheckOperands */
7999 /* ------------------------------------------------------------------ */
8000 /* decCheckNumber -- check a number */
8001 /* dn is the number to check */
8002 /* returns 0 if the number is clean, or 1 otherwise */
8003 /* */
8004 /* The number is considered valid if it could be a result from some */
8005 /* operation in some valid context. */
8006 /* ------------------------------------------------------------------ */
8007 static Flag decCheckNumber(const decNumber *dn) {
8008 const Unit *up; /* work */
8009 uInt maxuint; /* .. */
8010 Int ae, d, digits; /* .. */
8011 Int emin, emax; /* .. */
8013 if (dn==NULL) { /* hopeless */
8014 #if DECTRACE
8015 /* this one not DECVERB as standard tests include NULL */
8016 printf("Reference to decNumber is NULL.\n");
8017 #endif
8018 return 1;}
8020 /* check special values */
8021 if (dn->bits & DECSPECIAL) {
8022 if (dn->exponent!=0) {
8023 #if DECTRACE || DECVERB
8024 printf("Exponent %ld (not 0) for a special value [%02x].\n",
8025 (LI)dn->exponent, dn->bits);
8026 #endif
8027 return 1;}
8029 /* 2003.09.08: NaNs may now have coefficients, so next tests Inf only */
8030 if (decNumberIsInfinite(dn)) {
8031 if (dn->digits!=1) {
8032 #if DECTRACE || DECVERB
8033 printf("Digits %ld (not 1) for an infinity.\n", (LI)dn->digits);
8034 #endif
8035 return 1;}
8036 if (*dn->lsu!=0) {
8037 #if DECTRACE || DECVERB
8038 printf("LSU %ld (not 0) for an infinity.\n", (LI)*dn->lsu);
8039 #endif
8040 decDumpAr('I', dn->lsu, D2U(dn->digits));
8041 return 1;}
8042 } /* Inf */
8043 /* 2002.12.26: negative NaNs can now appear through proposed IEEE */
8044 /* concrete formats (decimal64, etc.). */
8045 return 0;
8048 /* check the coefficient */
8049 if (dn->digits<1 || dn->digits>DECNUMMAXP) {
8050 #if DECTRACE || DECVERB
8051 printf("Digits %ld in number.\n", (LI)dn->digits);
8052 #endif
8053 return 1;}
8055 d=dn->digits;
8057 for (up=dn->lsu; d>0; up++) {
8058 if (d>DECDPUN) maxuint=DECDPUNMAX;
8059 else { /* reached the msu */
8060 maxuint=powers[d]-1;
8061 if (dn->digits>1 && *up<powers[d-1]) {
8062 #if DECTRACE || DECVERB
8063 printf("Leading 0 in number.\n");
8064 decNumberShow(dn);
8065 #endif
8066 return 1;}
8068 if (*up>maxuint) {
8069 #if DECTRACE || DECVERB
8070 printf("Bad Unit [%08lx] in %ld-digit number at offset %ld [maxuint %ld].\n",
8071 (LI)*up, (LI)dn->digits, (LI)(up-dn->lsu), (LI)maxuint);
8072 #endif
8073 return 1;}
8074 d-=DECDPUN;
8077 /* check the exponent. Note that input operands can have exponents */
8078 /* which are out of the set->emin/set->emax and set->digits range */
8079 /* (just as they can have more digits than set->digits). */
8080 ae=dn->exponent+dn->digits-1; /* adjusted exponent */
8081 emax=DECNUMMAXE;
8082 emin=DECNUMMINE;
8083 digits=DECNUMMAXP;
8084 if (ae<emin-(digits-1)) {
8085 #if DECTRACE || DECVERB
8086 printf("Adjusted exponent underflow [%ld].\n", (LI)ae);
8087 decNumberShow(dn);
8088 #endif
8089 return 1;}
8090 if (ae>+emax) {
8091 #if DECTRACE || DECVERB
8092 printf("Adjusted exponent overflow [%ld].\n", (LI)ae);
8093 decNumberShow(dn);
8094 #endif
8095 return 1;}
8097 return 0; /* it's OK */
8098 } /* decCheckNumber */
8100 /* ------------------------------------------------------------------ */
8101 /* decCheckInexact -- check a normal finite inexact result has digits */
8102 /* dn is the number to check */
8103 /* set is the context (for status and precision) */
8104 /* sets Invalid operation, etc., if some digits are missing */
8105 /* [this check is not made for DECSUBSET compilation or when */
8106 /* subnormal is not set] */
8107 /* ------------------------------------------------------------------ */
8108 static void decCheckInexact(const decNumber *dn, decContext *set) {
8109 #if !DECSUBSET && DECEXTFLAG
8110 if ((set->status & (DEC_Inexact|DEC_Subnormal))==DEC_Inexact
8111 && (set->digits!=dn->digits) && !(dn->bits & DECSPECIAL)) {
8112 #if DECTRACE || DECVERB
8113 printf("Insufficient digits [%ld] on normal Inexact result.\n",
8114 (LI)dn->digits);
8115 decNumberShow(dn);
8116 #endif
8117 decContextSetStatus(set, DEC_Invalid_operation);
8119 #else
8120 /* next is a noop for quiet compiler */
8121 if (dn!=NULL && dn->digits==0) set->status|=DEC_Invalid_operation;
8122 #endif
8123 return;
8124 } /* decCheckInexact */
8125 #endif
8127 #if DECALLOC
8128 #undef malloc
8129 #undef free
8130 /* ------------------------------------------------------------------ */
8131 /* decMalloc -- accountable allocation routine */
8132 /* n is the number of bytes to allocate */
8133 /* */
8134 /* Semantics is the same as the stdlib malloc routine, but bytes */
8135 /* allocated are accounted for globally, and corruption fences are */
8136 /* added before and after the 'actual' storage. */
8137 /* ------------------------------------------------------------------ */
8138 /* This routine allocates storage with an extra twelve bytes; 8 are */
8139 /* at the start and hold: */
8140 /* 0-3 the original length requested */
8141 /* 4-7 buffer corruption detection fence (DECFENCE, x4) */
8142 /* The 4 bytes at the end also hold a corruption fence (DECFENCE, x4) */
8143 /* ------------------------------------------------------------------ */
8144 static void *decMalloc(size_t n) {
8145 uInt size=n+12; /* true size */
8146 void *alloc; /* -> allocated storage */
8147 uInt *j; /* work */
8148 uByte *b, *b0; /* .. */
8150 alloc=malloc(size); /* -> allocated storage */
8151 if (alloc==NULL) return NULL; /* out of strorage */
8152 b0=(uByte *)alloc; /* as bytes */
8153 decAllocBytes+=n; /* account for storage */
8154 j=(uInt *)alloc; /* -> first four bytes */
8155 *j=n; /* save n */
8156 /* printf(" alloc ++ dAB: %ld (%d)\n", decAllocBytes, n); */
8157 for (b=b0+4; b<b0+8; b++) *b=DECFENCE;
8158 for (b=b0+n+8; b<b0+n+12; b++) *b=DECFENCE;
8159 return b0+8; /* -> play area */
8160 } /* decMalloc */
8162 /* ------------------------------------------------------------------ */
8163 /* decFree -- accountable free routine */
8164 /* alloc is the storage to free */
8165 /* */
8166 /* Semantics is the same as the stdlib malloc routine, except that */
8167 /* the global storage accounting is updated and the fences are */
8168 /* checked to ensure that no routine has written 'out of bounds'. */
8169 /* ------------------------------------------------------------------ */
8170 /* This routine first checks that the fences have not been corrupted. */
8171 /* It then frees the storage using the 'truw' storage address (that */
8172 /* is, offset by 8). */
8173 /* ------------------------------------------------------------------ */
8174 static void decFree(void *alloc) {
8175 uInt *j, n; /* pointer, original length */
8176 uByte *b, *b0; /* work */
8178 if (alloc==NULL) return; /* allowed; it's a nop */
8179 b0=(uByte *)alloc; /* as bytes */
8180 b0-=8; /* -> true start of storage */
8181 j=(uInt *)b0; /* -> first four bytes */
8182 n=*j; /* lift */
8183 for (b=b0+4; b<b0+8; b++) if (*b!=DECFENCE)
8184 printf("=== Corrupt byte [%02x] at offset %d from %ld ===\n", *b,
8185 b-b0-8, (Int)b0);
8186 for (b=b0+n+8; b<b0+n+12; b++) if (*b!=DECFENCE)
8187 printf("=== Corrupt byte [%02x] at offset +%d from %ld, n=%ld ===\n", *b,
8188 b-b0-8, (Int)b0, n);
8189 free(b0); /* drop the storage */
8190 decAllocBytes-=n; /* account for storage */
8191 /* printf(" free -- dAB: %d (%d)\n", decAllocBytes, -n); */
8192 } /* decFree */
8193 #define malloc(a) decMalloc(a)
8194 #define free(a) decFree(a)
8195 #endif