1 // Copyright (C) 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 /* ------------------------------------------------------------------ */
4 /* Decimal Number arithmetic module */
5 /* ------------------------------------------------------------------ */
6 /* Copyright (c) IBM Corporation, 2000-2014. All rights reserved. */
8 /* This software is made available under the terms of the */
9 /* ICU License -- ICU 1.8.1 and later. */
11 /* The description and User's Guide ("The decNumber C Library") for */
12 /* this software is called decNumber.pdf. This document is */
13 /* available, together with arithmetic and format specifications, */
14 /* testcases, and Web links, on the General Decimal Arithmetic page. */
16 /* Please send comments, suggestions, and corrections to the author: */
18 /* Mike Cowlishaw, IBM Fellow */
19 /* IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK */
20 /* ------------------------------------------------------------------ */
22 /* Modified version, for use from within ICU.
23 * Renamed public functions, to avoid an unwanted export of the
24 * standard names from the ICU library.
26 * Use ICU's uprv_malloc() and uprv_free()
28 * Revert comment syntax to plain C
30 * Remove a few compiler warnings.
33 /* This module comprises the routines for arbitrary-precision General */
34 /* Decimal Arithmetic as defined in the specification which may be */
35 /* found on the General Decimal Arithmetic pages. It implements both */
36 /* the full ('extended') arithmetic and the simpler ('subset') */
41 /* 1. This code is ANSI C89 except: */
43 /* a) C99 line comments (double forward slash) are used. (Most C */
44 /* compilers accept these. If yours does not, a simple script */
45 /* can be used to convert them to ANSI C comments.) */
47 /* b) Types from C99 stdint.h are used. If you do not have this */
48 /* header file, see the User's Guide section of the decNumber */
49 /* documentation; this lists the necessary definitions. */
51 /* c) If DECDPUN>4 or DECUSE64=1, the C99 64-bit int64_t and */
52 /* uint64_t types may be used. To avoid these, set DECUSE64=0 */
53 /* and DECDPUN<=4 (see documentation). */
55 /* The code also conforms to C99 restrictions; in particular, */
56 /* strict aliasing rules are observed. */
58 /* 2. The decNumber format which this library uses is optimized for */
59 /* efficient processing of relatively short numbers; in particular */
60 /* it allows the use of fixed sized structures and minimizes copy */
61 /* and move operations. It does, however, support arbitrary */
62 /* precision (up to 999,999,999 digits) and arbitrary exponent */
63 /* range (Emax in the range 0 through 999,999,999 and Emin in the */
64 /* range -999,999,999 through 0). Mathematical functions (for */
65 /* example decNumberExp) as identified below are restricted more */
66 /* tightly: digits, emax, and -emin in the context must be <= */
67 /* DEC_MAX_MATH (999999), and their operand(s) must be within */
70 /* 3. Logical functions are further restricted; their operands must */
71 /* be finite, positive, have an exponent of zero, and all digits */
72 /* must be either 0 or 1. The result will only contain digits */
73 /* which are 0 or 1 (and will have exponent=0 and a sign of 0). */
75 /* 4. Operands to operator functions are never modified unless they */
76 /* are also specified to be the result number (which is always */
77 /* permitted). Other than that case, operands must not overlap. */
79 /* 5. Error handling: the type of the error is ORed into the status */
80 /* flags in the current context (decContext structure). The */
81 /* SIGFPE signal is then raised if the corresponding trap-enabler */
82 /* flag in the decContext is set (is 1). */
84 /* It is the responsibility of the caller to clear the status */
85 /* flags as required. */
87 /* The result of any routine which returns a number will always */
88 /* be a valid number (which may be a special value, such as an */
89 /* Infinity or NaN). */
91 /* 6. The decNumber format is not an exchangeable concrete */
92 /* representation as it comprises fields which may be machine- */
93 /* dependent (packed or unpacked, or special length, for example). */
94 /* Canonical conversions to and from strings are provided; other */
95 /* conversions are available in separate modules. */
97 /* 7. Normally, input operands are assumed to be valid. Set DECCHECK */
98 /* to 1 for extended operand checking (including NULL operands). */
99 /* Results are undefined if a badly-formed structure (or a NULL */
100 /* pointer to a structure) is provided, though with DECCHECK */
101 /* enabled the operator routines are protected against exceptions. */
102 /* (Except if the result pointer is NULL, which is unrecoverable.) */
104 /* However, the routines will never cause exceptions if they are */
105 /* given well-formed operands, even if the value of the operands */
106 /* is inappropriate for the operation and DECCHECK is not set. */
107 /* (Except for SIGFPE, as and where documented.) */
109 /* 8. Subset arithmetic is available only if DECSUBSET is set to 1. */
110 /* ------------------------------------------------------------------ */
111 /* Implementation notes for maintenance of this module: */
113 /* 1. Storage leak protection: Routines which use malloc are not */
114 /* permitted to use return for fastpath or error exits (i.e., */
115 /* they follow strict structured programming conventions). */
116 /* Instead they have a do{}while(0); construct surrounding the */
117 /* code which is protected -- break may be used to exit this. */
118 /* Other routines can safely use the return statement inline. */
120 /* Storage leak accounting can be enabled using DECALLOC. */
122 /* 2. All loops use the for(;;) construct. Any do construct does */
123 /* not loop; it is for allocation protection as just described. */
125 /* 3. Setting status in the context must always be the very last */
126 /* action in a routine, as non-0 status may raise a trap and hence */
127 /* the call to set status may not return (if the handler uses long */
128 /* jump). Therefore all cleanup must be done first. In general, */
129 /* to achieve this status is accumulated and is only applied just */
130 /* before return by calling decContextSetStatus (via decStatus). */
132 /* Routines which allocate storage cannot, in general, use the */
133 /* 'top level' routines which could cause a non-returning */
134 /* transfer of control. The decXxxxOp routines are safe (do not */
135 /* call decStatus even if traps are set in the context) and should */
136 /* be used instead (they are also a little faster). */
138 /* 4. Exponent checking is minimized by allowing the exponent to */
139 /* grow outside its limits during calculations, provided that */
140 /* the decFinalize function is called later. Multiplication and */
141 /* division, and intermediate calculations in exponentiation, */
142 /* require more careful checks because of the risk of 31-bit */
143 /* overflow (the most negative valid exponent is -1999999997, for */
144 /* a 999999999-digit number with adjusted exponent of -999999999). */
146 /* 5. Rounding is deferred until finalization of results, with any */
147 /* 'off to the right' data being represented as a single digit */
148 /* residue (in the range -1 through 9). This avoids any double- */
149 /* rounding when more than one shortening takes place (for */
150 /* example, when a result is subnormal). */
152 /* 6. The digits count is allowed to rise to a multiple of DECDPUN */
153 /* during many operations, so whole Units are handled and exact */
154 /* accounting of digits is not needed. The correct digits value */
155 /* is found by decGetDigits, which accounts for leading zeros. */
156 /* This must be called before any rounding if the number of digits */
157 /* is not known exactly. */
159 /* 7. The multiply-by-reciprocal 'trick' is used for partitioning */
160 /* numbers up to four digits, using appropriate constants. This */
161 /* is not useful for longer numbers because overflow of 32 bits */
162 /* would lead to 4 multiplies, which is almost as expensive as */
163 /* a divide (unless a floating-point or 64-bit multiply is */
164 /* assumed to be available). */
166 /* 8. Unusual abbreviations that may be used in the commentary: */
167 /* lhs -- left hand side (operand, of an operation) */
168 /* lsd -- least significant digit (of coefficient) */
169 /* lsu -- least significant Unit (of coefficient) */
170 /* msd -- most significant digit (of coefficient) */
171 /* msi -- most significant item (in an array) */
172 /* msu -- most significant Unit (of coefficient) */
173 /* rhs -- right hand side (operand, of an operation) */
174 /* +ve -- positive */
175 /* -ve -- negative */
176 /* ** -- raise to the power */
177 /* ------------------------------------------------------------------ */
179 #include <stdlib.h> /* for malloc, free, etc. */
180 /* #include <stdio.h> */ /* for printf [if needed] */
181 #include <string.h> /* for strcpy */
182 #include <ctype.h> /* for lower */
183 #include "cmemory.h" /* for uprv_malloc, etc., in ICU */
184 #include "decNumber.h" /* base number library */
185 #include "decNumberLocal.h" /* decNumber local types, etc. */
189 /* Public lookup table used by the D2U macro */
190 static const uByte d2utable[DECMAXD2U+1]=D2UTABLE;
192 #define DECVERB 1 /* set to 1 for verbose DECCHECK */
193 #define powers DECPOWERS /* old internal name */
195 /* Local constants */
196 #define DIVIDE 0x80 /* Divide operators */
197 #define REMAINDER 0x40 /* .. */
198 #define DIVIDEINT 0x20 /* .. */
199 #define REMNEAR 0x10 /* .. */
200 #define COMPARE 0x01 /* Compare operators */
201 #define COMPMAX 0x02 /* .. */
202 #define COMPMIN 0x03 /* .. */
203 #define COMPTOTAL 0x04 /* .. */
204 #define COMPNAN 0x05 /* .. [NaN processing] */
205 #define COMPSIG 0x06 /* .. [signaling COMPARE] */
206 #define COMPMAXMAG 0x07 /* .. */
207 #define COMPMINMAG 0x08 /* .. */
209 #define DEC_sNaN 0x40000000 /* local status: sNaN signal */
210 #define BADINT (Int)0x80000000 /* most-negative Int; error indicator */
211 /* Next two indicate an integer >= 10**6, and its parity (bottom bit) */
212 #define BIGEVEN (Int)0x80000002
213 #define BIGODD (Int)0x80000003
215 static const Unit uarrone[1]={1}; /* Unit array of 1, used for incrementing */
217 /* ------------------------------------------------------------------ */
218 /* round-for-reround digits */
219 /* ------------------------------------------------------------------ */
221 static const uByte DECSTICKYTAB[10]={1,1,2,3,4,6,6,7,8,9}; /* used if sticky */
224 /* ------------------------------------------------------------------ */
225 /* Powers of ten (powers[n]==10**n, 0<=n<=9) */
226 /* ------------------------------------------------------------------ */
227 static const uInt DECPOWERS[10]={1, 10, 100, 1000, 10000, 100000, 1000000,
228 10000000, 100000000, 1000000000};
231 /* Granularity-dependent code */
233 #define eInt Int /* extended integer */
234 #define ueInt uInt /* unsigned extended integer */
235 /* Constant multipliers for divide-by-power-of five using reciprocal */
236 /* multiply, after removing powers of 2 by shifting, and final shift */
237 /* of 17 [we only need up to **4] */
238 static const uInt multies[]={131073, 26215, 5243, 1049, 210};
239 /* QUOT10 -- macro to return the quotient of unit u divided by 10**n */
240 #define QUOT10(u, n) ((((uInt)(u)>>(n))*multies[n])>>17)
242 /* For DECDPUN>4 non-ANSI-89 64-bit types are needed. */
244 #error decNumber.c: DECUSE64 must be 1 when DECDPUN>4
246 #define eInt Long /* extended integer */
247 #define ueInt uLong /* unsigned extended integer */
251 static decNumber * decAddOp(decNumber *, const decNumber *, const decNumber *,
252 decContext *, uByte, uInt *);
253 static Flag decBiStr(const char *, const char *, const char *);
254 static uInt decCheckMath(const decNumber *, decContext *, uInt *);
255 static void decApplyRound(decNumber *, decContext *, Int, uInt *);
256 static Int decCompare(const decNumber *lhs, const decNumber *rhs, Flag);
257 static decNumber * decCompareOp(decNumber *, const decNumber *,
258 const decNumber *, decContext *,
260 static void decCopyFit(decNumber *, const decNumber *, decContext *,
262 static decNumber * decDecap(decNumber *, Int);
263 static decNumber * decDivideOp(decNumber *, const decNumber *,
264 const decNumber *, decContext *, Flag, uInt *);
265 static decNumber * decExpOp(decNumber *, const decNumber *,
266 decContext *, uInt *);
267 static void decFinalize(decNumber *, decContext *, Int *, uInt *);
268 static Int decGetDigits(Unit *, Int);
269 static Int decGetInt(const decNumber *);
270 static decNumber * decLnOp(decNumber *, const decNumber *,
271 decContext *, uInt *);
272 static decNumber * decMultiplyOp(decNumber *, const decNumber *,
273 const decNumber *, decContext *,
275 static decNumber * decNaNs(decNumber *, const decNumber *,
276 const decNumber *, decContext *, uInt *);
277 static decNumber * decQuantizeOp(decNumber *, const decNumber *,
278 const decNumber *, decContext *, Flag,
280 static void decReverse(Unit *, Unit *);
281 static void decSetCoeff(decNumber *, decContext *, const Unit *,
283 static void decSetMaxValue(decNumber *, decContext *);
284 static void decSetOverflow(decNumber *, decContext *, uInt *);
285 static void decSetSubnormal(decNumber *, decContext *, Int *, uInt *);
286 static Int decShiftToLeast(Unit *, Int, Int);
287 static Int decShiftToMost(Unit *, Int, Int);
288 static void decStatus(decNumber *, uInt, decContext *);
289 static void decToString(const decNumber *, char[], Flag);
290 static decNumber * decTrim(decNumber *, decContext *, Flag, Flag, Int *);
291 static Int decUnitAddSub(const Unit *, Int, const Unit *, Int, Int,
293 static Int decUnitCompare(const Unit *, Int, const Unit *, Int, Int);
296 /* decFinish == decFinalize when no subset arithmetic needed */
297 #define decFinish(a,b,c,d) decFinalize(a,b,c,d)
299 static void decFinish(decNumber *, decContext *, Int *, uInt *);
300 static decNumber * decRoundOperand(const decNumber *, decContext *, uInt *);
304 /* masked special-values bits */
305 #define SPECIALARG (rhs->bits & DECSPECIAL)
306 #define SPECIALARGS ((lhs->bits | rhs->bits) & DECSPECIAL)
309 #define malloc(a) uprv_malloc(a)
310 #define free(a) uprv_free(a)
312 /* Diagnostic macros, etc. */
314 /* Handle malloc/free accounting. If enabled, our accountable routines */
315 /* are used; otherwise the code just goes straight to the system malloc */
316 /* and free routines. */
317 #define malloc(a) decMalloc(a)
318 #define free(a) decFree(a)
319 #define DECFENCE 0x5a /* corruption detector */
320 /* 'Our' malloc and free: */
321 static void *decMalloc(size_t);
322 static void decFree(void *);
323 uInt decAllocBytes=0; /* count of bytes allocated */
324 /* Note that DECALLOC code only checks for storage buffer overflow. */
325 /* To check for memory leaks, the decAllocBytes variable must be */
326 /* checked to be 0 at appropriate times (e.g., after the test */
327 /* harness completes a set of tests). This checking may be unreliable */
328 /* if the testing is done in a multi-thread environment. */
332 /* Optional checking routines. Enabling these means that decNumber */
333 /* and decContext operands to operator routines are checked for */
334 /* correctness. This roughly doubles the execution time of the */
335 /* fastest routines (and adds 600+ bytes), so should not normally be */
336 /* used in 'production'. */
337 /* decCheckInexact is used to check that inexact results have a full */
338 /* complement of digits (where appropriate -- this is not the case */
339 /* for Quantize, for example) */
340 #define DECUNRESU ((decNumber *)(void *)0xffffffff)
341 #define DECUNUSED ((const decNumber *)(void *)0xffffffff)
342 #define DECUNCONT ((decContext *)(void *)(0xffffffff))
343 static Flag decCheckOperands(decNumber *, const decNumber *,
344 const decNumber *, decContext *);
345 static Flag decCheckNumber(const decNumber *);
346 static void decCheckInexact(const decNumber *, decContext *);
349 #if DECTRACE || DECCHECK
350 /* Optional trace/debugging routines (may or may not be used) */
351 void decNumberShow(const decNumber *); /* displays the components of a number */
352 static void decDumpAr(char, const Unit *, Int);
355 /* ================================================================== */
357 /* ================================================================== */
359 /* ------------------------------------------------------------------ */
360 /* from-int32 -- conversion from Int or uInt */
362 /* dn is the decNumber to receive the integer */
363 /* in or uin is the integer to be converted */
366 /* No error is possible. */
367 /* ------------------------------------------------------------------ */
368 U_CAPI decNumber * U_EXPORT2 uprv_decNumberFromInt32(decNumber *dn, Int in) {
371 else { /* negative (possibly BADINT) */
372 if (in==BADINT) unsig=(uInt)1073741824*2; /* special case */
373 else unsig=-in; /* invert */
375 /* in is now positive */
376 uprv_decNumberFromUInt32(dn, unsig);
377 if (in<0) dn->bits=DECNEG; /* sign needed */
379 } /* decNumberFromInt32 */
381 U_CAPI decNumber * U_EXPORT2 uprv_decNumberFromUInt32(decNumber *dn, uInt uin) {
382 Unit *up; /* work pointer */
383 uprv_decNumberZero(dn); /* clean */
384 if (uin==0) return dn; /* [or decGetDigits bad call] */
385 for (up=dn->lsu; uin>0; up++) {
386 *up=(Unit)(uin%(DECDPUNMAX+1));
387 uin=uin/(DECDPUNMAX+1);
389 dn->digits=decGetDigits(dn->lsu, up-dn->lsu);
391 } /* decNumberFromUInt32 */
393 /* ------------------------------------------------------------------ */
394 /* to-int32 -- conversion to Int or uInt */
396 /* dn is the decNumber to convert */
397 /* set is the context for reporting errors */
398 /* returns the converted decNumber, or 0 if Invalid is set */
400 /* Invalid is set if the decNumber does not have exponent==0 or if */
401 /* it is a NaN, Infinite, or out-of-range. */
402 /* ------------------------------------------------------------------ */
403 U_CAPI Int U_EXPORT2 uprv_decNumberToInt32(const decNumber *dn, decContext *set) {
405 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
408 /* special or too many digits, or bad exponent */
409 if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0) ; /* bad */
410 else { /* is a finite integer with 10 or fewer digits */
412 const Unit *up; /* .. */
413 uInt hi=0, lo; /* .. */
414 up=dn->lsu; /* -> lsu */
415 lo=*up; /* get 1 to 9 digits */
416 #if DECDPUN>1 /* split to higher */
421 /* collect remaining Units, if any, into hi */
422 for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
423 /* now low has the lsd, hi the remainder */
424 if (hi>214748364 || (hi==214748364 && lo>7)) { /* out of range? */
425 /* most-negative is a reprieve */
426 if (dn->bits&DECNEG && hi==214748364 && lo==8) return 0x80000000;
427 /* bad -- drop through */
429 else { /* in-range always */
431 if (dn->bits&DECNEG) return -i;
435 uprv_decContextSetStatus(set, DEC_Invalid_operation); /* [may not return] */
437 } /* decNumberToInt32 */
439 U_CAPI uInt U_EXPORT2 uprv_decNumberToUInt32(const decNumber *dn, decContext *set) {
441 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
443 /* special or too many digits, or bad exponent, or negative (<0) */
444 if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0
445 || (dn->bits&DECNEG && !ISZERO(dn))); /* bad */
446 else { /* is a finite integer with 10 or fewer digits */
448 const Unit *up; /* .. */
449 uInt hi=0, lo; /* .. */
450 up=dn->lsu; /* -> lsu */
451 lo=*up; /* get 1 to 9 digits */
452 #if DECDPUN>1 /* split to higher */
457 /* collect remaining Units, if any, into hi */
458 for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
460 /* now low has the lsd, hi the remainder */
461 if (hi>429496729 || (hi==429496729 && lo>5)) ; /* no reprieve possible */
462 else return X10(hi)+lo;
464 uprv_decContextSetStatus(set, DEC_Invalid_operation); /* [may not return] */
466 } /* decNumberToUInt32 */
468 /* ------------------------------------------------------------------ */
469 /* to-scientific-string -- conversion to numeric string */
470 /* to-engineering-string -- conversion to numeric string */
472 /* decNumberToString(dn, string); */
473 /* decNumberToEngString(dn, string); */
475 /* dn is the decNumber to convert */
476 /* string is the string where the result will be laid out */
478 /* string must be at least dn->digits+14 characters long */
480 /* No error is possible, and no status can be set. */
481 /* ------------------------------------------------------------------ */
482 U_CAPI char * U_EXPORT2 uprv_decNumberToString(const decNumber *dn, char *string){
483 decToString(dn, string, 0);
485 } /* DecNumberToString */
487 U_CAPI char * U_EXPORT2 uprv_decNumberToEngString(const decNumber *dn, char *string){
488 decToString(dn, string, 1);
490 } /* DecNumberToEngString */
492 /* ------------------------------------------------------------------ */
493 /* to-number -- conversion from numeric string */
495 /* decNumberFromString -- convert string to decNumber */
496 /* dn -- the number structure to fill */
497 /* chars[] -- the string to convert ('\0' terminated) */
498 /* set -- the context used for processing any error, */
499 /* determining the maximum precision available */
500 /* (set.digits), determining the maximum and minimum */
501 /* exponent (set.emax and set.emin), determining if */
502 /* extended values are allowed, and checking the */
503 /* rounding mode if overflow occurs or rounding is */
506 /* The length of the coefficient and the size of the exponent are */
507 /* checked by this routine, so the correct error (Underflow or */
508 /* Overflow) can be reported or rounding applied, as necessary. */
510 /* If bad syntax is detected, the result will be a quiet NaN. */
511 /* ------------------------------------------------------------------ */
512 U_CAPI decNumber * U_EXPORT2 uprv_decNumberFromString(decNumber *dn, const char chars[],
514 Int exponent=0; /* working exponent [assume 0] */
515 uByte bits=0; /* working flags [assume +ve] */
516 Unit *res; /* where result will be built */
517 Unit resbuff[SD2U(DECBUFFER+9)];/* local buffer in case need temporary */
518 /* [+9 allows for ln() constants] */
519 Unit *allocres=NULL; /* -> allocated result, iff allocated */
520 Int d=0; /* count of digits found in decimal part */
521 const char *dotchar=NULL; /* where dot was found */
522 const char *cfirst=chars; /* -> first character of decimal part */
523 const char *last=NULL; /* -> last digit of decimal part */
524 const char *c; /* work */
527 Int cut, out; /* .. */
529 Int residue; /* rounding residue */
530 uInt status=0; /* error code */
533 if (decCheckOperands(DECUNRESU, DECUNUSED, DECUNUSED, set))
534 return uprv_decNumberZero(dn);
537 do { /* status & malloc protection */
538 for (c=chars;; c++) { /* -> input character */
539 if (*c>='0' && *c<='9') { /* test for Arabic digit */
541 d++; /* count of real digits */
542 continue; /* still in decimal part */
544 if (*c=='.' && dotchar==NULL) { /* first '.' */
545 dotchar=c; /* record offset into decimal part */
546 if (c==cfirst) cfirst++; /* first digit must follow */
548 if (c==chars) { /* first in string... */
549 if (*c=='-') { /* valid - sign */
553 if (*c=='+') { /* valid + sign */
557 /* *c is not a digit, or a valid +, -, or '.' */
561 if (last==NULL) { /* no digits yet */
562 status=DEC_Conversion_syntax;/* assume the worst */
563 if (*c=='\0') break; /* and no more to come... */
565 /* if subset then infinities and NaNs are not allowed */
566 if (!set->extended) break; /* hopeless */
568 /* Infinities and NaNs are possible, here */
569 if (dotchar!=NULL) break; /* .. unless had a dot */
570 uprv_decNumberZero(dn); /* be optimistic */
571 if (decBiStr(c, "infinity", "INFINITY")
572 || decBiStr(c, "inf", "INF")) {
573 dn->bits=bits | DECINF;
574 status=0; /* is OK */
575 break; /* all done */
578 /* 2003.09.10 NaNs are now permitted to have a sign */
579 dn->bits=bits | DECNAN; /* assume simple NaN */
580 if (*c=='s' || *c=='S') { /* looks like an sNaN */
582 dn->bits=bits | DECSNAN;
584 if (*c!='n' && *c!='N') break; /* check caseless "NaN" */
586 if (*c!='a' && *c!='A') break; /* .. */
588 if (*c!='n' && *c!='N') break; /* .. */
590 /* now either nothing, or nnnn payload, expected */
591 /* -> start of integer and skip leading 0s [including plain 0] */
592 for (cfirst=c; *cfirst=='0';) cfirst++;
593 if (*cfirst=='\0') { /* "NaN" or "sNaN", maybe with all 0s */
594 status=0; /* it's good */
597 /* something other than 0s; setup last and d as usual [no dots] */
598 for (c=cfirst;; c++, d++) {
599 if (*c<'0' || *c>'9') break; /* test for Arabic digit */
602 if (*c!='\0') break; /* not all digits */
603 if (d>set->digits-1) {
604 /* [NB: payload in a decNumber can be full length unless */
605 /* clamped, in which case can only be digits-1] */
606 if (set->clamp) break;
607 if (d>set->digits) break;
608 } /* too many digits? */
609 /* good; drop through to convert the integer to coefficient */
610 status=0; /* syntax is OK */
611 bits=dn->bits; /* for copy-back */
614 else if (*c!='\0') { /* more to process... */
615 /* had some digits; exponent is only valid sequence now */
616 Flag nege; /* 1=negative exponent */
617 const char *firstexp; /* -> first significant exponent digit */
618 status=DEC_Conversion_syntax;/* assume the worst */
619 if (*c!='e' && *c!='E') break;
620 /* Found 'e' or 'E' -- now process explicit exponent */
621 /* 1998.07.11: sign no longer required */
623 c++; /* to (possible) sign */
624 if (*c=='-') {nege=1; c++;}
625 else if (*c=='+') c++;
628 for (; *c=='0' && *(c+1)!='\0';) c++; /* strip insignificant zeros */
629 firstexp=c; /* save exponent digit place */
631 if (*c<'0' || *c>'9') break; /* not a digit */
632 exponent=X10(exponent)+(Int)*c-(Int)'0';
634 /* if not now on a '\0', *c must not be a digit */
637 /* (this next test must be after the syntax checks) */
638 /* if it was too long the exponent may have wrapped, so check */
639 /* carefully and set it to a certain overflow if wrap possible */
640 if (c>=firstexp+9+1) {
641 if (c>firstexp+9+1 || *firstexp>'1') exponent=DECNUMMAXE*2;
642 /* [up to 1999999999 is OK, for example 1E-1000000998] */
644 if (nege) exponent=-exponent; /* was negative */
645 status=0; /* is OK */
646 } /* stuff after digits */
648 /* Here when whole string has been inspected; syntax is good */
649 /* cfirst->first digit (never dot), last->last digit (ditto) */
651 /* strip leading zeros/dot [leave final 0 if all 0's] */
652 if (*cfirst=='0') { /* [cfirst has stepped over .] */
653 for (c=cfirst; c<last; c++, cfirst++) {
654 if (*c=='.') continue; /* ignore dots */
655 if (*c!='0') break; /* non-zero found */
656 d--; /* 0 stripped */
659 /* make a rapid exit for easy zeros if !extended */
660 if (*cfirst=='0' && !set->extended) {
661 uprv_decNumberZero(dn); /* clean result */
662 break; /* [could be return] */
665 } /* at least one leading 0 */
667 /* Handle decimal point... */
668 if (dotchar!=NULL && dotchar<last) /* non-trailing '.' found? */
669 exponent-=(last-dotchar); /* adjust exponent */
670 /* [we can now ignore the .] */
672 /* OK, the digits string is good. Assemble in the decNumber, or in */
673 /* a temporary units array if rounding is needed */
674 if (d<=set->digits) res=dn->lsu; /* fits into supplied decNumber */
675 else { /* rounding needed */
676 Int needbytes=D2U(d)*sizeof(Unit);/* bytes needed */
677 res=resbuff; /* assume use local buffer */
678 if (needbytes>(Int)sizeof(resbuff)) { /* too big for local */
679 allocres=(Unit *)malloc(needbytes);
680 if (allocres==NULL) {status|=DEC_Insufficient_storage; break;}
684 /* res now -> number lsu, buffer, or allocated storage for Unit array */
686 /* Place the coefficient into the selected Unit array */
687 /* [this is often 70% of the cost of this function when DECDPUN>1] */
689 out=0; /* accumulator */
690 up=res+D2U(d)-1; /* -> msu */
691 cut=d-(up-res)*DECDPUN; /* digits in top unit */
692 for (c=cfirst;; c++) { /* along the digits */
693 if (*c=='.') continue; /* ignore '.' [don't decrement cut] */
694 out=X10(out)+(Int)*c-(Int)'0';
695 if (c==last) break; /* done [never get to trailing '.'] */
697 if (cut>0) continue; /* more for this unit */
698 *up=(Unit)out; /* write unit */
699 up--; /* prepare for unit below.. */
700 cut=DECDPUN; /* .. */
703 *up=(Unit)out; /* write lsu */
708 for (c=last; c>=cfirst; c--) { /* over each character, from least */
709 if (*c=='.') continue; /* ignore . [don't step up] */
710 *up=(Unit)((Int)*c-(Int)'0');
716 dn->exponent=exponent;
719 /* if not in number (too long) shorten into the number */
722 decSetCoeff(dn, set, res, d, &residue, &status);
723 /* always check for overflow or subnormal and round as needed */
724 decFinalize(dn, set, &residue, &status);
726 else { /* no rounding, but may still have overflow or subnormal */
727 /* [these tests are just for performance; finalize repeats them] */
728 if ((dn->exponent-1<set->emin-dn->digits)
729 || (dn->exponent-1>set->emax-set->digits)) {
731 decFinalize(dn, set, &residue, &status);
734 /* decNumberShow(dn); */
735 } while(0); /* [for break] */
737 if (allocres!=NULL) free(allocres); /* drop any storage used */
738 if (status!=0) decStatus(dn, status, set);
740 } /* decNumberFromString */
742 /* ================================================================== */
744 /* ================================================================== */
746 /* ------------------------------------------------------------------ */
747 /* decNumberAbs -- absolute value operator */
749 /* This computes C = abs(A) */
751 /* res is C, the result. C may be A */
753 /* set is the context */
755 /* See also decNumberCopyAbs for a quiet bitwise version of this. */
756 /* C must have space for set->digits digits. */
757 /* ------------------------------------------------------------------ */
758 /* This has the same effect as decNumberPlus unless A is negative, */
759 /* in which case it has the same effect as decNumberMinus. */
760 /* ------------------------------------------------------------------ */
761 U_CAPI decNumber * U_EXPORT2 uprv_decNumberAbs(decNumber *res, const decNumber *rhs,
763 decNumber dzero; /* for 0 */
764 uInt status=0; /* accumulator */
767 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
770 uprv_decNumberZero(&dzero); /* set 0 */
771 dzero.exponent=rhs->exponent; /* [no coefficient expansion] */
772 decAddOp(res, &dzero, rhs, set, (uByte)(rhs->bits & DECNEG), &status);
773 if (status!=0) decStatus(res, status, set);
775 decCheckInexact(res, set);
780 /* ------------------------------------------------------------------ */
781 /* decNumberAdd -- add two Numbers */
783 /* This computes C = A + B */
785 /* res is C, the result. C may be A and/or B (e.g., X=X+X) */
788 /* set is the context */
790 /* C must have space for set->digits digits. */
791 /* ------------------------------------------------------------------ */
792 /* This just calls the routine shared with Subtract */
793 U_CAPI decNumber * U_EXPORT2 uprv_decNumberAdd(decNumber *res, const decNumber *lhs,
794 const decNumber *rhs, decContext *set) {
795 uInt status=0; /* accumulator */
796 decAddOp(res, lhs, rhs, set, 0, &status);
797 if (status!=0) decStatus(res, status, set);
799 decCheckInexact(res, set);
804 /* ------------------------------------------------------------------ */
805 /* decNumberAnd -- AND two Numbers, digitwise */
807 /* This computes C = A & B */
809 /* res is C, the result. C may be A and/or B (e.g., X=X&X) */
812 /* set is the context (used for result length and error report) */
814 /* C must have space for set->digits digits. */
816 /* Logical function restrictions apply (see above); a NaN is */
817 /* returned with Invalid_operation if a restriction is violated. */
818 /* ------------------------------------------------------------------ */
819 U_CAPI decNumber * U_EXPORT2 uprv_decNumberAnd(decNumber *res, const decNumber *lhs,
820 const decNumber *rhs, decContext *set) {
821 const Unit *ua, *ub; /* -> operands */
822 const Unit *msua, *msub; /* -> operand msus */
823 Unit *uc, *msuc; /* -> result and its msu */
824 Int msudigs; /* digits in res msu */
826 if (decCheckOperands(res, lhs, rhs, set)) return res;
829 if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
830 || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
831 decStatus(res, DEC_Invalid_operation, set);
835 /* operands are valid */
836 ua=lhs->lsu; /* bottom-up */
837 ub=rhs->lsu; /* .. */
838 uc=res->lsu; /* .. */
839 msua=ua+D2U(lhs->digits)-1; /* -> msu of lhs */
840 msub=ub+D2U(rhs->digits)-1; /* -> msu of rhs */
841 msuc=uc+D2U(set->digits)-1; /* -> msu of result */
842 msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */
843 for (; uc<=msuc; ua++, ub++, uc++) { /* Unit loop */
844 Unit a, b; /* extract units */
849 *uc=0; /* can now write back */
850 if (a|b) { /* maybe 1 bits to examine */
852 *uc=0; /* can now write back */
853 /* This loop could be unrolled and/or use BIN2BCD tables */
854 for (i=0; i<DECDPUN; i++) {
855 if (a&b&1) *uc=*uc+(Unit)powers[i]; /* effect AND */
861 decStatus(res, DEC_Invalid_operation, set);
864 if (uc==msuc && i==msudigs-1) break; /* just did final digit */
868 /* [here uc-1 is the msu of the result] */
869 res->digits=decGetDigits(res->lsu, uc-res->lsu);
870 res->exponent=0; /* integer */
871 res->bits=0; /* sign=0 */
872 return res; /* [no status to set] */
875 /* ------------------------------------------------------------------ */
876 /* decNumberCompare -- compare two Numbers */
878 /* This computes C = A ? B */
880 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
883 /* set is the context */
885 /* C must have space for one digit (or NaN). */
886 /* ------------------------------------------------------------------ */
887 U_CAPI decNumber * U_EXPORT2 uprv_decNumberCompare(decNumber *res, const decNumber *lhs,
888 const decNumber *rhs, decContext *set) {
889 uInt status=0; /* accumulator */
890 decCompareOp(res, lhs, rhs, set, COMPARE, &status);
891 if (status!=0) decStatus(res, status, set);
893 } /* decNumberCompare */
895 /* ------------------------------------------------------------------ */
896 /* decNumberCompareSignal -- compare, signalling on all NaNs */
898 /* This computes C = A ? B */
900 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
903 /* set is the context */
905 /* C must have space for one digit (or NaN). */
906 /* ------------------------------------------------------------------ */
907 U_CAPI decNumber * U_EXPORT2 uprv_decNumberCompareSignal(decNumber *res, const decNumber *lhs,
908 const decNumber *rhs, decContext *set) {
909 uInt status=0; /* accumulator */
910 decCompareOp(res, lhs, rhs, set, COMPSIG, &status);
911 if (status!=0) decStatus(res, status, set);
913 } /* decNumberCompareSignal */
915 /* ------------------------------------------------------------------ */
916 /* decNumberCompareTotal -- compare two Numbers, using total ordering */
918 /* This computes C = A ? B, under total ordering */
920 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
923 /* set is the context */
925 /* C must have space for one digit; the result will always be one of */
927 /* ------------------------------------------------------------------ */
928 U_CAPI decNumber * U_EXPORT2 uprv_decNumberCompareTotal(decNumber *res, const decNumber *lhs,
929 const decNumber *rhs, decContext *set) {
930 uInt status=0; /* accumulator */
931 decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
932 if (status!=0) decStatus(res, status, set);
934 } /* decNumberCompareTotal */
936 /* ------------------------------------------------------------------ */
937 /* decNumberCompareTotalMag -- compare, total ordering of magnitudes */
939 /* This computes C = |A| ? |B|, under total ordering */
941 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
944 /* set is the context */
946 /* C must have space for one digit; the result will always be one of */
948 /* ------------------------------------------------------------------ */
949 U_CAPI decNumber * U_EXPORT2 uprv_decNumberCompareTotalMag(decNumber *res, const decNumber *lhs,
950 const decNumber *rhs, decContext *set) {
951 uInt status=0; /* accumulator */
952 uInt needbytes; /* for space calculations */
953 decNumber bufa[D2N(DECBUFFER+1)];/* +1 in case DECBUFFER=0 */
954 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
955 decNumber bufb[D2N(DECBUFFER+1)];
956 decNumber *allocbufb=NULL; /* -> allocated bufb, iff allocated */
957 decNumber *a, *b; /* temporary pointers */
960 if (decCheckOperands(res, lhs, rhs, set)) return res;
963 do { /* protect allocated storage */
964 /* if either is negative, take a copy and absolute */
965 if (decNumberIsNegative(lhs)) { /* lhs<0 */
967 needbytes=sizeof(decNumber)+(D2U(lhs->digits)-1)*sizeof(Unit);
968 if (needbytes>sizeof(bufa)) { /* need malloc space */
969 allocbufa=(decNumber *)malloc(needbytes);
970 if (allocbufa==NULL) { /* hopeless -- abandon */
971 status|=DEC_Insufficient_storage;
973 a=allocbufa; /* use the allocated space */
975 uprv_decNumberCopy(a, lhs); /* copy content */
976 a->bits&=~DECNEG; /* .. and clear the sign */
977 lhs=a; /* use copy from here on */
979 if (decNumberIsNegative(rhs)) { /* rhs<0 */
981 needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
982 if (needbytes>sizeof(bufb)) { /* need malloc space */
983 allocbufb=(decNumber *)malloc(needbytes);
984 if (allocbufb==NULL) { /* hopeless -- abandon */
985 status|=DEC_Insufficient_storage;
987 b=allocbufb; /* use the allocated space */
989 uprv_decNumberCopy(b, rhs); /* copy content */
990 b->bits&=~DECNEG; /* .. and clear the sign */
991 rhs=b; /* use copy from here on */
993 decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
994 } while(0); /* end protected */
996 if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */
997 if (allocbufb!=NULL) free(allocbufb); /* .. */
998 if (status!=0) decStatus(res, status, set);
1000 } /* decNumberCompareTotalMag */
1002 /* ------------------------------------------------------------------ */
1003 /* decNumberDivide -- divide one number by another */
1005 /* This computes C = A / B */
1007 /* res is C, the result. C may be A and/or B (e.g., X=X/X) */
1010 /* set is the context */
1012 /* C must have space for set->digits digits. */
1013 /* ------------------------------------------------------------------ */
1014 U_CAPI decNumber * U_EXPORT2 uprv_decNumberDivide(decNumber *res, const decNumber *lhs,
1015 const decNumber *rhs, decContext *set) {
1016 uInt status=0; /* accumulator */
1017 decDivideOp(res, lhs, rhs, set, DIVIDE, &status);
1018 if (status!=0) decStatus(res, status, set);
1020 decCheckInexact(res, set);
1023 } /* decNumberDivide */
1025 /* ------------------------------------------------------------------ */
1026 /* decNumberDivideInteger -- divide and return integer quotient */
1028 /* This computes C = A # B, where # is the integer divide operator */
1030 /* res is C, the result. C may be A and/or B (e.g., X=X#X) */
1033 /* set is the context */
1035 /* C must have space for set->digits digits. */
1036 /* ------------------------------------------------------------------ */
1037 U_CAPI decNumber * U_EXPORT2 uprv_decNumberDivideInteger(decNumber *res, const decNumber *lhs,
1038 const decNumber *rhs, decContext *set) {
1039 uInt status=0; /* accumulator */
1040 decDivideOp(res, lhs, rhs, set, DIVIDEINT, &status);
1041 if (status!=0) decStatus(res, status, set);
1043 } /* decNumberDivideInteger */
1045 /* ------------------------------------------------------------------ */
1046 /* decNumberExp -- exponentiation */
1048 /* This computes C = exp(A) */
1050 /* res is C, the result. C may be A */
1052 /* set is the context; note that rounding mode has no effect */
1054 /* C must have space for set->digits digits. */
1056 /* Mathematical function restrictions apply (see above); a NaN is */
1057 /* returned with Invalid_operation if a restriction is violated. */
1059 /* Finite results will always be full precision and Inexact, except */
1060 /* when A is a zero or -Infinity (giving 1 or 0 respectively). */
1062 /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */
1063 /* almost always be correctly rounded, but may be up to 1 ulp in */
1064 /* error in rare cases. */
1065 /* ------------------------------------------------------------------ */
1066 /* This is a wrapper for decExpOp which can handle the slightly wider */
1067 /* (double) range needed by Ln (which has to be able to calculate */
1068 /* exp(-a) where a can be the tiniest number (Ntiny). */
1069 /* ------------------------------------------------------------------ */
1070 U_CAPI decNumber * U_EXPORT2 uprv_decNumberExp(decNumber *res, const decNumber *rhs,
1072 uInt status=0; /* accumulator */
1074 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */
1078 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1081 /* Check restrictions; these restrictions ensure that if h=8 (see */
1082 /* decExpOp) then the result will either overflow or underflow to 0. */
1083 /* Other math functions restrict the input range, too, for inverses. */
1084 /* If not violated then carry out the operation. */
1085 if (!decCheckMath(rhs, set, &status)) do { /* protect allocation */
1087 if (!set->extended) {
1088 /* reduce operand and set lostDigits status, as needed */
1089 if (rhs->digits>set->digits) {
1090 allocrhs=decRoundOperand(rhs, set, &status);
1091 if (allocrhs==NULL) break;
1096 decExpOp(res, rhs, set, &status);
1097 } while(0); /* end protected */
1100 if (allocrhs !=NULL) free(allocrhs); /* drop any storage used */
1102 /* apply significant status */
1103 if (status!=0) decStatus(res, status, set);
1105 decCheckInexact(res, set);
1108 } /* decNumberExp */
1110 /* ------------------------------------------------------------------ */
1111 /* decNumberFMA -- fused multiply add */
1113 /* This computes D = (A * B) + C with only one rounding */
1115 /* res is D, the result. D may be A or B or C (e.g., X=FMA(X,X,X)) */
1118 /* fhs is C [far hand side] */
1119 /* set is the context */
1121 /* Mathematical function restrictions apply (see above); a NaN is */
1122 /* returned with Invalid_operation if a restriction is violated. */
1124 /* C must have space for set->digits digits. */
1125 /* ------------------------------------------------------------------ */
1126 U_CAPI decNumber * U_EXPORT2 uprv_decNumberFMA(decNumber *res, const decNumber *lhs,
1127 const decNumber *rhs, const decNumber *fhs,
1129 uInt status=0; /* accumulator */
1130 decContext dcmul; /* context for the multiplication */
1131 uInt needbytes; /* for space calculations */
1132 decNumber bufa[D2N(DECBUFFER*2+1)];
1133 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
1134 decNumber *acc; /* accumulator pointer */
1135 decNumber dzero; /* work */
1138 if (decCheckOperands(res, lhs, rhs, set)) return res;
1139 if (decCheckOperands(res, fhs, DECUNUSED, set)) return res;
1142 do { /* protect allocated storage */
1144 if (!set->extended) { /* [undefined if subset] */
1145 status|=DEC_Invalid_operation;
1148 /* Check math restrictions [these ensure no overflow or underflow] */
1149 if ((!decNumberIsSpecial(lhs) && decCheckMath(lhs, set, &status))
1150 || (!decNumberIsSpecial(rhs) && decCheckMath(rhs, set, &status))
1151 || (!decNumberIsSpecial(fhs) && decCheckMath(fhs, set, &status))) break;
1152 /* set up context for multiply */
1154 dcmul.digits=lhs->digits+rhs->digits; /* just enough */
1155 /* [The above may be an over-estimate for subset arithmetic, but that's OK] */
1156 dcmul.emax=DEC_MAX_EMAX; /* effectively unbounded .. */
1157 dcmul.emin=DEC_MIN_EMIN; /* [thanks to Math restrictions] */
1158 /* set up decNumber space to receive the result of the multiply */
1159 acc=bufa; /* may fit */
1160 needbytes=sizeof(decNumber)+(D2U(dcmul.digits)-1)*sizeof(Unit);
1161 if (needbytes>sizeof(bufa)) { /* need malloc space */
1162 allocbufa=(decNumber *)malloc(needbytes);
1163 if (allocbufa==NULL) { /* hopeless -- abandon */
1164 status|=DEC_Insufficient_storage;
1166 acc=allocbufa; /* use the allocated space */
1168 /* multiply with extended range and necessary precision */
1169 /*printf("emin=%ld\n", dcmul.emin); */
1170 decMultiplyOp(acc, lhs, rhs, &dcmul, &status);
1171 /* Only Invalid operation (from sNaN or Inf * 0) is possible in */
1172 /* status; if either is seen than ignore fhs (in case it is */
1173 /* another sNaN) and set acc to NaN unless we had an sNaN */
1174 /* [decMultiplyOp leaves that to caller] */
1175 /* Note sNaN has to go through addOp to shorten payload if */
1177 if ((status&DEC_Invalid_operation)!=0) {
1178 if (!(status&DEC_sNaN)) { /* but be true invalid */
1179 uprv_decNumberZero(res); /* acc not yet set */
1183 uprv_decNumberZero(&dzero); /* make 0 (any non-NaN would do) */
1184 fhs=&dzero; /* use that */
1187 else { /* multiply was OK */
1188 if (status!=0) printf("Status=%08lx after FMA multiply\n", (LI)status);
1191 /* add the third operand and result -> res, and all is done */
1192 decAddOp(res, acc, fhs, set, 0, &status);
1193 } while(0); /* end protected */
1195 if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */
1196 if (status!=0) decStatus(res, status, set);
1198 decCheckInexact(res, set);
1201 } /* decNumberFMA */
1203 /* ------------------------------------------------------------------ */
1204 /* decNumberInvert -- invert a Number, digitwise */
1206 /* This computes C = ~A */
1208 /* res is C, the result. C may be A (e.g., X=~X) */
1210 /* set is the context (used for result length and error report) */
1212 /* C must have space for set->digits digits. */
1214 /* Logical function restrictions apply (see above); a NaN is */
1215 /* returned with Invalid_operation if a restriction is violated. */
1216 /* ------------------------------------------------------------------ */
1217 U_CAPI decNumber * U_EXPORT2 uprv_decNumberInvert(decNumber *res, const decNumber *rhs,
1219 const Unit *ua, *msua; /* -> operand and its msu */
1220 Unit *uc, *msuc; /* -> result and its msu */
1221 Int msudigs; /* digits in res msu */
1223 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1226 if (rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
1227 decStatus(res, DEC_Invalid_operation, set);
1230 /* operand is valid */
1231 ua=rhs->lsu; /* bottom-up */
1232 uc=res->lsu; /* .. */
1233 msua=ua+D2U(rhs->digits)-1; /* -> msu of rhs */
1234 msuc=uc+D2U(set->digits)-1; /* -> msu of result */
1235 msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */
1236 for (; uc<=msuc; ua++, uc++) { /* Unit loop */
1237 Unit a; /* extract unit */
1238 Int i, j; /* work */
1241 *uc=0; /* can now write back */
1242 /* always need to examine all bits in rhs */
1243 /* This loop could be unrolled and/or use BIN2BCD tables */
1244 for (i=0; i<DECDPUN; i++) {
1245 if ((~a)&1) *uc=*uc+(Unit)powers[i]; /* effect INVERT */
1249 decStatus(res, DEC_Invalid_operation, set);
1252 if (uc==msuc && i==msudigs-1) break; /* just did final digit */
1255 /* [here uc-1 is the msu of the result] */
1256 res->digits=decGetDigits(res->lsu, uc-res->lsu);
1257 res->exponent=0; /* integer */
1258 res->bits=0; /* sign=0 */
1259 return res; /* [no status to set] */
1260 } /* decNumberInvert */
1262 /* ------------------------------------------------------------------ */
1263 /* decNumberLn -- natural logarithm */
1265 /* This computes C = ln(A) */
1267 /* res is C, the result. C may be A */
1269 /* set is the context; note that rounding mode has no effect */
1271 /* C must have space for set->digits digits. */
1273 /* Notable cases: */
1274 /* A<0 -> Invalid */
1275 /* A=0 -> -Infinity (Exact) */
1276 /* A=+Infinity -> +Infinity (Exact) */
1277 /* A=1 exactly -> 0 (Exact) */
1279 /* Mathematical function restrictions apply (see above); a NaN is */
1280 /* returned with Invalid_operation if a restriction is violated. */
1282 /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */
1283 /* almost always be correctly rounded, but may be up to 1 ulp in */
1284 /* error in rare cases. */
1285 /* ------------------------------------------------------------------ */
1286 /* This is a wrapper for decLnOp which can handle the slightly wider */
1287 /* (+11) range needed by Ln, Log10, etc. (which may have to be able */
1288 /* to calculate at p+e+2). */
1289 /* ------------------------------------------------------------------ */
1290 U_CAPI decNumber * U_EXPORT2 uprv_decNumberLn(decNumber *res, const decNumber *rhs,
1292 uInt status=0; /* accumulator */
1294 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */
1298 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1301 /* Check restrictions; this is a math function; if not violated */
1302 /* then carry out the operation. */
1303 if (!decCheckMath(rhs, set, &status)) do { /* protect allocation */
1305 if (!set->extended) {
1306 /* reduce operand and set lostDigits status, as needed */
1307 if (rhs->digits>set->digits) {
1308 allocrhs=decRoundOperand(rhs, set, &status);
1309 if (allocrhs==NULL) break;
1312 /* special check in subset for rhs=0 */
1313 if (ISZERO(rhs)) { /* +/- zeros -> error */
1314 status|=DEC_Invalid_operation;
1318 decLnOp(res, rhs, set, &status);
1319 } while(0); /* end protected */
1322 if (allocrhs !=NULL) free(allocrhs); /* drop any storage used */
1324 /* apply significant status */
1325 if (status!=0) decStatus(res, status, set);
1327 decCheckInexact(res, set);
1332 /* ------------------------------------------------------------------ */
1333 /* decNumberLogB - get adjusted exponent, by 754 rules */
1335 /* This computes C = adjustedexponent(A) */
1337 /* res is C, the result. C may be A */
1339 /* set is the context, used only for digits and status */
1341 /* C must have space for 10 digits (A might have 10**9 digits and */
1342 /* an exponent of +999999999, or one digit and an exponent of */
1345 /* This returns the adjusted exponent of A after (in theory) padding */
1346 /* with zeros on the right to set->digits digits while keeping the */
1347 /* same value. The exponent is not limited by emin/emax. */
1349 /* Notable cases: */
1350 /* A<0 -> Use |A| */
1351 /* A=0 -> -Infinity (Division by zero) */
1352 /* A=Infinite -> +Infinity (Exact) */
1353 /* A=1 exactly -> 0 (Exact) */
1354 /* NaNs are propagated as usual */
1355 /* ------------------------------------------------------------------ */
1356 U_CAPI decNumber * U_EXPORT2 uprv_decNumberLogB(decNumber *res, const decNumber *rhs,
1358 uInt status=0; /* accumulator */
1361 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1364 /* NaNs as usual; Infinities return +Infinity; 0->oops */
1365 if (decNumberIsNaN(rhs)) decNaNs(res, rhs, NULL, set, &status);
1366 else if (decNumberIsInfinite(rhs)) uprv_decNumberCopyAbs(res, rhs);
1367 else if (decNumberIsZero(rhs)) {
1368 uprv_decNumberZero(res); /* prepare for Infinity */
1369 res->bits=DECNEG|DECINF; /* -Infinity */
1370 status|=DEC_Division_by_zero; /* as per 754 */
1372 else { /* finite non-zero */
1373 Int ae=rhs->exponent+rhs->digits-1; /* adjusted exponent */
1374 uprv_decNumberFromInt32(res, ae); /* lay it out */
1377 if (status!=0) decStatus(res, status, set);
1379 } /* decNumberLogB */
1381 /* ------------------------------------------------------------------ */
1382 /* decNumberLog10 -- logarithm in base 10 */
1384 /* This computes C = log10(A) */
1386 /* res is C, the result. C may be A */
1388 /* set is the context; note that rounding mode has no effect */
1390 /* C must have space for set->digits digits. */
1392 /* Notable cases: */
1393 /* A<0 -> Invalid */
1394 /* A=0 -> -Infinity (Exact) */
1395 /* A=+Infinity -> +Infinity (Exact) */
1396 /* A=10**n (if n is an integer) -> n (Exact) */
1398 /* Mathematical function restrictions apply (see above); a NaN is */
1399 /* returned with Invalid_operation if a restriction is violated. */
1401 /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */
1402 /* almost always be correctly rounded, but may be up to 1 ulp in */
1403 /* error in rare cases. */
1404 /* ------------------------------------------------------------------ */
1405 /* This calculates ln(A)/ln(10) using appropriate precision. For */
1406 /* ln(A) this is the max(p, rhs->digits + t) + 3, where p is the */
1407 /* requested digits and t is the number of digits in the exponent */
1408 /* (maximum 6). For ln(10) it is p + 3; this is often handled by the */
1409 /* fastpath in decLnOp. The final division is done to the requested */
1411 /* ------------------------------------------------------------------ */
1412 #if defined(__clang__) || U_GCC_MAJOR_MINOR >= 406
1413 #pragma GCC diagnostic push
1414 #pragma GCC diagnostic ignored "-Warray-bounds"
1416 U_CAPI decNumber * U_EXPORT2 uprv_decNumberLog10(decNumber *res, const decNumber *rhs,
1418 uInt status=0, ignore=0; /* status accumulators */
1419 uInt needbytes; /* for space calculations */
1420 Int p; /* working precision */
1421 Int t; /* digits in exponent of A */
1423 /* buffers for a and b working decimals */
1424 /* (adjustment calculator, same size) */
1425 decNumber bufa[D2N(DECBUFFER+2)];
1426 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
1427 decNumber *a=bufa; /* temporary a */
1428 decNumber bufb[D2N(DECBUFFER+2)];
1429 decNumber *allocbufb=NULL; /* -> allocated bufb, iff allocated */
1430 decNumber *b=bufb; /* temporary b */
1431 decNumber bufw[D2N(10)]; /* working 2-10 digit number */
1432 decNumber *w=bufw; /* .. */
1434 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */
1437 decContext aset; /* working context */
1440 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1443 /* Check restrictions; this is a math function; if not violated */
1444 /* then carry out the operation. */
1445 if (!decCheckMath(rhs, set, &status)) do { /* protect malloc */
1447 if (!set->extended) {
1448 /* reduce operand and set lostDigits status, as needed */
1449 if (rhs->digits>set->digits) {
1450 allocrhs=decRoundOperand(rhs, set, &status);
1451 if (allocrhs==NULL) break;
1454 /* special check in subset for rhs=0 */
1455 if (ISZERO(rhs)) { /* +/- zeros -> error */
1456 status|=DEC_Invalid_operation;
1461 uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64); /* clean context */
1463 /* handle exact powers of 10; only check if +ve finite */
1464 if (!(rhs->bits&(DECNEG|DECSPECIAL)) && !ISZERO(rhs)) {
1465 Int residue=0; /* (no residue) */
1466 uInt copystat=0; /* clean status */
1468 /* round to a single digit... */
1470 decCopyFit(w, rhs, &aset, &residue, ©stat); /* copy & shorten */
1471 /* if exact and the digit is 1, rhs is a power of 10 */
1472 if (!(copystat&DEC_Inexact) && w->lsu[0]==1) {
1473 /* the exponent, conveniently, is the power of 10; making */
1474 /* this the result needs a little care as it might not fit, */
1475 /* so first convert it into the working number, and then move */
1477 uprv_decNumberFromInt32(w, w->exponent);
1479 decCopyFit(res, w, set, &residue, &status); /* copy & round */
1480 decFinish(res, set, &residue, &status); /* cleanup/set flags */
1482 } /* not a power of 10 */
1483 } /* not a candidate for exact */
1485 /* simplify the information-content calculation to use 'total */
1486 /* number of digits in a, including exponent' as compared to the */
1487 /* requested digits, as increasing this will only rarely cost an */
1488 /* iteration in ln(a) anyway */
1489 t=6; /* it can never be >6 */
1491 /* allocate space when needed... */
1492 p=(rhs->digits+t>set->digits?rhs->digits+t:set->digits)+3;
1493 needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1494 if (needbytes>sizeof(bufa)) { /* need malloc space */
1495 allocbufa=(decNumber *)malloc(needbytes);
1496 if (allocbufa==NULL) { /* hopeless -- abandon */
1497 status|=DEC_Insufficient_storage;
1499 a=allocbufa; /* use the allocated space */
1501 aset.digits=p; /* as calculated */
1502 aset.emax=DEC_MAX_MATH; /* usual bounds */
1503 aset.emin=-DEC_MAX_MATH; /* .. */
1504 aset.clamp=0; /* and no concrete format */
1505 decLnOp(a, rhs, &aset, &status); /* a=ln(rhs) */
1507 /* skip the division if the result so far is infinite, NaN, or */
1508 /* zero, or there was an error; note NaN from sNaN needs copy */
1509 if (status&DEC_NaNs && !(status&DEC_sNaN)) break;
1510 if (a->bits&DECSPECIAL || ISZERO(a)) {
1511 uprv_decNumberCopy(res, a); /* [will fit] */
1514 /* for ln(10) an extra 3 digits of precision are needed */
1516 needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1517 if (needbytes>sizeof(bufb)) { /* need malloc space */
1518 allocbufb=(decNumber *)malloc(needbytes);
1519 if (allocbufb==NULL) { /* hopeless -- abandon */
1520 status|=DEC_Insufficient_storage;
1522 b=allocbufb; /* use the allocated space */
1524 uprv_decNumberZero(w); /* set up 10... */
1526 w->lsu[1]=1; w->lsu[0]=0; /* .. */
1528 w->lsu[0]=10; /* .. */
1530 w->digits=2; /* .. */
1533 decLnOp(b, w, &aset, &ignore); /* b=ln(10) */
1535 aset.digits=set->digits; /* for final divide */
1536 decDivideOp(res, a, b, &aset, DIVIDE, &status); /* into result */
1537 } while(0); /* [for break] */
1539 if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */
1540 if (allocbufb!=NULL) free(allocbufb); /* .. */
1542 if (allocrhs !=NULL) free(allocrhs); /* .. */
1544 /* apply significant status */
1545 if (status!=0) decStatus(res, status, set);
1547 decCheckInexact(res, set);
1550 } /* decNumberLog10 */
1551 #if defined(__clang__) || U_GCC_MAJOR_MINOR >= 406
1552 #pragma GCC diagnostic pop
1555 /* ------------------------------------------------------------------ */
1556 /* decNumberMax -- compare two Numbers and return the maximum */
1558 /* This computes C = A ? B, returning the maximum by 754 rules */
1560 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
1563 /* set is the context */
1565 /* C must have space for set->digits digits. */
1566 /* ------------------------------------------------------------------ */
1567 U_CAPI decNumber * U_EXPORT2 uprv_decNumberMax(decNumber *res, const decNumber *lhs,
1568 const decNumber *rhs, decContext *set) {
1569 uInt status=0; /* accumulator */
1570 decCompareOp(res, lhs, rhs, set, COMPMAX, &status);
1571 if (status!=0) decStatus(res, status, set);
1573 decCheckInexact(res, set);
1576 } /* decNumberMax */
1578 /* ------------------------------------------------------------------ */
1579 /* decNumberMaxMag -- compare and return the maximum by magnitude */
1581 /* This computes C = A ? B, returning the maximum by 754 rules */
1583 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
1586 /* set is the context */
1588 /* C must have space for set->digits digits. */
1589 /* ------------------------------------------------------------------ */
1590 U_CAPI decNumber * U_EXPORT2 uprv_decNumberMaxMag(decNumber *res, const decNumber *lhs,
1591 const decNumber *rhs, decContext *set) {
1592 uInt status=0; /* accumulator */
1593 decCompareOp(res, lhs, rhs, set, COMPMAXMAG, &status);
1594 if (status!=0) decStatus(res, status, set);
1596 decCheckInexact(res, set);
1599 } /* decNumberMaxMag */
1601 /* ------------------------------------------------------------------ */
1602 /* decNumberMin -- compare two Numbers and return the minimum */
1604 /* This computes C = A ? B, returning the minimum by 754 rules */
1606 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
1609 /* set is the context */
1611 /* C must have space for set->digits digits. */
1612 /* ------------------------------------------------------------------ */
1613 U_CAPI decNumber * U_EXPORT2 uprv_decNumberMin(decNumber *res, const decNumber *lhs,
1614 const decNumber *rhs, decContext *set) {
1615 uInt status=0; /* accumulator */
1616 decCompareOp(res, lhs, rhs, set, COMPMIN, &status);
1617 if (status!=0) decStatus(res, status, set);
1619 decCheckInexact(res, set);
1622 } /* decNumberMin */
1624 /* ------------------------------------------------------------------ */
1625 /* decNumberMinMag -- compare and return the minimum by magnitude */
1627 /* This computes C = A ? B, returning the minimum by 754 rules */
1629 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
1632 /* set is the context */
1634 /* C must have space for set->digits digits. */
1635 /* ------------------------------------------------------------------ */
1636 U_CAPI decNumber * U_EXPORT2 uprv_decNumberMinMag(decNumber *res, const decNumber *lhs,
1637 const decNumber *rhs, decContext *set) {
1638 uInt status=0; /* accumulator */
1639 decCompareOp(res, lhs, rhs, set, COMPMINMAG, &status);
1640 if (status!=0) decStatus(res, status, set);
1642 decCheckInexact(res, set);
1645 } /* decNumberMinMag */
1647 /* ------------------------------------------------------------------ */
1648 /* decNumberMinus -- prefix minus operator */
1650 /* This computes C = 0 - A */
1652 /* res is C, the result. C may be A */
1654 /* set is the context */
1656 /* See also decNumberCopyNegate for a quiet bitwise version of this. */
1657 /* C must have space for set->digits digits. */
1658 /* ------------------------------------------------------------------ */
1659 /* Simply use AddOp for the subtract, which will do the necessary. */
1660 /* ------------------------------------------------------------------ */
1661 U_CAPI decNumber * U_EXPORT2 uprv_decNumberMinus(decNumber *res, const decNumber *rhs,
1664 uInt status=0; /* accumulator */
1667 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1670 uprv_decNumberZero(&dzero); /* make 0 */
1671 dzero.exponent=rhs->exponent; /* [no coefficient expansion] */
1672 decAddOp(res, &dzero, rhs, set, DECNEG, &status);
1673 if (status!=0) decStatus(res, status, set);
1675 decCheckInexact(res, set);
1678 } /* decNumberMinus */
1680 /* ------------------------------------------------------------------ */
1681 /* decNumberNextMinus -- next towards -Infinity */
1683 /* This computes C = A - infinitesimal, rounded towards -Infinity */
1685 /* res is C, the result. C may be A */
1687 /* set is the context */
1689 /* This is a generalization of 754 NextDown. */
1690 /* ------------------------------------------------------------------ */
1691 U_CAPI decNumber * U_EXPORT2 uprv_decNumberNextMinus(decNumber *res, const decNumber *rhs,
1693 decNumber dtiny; /* constant */
1694 decContext workset=*set; /* work */
1695 uInt status=0; /* accumulator */
1697 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1700 /* +Infinity is the special case */
1701 if ((rhs->bits&(DECINF|DECNEG))==DECINF) {
1702 decSetMaxValue(res, set); /* is +ve */
1703 /* there is no status to set */
1706 uprv_decNumberZero(&dtiny); /* start with 0 */
1707 dtiny.lsu[0]=1; /* make number that is .. */
1708 dtiny.exponent=DEC_MIN_EMIN-1; /* .. smaller than tiniest */
1709 workset.round=DEC_ROUND_FLOOR;
1710 decAddOp(res, rhs, &dtiny, &workset, DECNEG, &status);
1711 status&=DEC_Invalid_operation|DEC_sNaN; /* only sNaN Invalid please */
1712 if (status!=0) decStatus(res, status, set);
1714 } /* decNumberNextMinus */
1716 /* ------------------------------------------------------------------ */
1717 /* decNumberNextPlus -- next towards +Infinity */
1719 /* This computes C = A + infinitesimal, rounded towards +Infinity */
1721 /* res is C, the result. C may be A */
1723 /* set is the context */
1725 /* This is a generalization of 754 NextUp. */
1726 /* ------------------------------------------------------------------ */
1727 U_CAPI decNumber * U_EXPORT2 uprv_decNumberNextPlus(decNumber *res, const decNumber *rhs,
1729 decNumber dtiny; /* constant */
1730 decContext workset=*set; /* work */
1731 uInt status=0; /* accumulator */
1733 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1736 /* -Infinity is the special case */
1737 if ((rhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1738 decSetMaxValue(res, set);
1739 res->bits=DECNEG; /* negative */
1740 /* there is no status to set */
1743 uprv_decNumberZero(&dtiny); /* start with 0 */
1744 dtiny.lsu[0]=1; /* make number that is .. */
1745 dtiny.exponent=DEC_MIN_EMIN-1; /* .. smaller than tiniest */
1746 workset.round=DEC_ROUND_CEILING;
1747 decAddOp(res, rhs, &dtiny, &workset, 0, &status);
1748 status&=DEC_Invalid_operation|DEC_sNaN; /* only sNaN Invalid please */
1749 if (status!=0) decStatus(res, status, set);
1751 } /* decNumberNextPlus */
1753 /* ------------------------------------------------------------------ */
1754 /* decNumberNextToward -- next towards rhs */
1756 /* This computes C = A +/- infinitesimal, rounded towards */
1757 /* +/-Infinity in the direction of B, as per 754-1985 nextafter */
1758 /* modified during revision but dropped from 754-2008. */
1760 /* res is C, the result. C may be A or B. */
1763 /* set is the context */
1765 /* This is a generalization of 754-1985 NextAfter. */
1766 /* ------------------------------------------------------------------ */
1767 U_CAPI decNumber * U_EXPORT2 uprv_decNumberNextToward(decNumber *res, const decNumber *lhs,
1768 const decNumber *rhs, decContext *set) {
1769 decNumber dtiny; /* constant */
1770 decContext workset=*set; /* work */
1771 Int result; /* .. */
1772 uInt status=0; /* accumulator */
1774 if (decCheckOperands(res, lhs, rhs, set)) return res;
1777 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) {
1778 decNaNs(res, lhs, rhs, set, &status);
1780 else { /* Is numeric, so no chance of sNaN Invalid, etc. */
1781 result=decCompare(lhs, rhs, 0); /* sign matters */
1782 if (result==BADINT) status|=DEC_Insufficient_storage; /* rare */
1783 else { /* valid compare */
1784 if (result==0) uprv_decNumberCopySign(res, lhs, rhs); /* easy */
1785 else { /* differ: need NextPlus or NextMinus */
1786 uByte sub; /* add or subtract */
1787 if (result<0) { /* lhs<rhs, do nextplus */
1788 /* -Infinity is the special case */
1789 if ((lhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1790 decSetMaxValue(res, set);
1791 res->bits=DECNEG; /* negative */
1792 return res; /* there is no status to set */
1794 workset.round=DEC_ROUND_CEILING;
1795 sub=0; /* add, please */
1797 else { /* lhs>rhs, do nextminus */
1798 /* +Infinity is the special case */
1799 if ((lhs->bits&(DECINF|DECNEG))==DECINF) {
1800 decSetMaxValue(res, set);
1801 return res; /* there is no status to set */
1803 workset.round=DEC_ROUND_FLOOR;
1804 sub=DECNEG; /* subtract, please */
1806 uprv_decNumberZero(&dtiny); /* start with 0 */
1807 dtiny.lsu[0]=1; /* make number that is .. */
1808 dtiny.exponent=DEC_MIN_EMIN-1; /* .. smaller than tiniest */
1809 decAddOp(res, lhs, &dtiny, &workset, sub, &status); /* + or - */
1810 /* turn off exceptions if the result is a normal number */
1811 /* (including Nmin), otherwise let all status through */
1812 if (uprv_decNumberIsNormal(res, set)) status=0;
1816 if (status!=0) decStatus(res, status, set);
1818 } /* decNumberNextToward */
1820 /* ------------------------------------------------------------------ */
1821 /* decNumberOr -- OR two Numbers, digitwise */
1823 /* This computes C = A | B */
1825 /* res is C, the result. C may be A and/or B (e.g., X=X|X) */
1828 /* set is the context (used for result length and error report) */
1830 /* C must have space for set->digits digits. */
1832 /* Logical function restrictions apply (see above); a NaN is */
1833 /* returned with Invalid_operation if a restriction is violated. */
1834 /* ------------------------------------------------------------------ */
1835 U_CAPI decNumber * U_EXPORT2 uprv_decNumberOr(decNumber *res, const decNumber *lhs,
1836 const decNumber *rhs, decContext *set) {
1837 const Unit *ua, *ub; /* -> operands */
1838 const Unit *msua, *msub; /* -> operand msus */
1839 Unit *uc, *msuc; /* -> result and its msu */
1840 Int msudigs; /* digits in res msu */
1842 if (decCheckOperands(res, lhs, rhs, set)) return res;
1845 if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
1846 || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
1847 decStatus(res, DEC_Invalid_operation, set);
1850 /* operands are valid */
1851 ua=lhs->lsu; /* bottom-up */
1852 ub=rhs->lsu; /* .. */
1853 uc=res->lsu; /* .. */
1854 msua=ua+D2U(lhs->digits)-1; /* -> msu of lhs */
1855 msub=ub+D2U(rhs->digits)-1; /* -> msu of rhs */
1856 msuc=uc+D2U(set->digits)-1; /* -> msu of result */
1857 msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */
1858 for (; uc<=msuc; ua++, ub++, uc++) { /* Unit loop */
1859 Unit a, b; /* extract units */
1864 *uc=0; /* can now write back */
1865 if (a|b) { /* maybe 1 bits to examine */
1867 /* This loop could be unrolled and/or use BIN2BCD tables */
1868 for (i=0; i<DECDPUN; i++) {
1869 if ((a|b)&1) *uc=*uc+(Unit)powers[i]; /* effect OR */
1875 decStatus(res, DEC_Invalid_operation, set);
1878 if (uc==msuc && i==msudigs-1) break; /* just did final digit */
1882 /* [here uc-1 is the msu of the result] */
1883 res->digits=decGetDigits(res->lsu, uc-res->lsu);
1884 res->exponent=0; /* integer */
1885 res->bits=0; /* sign=0 */
1886 return res; /* [no status to set] */
1889 /* ------------------------------------------------------------------ */
1890 /* decNumberPlus -- prefix plus operator */
1892 /* This computes C = 0 + A */
1894 /* res is C, the result. C may be A */
1896 /* set is the context */
1898 /* See also decNumberCopy for a quiet bitwise version of this. */
1899 /* C must have space for set->digits digits. */
1900 /* ------------------------------------------------------------------ */
1901 /* This simply uses AddOp; Add will take fast path after preparing A. */
1902 /* Performance is a concern here, as this routine is often used to */
1903 /* check operands and apply rounding and overflow/underflow testing. */
1904 /* ------------------------------------------------------------------ */
1905 U_CAPI decNumber * U_EXPORT2 uprv_decNumberPlus(decNumber *res, const decNumber *rhs,
1908 uInt status=0; /* accumulator */
1910 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1913 uprv_decNumberZero(&dzero); /* make 0 */
1914 dzero.exponent=rhs->exponent; /* [no coefficient expansion] */
1915 decAddOp(res, &dzero, rhs, set, 0, &status);
1916 if (status!=0) decStatus(res, status, set);
1918 decCheckInexact(res, set);
1921 } /* decNumberPlus */
1923 /* ------------------------------------------------------------------ */
1924 /* decNumberMultiply -- multiply two Numbers */
1926 /* This computes C = A x B */
1928 /* res is C, the result. C may be A and/or B (e.g., X=X+X) */
1931 /* set is the context */
1933 /* C must have space for set->digits digits. */
1934 /* ------------------------------------------------------------------ */
1935 U_CAPI decNumber * U_EXPORT2 uprv_decNumberMultiply(decNumber *res, const decNumber *lhs,
1936 const decNumber *rhs, decContext *set) {
1937 uInt status=0; /* accumulator */
1938 decMultiplyOp(res, lhs, rhs, set, &status);
1939 if (status!=0) decStatus(res, status, set);
1941 decCheckInexact(res, set);
1944 } /* decNumberMultiply */
1946 /* ------------------------------------------------------------------ */
1947 /* decNumberPower -- raise a number to a power */
1949 /* This computes C = A ** B */
1951 /* res is C, the result. C may be A and/or B (e.g., X=X**X) */
1954 /* set is the context */
1956 /* C must have space for set->digits digits. */
1958 /* Mathematical function restrictions apply (see above); a NaN is */
1959 /* returned with Invalid_operation if a restriction is violated. */
1961 /* However, if 1999999997<=B<=999999999 and B is an integer then the */
1962 /* restrictions on A and the context are relaxed to the usual bounds, */
1963 /* for compatibility with the earlier (integer power only) version */
1964 /* of this function. */
1966 /* When B is an integer, the result may be exact, even if rounded. */
1968 /* The final result is rounded according to the context; it will */
1969 /* almost always be correctly rounded, but may be up to 1 ulp in */
1970 /* error in rare cases. */
1971 /* ------------------------------------------------------------------ */
1972 U_CAPI decNumber * U_EXPORT2 uprv_decNumberPower(decNumber *res, const decNumber *lhs,
1973 const decNumber *rhs, decContext *set) {
1975 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */
1976 decNumber *allocrhs=NULL; /* .., rhs */
1978 decNumber *allocdac=NULL; /* -> allocated acc buffer, iff used */
1979 decNumber *allocinv=NULL; /* -> allocated 1/x buffer, iff used */
1980 Int reqdigits=set->digits; /* requested DIGITS */
1981 Int n; /* rhs in binary */
1982 Flag rhsint=0; /* 1 if rhs is an integer */
1983 Flag useint=0; /* 1 if can use integer calculation */
1984 Flag isoddint=0; /* 1 if rhs is an integer and odd */
1987 Int dropped; /* .. */
1989 uInt needbytes; /* buffer size needed */
1990 Flag seenbit; /* seen a bit while powering */
1991 Int residue=0; /* rounding residue */
1992 uInt status=0; /* accumulators */
1993 uByte bits=0; /* result sign if errors */
1994 decContext aset; /* working context */
1995 decNumber dnOne; /* work value 1... */
1996 /* local accumulator buffer [a decNumber, with digits+elength+1 digits] */
1997 decNumber dacbuff[D2N(DECBUFFER+9)];
1998 decNumber *dac=dacbuff; /* -> result accumulator */
1999 /* same again for possible 1/lhs calculation */
2000 decNumber invbuff[D2N(DECBUFFER+9)];
2003 if (decCheckOperands(res, lhs, rhs, set)) return res;
2006 do { /* protect allocated storage */
2008 if (!set->extended) { /* reduce operands and set status, as needed */
2009 if (lhs->digits>reqdigits) {
2010 alloclhs=decRoundOperand(lhs, set, &status);
2011 if (alloclhs==NULL) break;
2014 if (rhs->digits>reqdigits) {
2015 allocrhs=decRoundOperand(rhs, set, &status);
2016 if (allocrhs==NULL) break;
2021 /* [following code does not require input rounding] */
2023 /* handle NaNs and rhs Infinity (lhs infinity is harder) */
2025 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) { /* NaNs */
2026 decNaNs(res, lhs, rhs, set, &status);
2028 if (decNumberIsInfinite(rhs)) { /* rhs Infinity */
2029 Flag rhsneg=rhs->bits&DECNEG; /* save rhs sign */
2030 if (decNumberIsNegative(lhs) /* lhs<0 */
2031 && !decNumberIsZero(lhs)) /* .. */
2032 status|=DEC_Invalid_operation;
2033 else { /* lhs >=0 */
2034 uprv_decNumberZero(&dnOne); /* set up 1 */
2036 uprv_decNumberCompare(dac, lhs, &dnOne, set); /* lhs ? 1 */
2037 uprv_decNumberZero(res); /* prepare for 0/1/Infinity */
2038 if (decNumberIsNegative(dac)) { /* lhs<1 */
2039 if (rhsneg) res->bits|=DECINF; /* +Infinity [else is +0] */
2041 else if (dac->lsu[0]==0) { /* lhs=1 */
2042 /* 1**Infinity is inexact, so return fully-padded 1.0000 */
2043 Int shift=set->digits-1;
2044 *res->lsu=1; /* was 0, make int 1 */
2045 res->digits=decShiftToMost(res->lsu, 1, shift);
2046 res->exponent=-shift; /* make 1.0000... */
2047 status|=DEC_Inexact|DEC_Rounded; /* deemed inexact */
2050 if (!rhsneg) res->bits|=DECINF; /* +Infinity [else is +0] */
2054 /* [lhs infinity drops through] */
2057 /* Original rhs may be an integer that fits and is in range */
2059 if (n!=BADINT) { /* it is an integer */
2060 rhsint=1; /* record the fact for 1**n */
2061 isoddint=(Flag)n&1; /* [works even if big] */
2062 if (n!=BIGEVEN && n!=BIGODD) /* can use integer path? */
2063 useint=1; /* looks good */
2066 if (decNumberIsNegative(lhs) /* -x .. */
2067 && isoddint) bits=DECNEG; /* .. to an odd power */
2069 /* handle LHS infinity */
2070 if (decNumberIsInfinite(lhs)) { /* [NaNs already handled] */
2071 uByte rbits=rhs->bits; /* save */
2072 uprv_decNumberZero(res); /* prepare */
2073 if (n==0) *res->lsu=1; /* [-]Inf**0 => 1 */
2075 /* -Inf**nonint -> error */
2076 if (!rhsint && decNumberIsNegative(lhs)) {
2077 status|=DEC_Invalid_operation; /* -Inf**nonint is error */
2079 if (!(rbits & DECNEG)) bits|=DECINF; /* was not a **-n */
2080 /* [otherwise will be 0 or -0] */
2085 /* similarly handle LHS zero */
2086 if (decNumberIsZero(lhs)) {
2087 if (n==0) { /* 0**0 => Error */
2089 if (!set->extended) { /* [unless subset] */
2090 uprv_decNumberZero(res);
2091 *res->lsu=1; /* return 1 */
2094 status|=DEC_Invalid_operation;
2097 uByte rbits=rhs->bits; /* save */
2098 if (rbits & DECNEG) { /* was a 0**(-n) */
2100 if (!set->extended) { /* [bad if subset] */
2101 status|=DEC_Invalid_operation;
2106 uprv_decNumberZero(res); /* prepare */
2107 /* [otherwise will be 0 or -0] */
2112 /* here both lhs and rhs are finite; rhs==0 is handled in the */
2113 /* integer path. Next handle the non-integer cases */
2114 if (!useint) { /* non-integral rhs */
2115 /* any -ve lhs is bad, as is either operand or context out of */
2117 if (decNumberIsNegative(lhs)) {
2118 status|=DEC_Invalid_operation;
2120 if (decCheckMath(lhs, set, &status)
2121 || decCheckMath(rhs, set, &status)) break; /* variable status */
2123 uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64); /* clean context */
2124 aset.emax=DEC_MAX_MATH; /* usual bounds */
2125 aset.emin=-DEC_MAX_MATH; /* .. */
2126 aset.clamp=0; /* and no concrete format */
2128 /* calculate the result using exp(ln(lhs)*rhs), which can */
2129 /* all be done into the accumulator, dac. The precision needed */
2130 /* is enough to contain the full information in the lhs (which */
2131 /* is the total digits, including exponent), or the requested */
2132 /* precision, if larger, + 4; 6 is used for the exponent */
2133 /* maximum length, and this is also used when it is shorter */
2134 /* than the requested digits as it greatly reduces the >0.5 ulp */
2135 /* cases at little cost (because Ln doubles digits each */
2136 /* iteration so a few extra digits rarely causes an extra */
2138 aset.digits=MAXI(lhs->digits, set->digits)+6+4;
2139 } /* non-integer rhs */
2141 else { /* rhs is in-range integer */
2142 if (n==0) { /* x**0 = 1 */
2143 /* (0**0 was handled above) */
2144 uprv_decNumberZero(res); /* result=1 */
2145 *res->lsu=1; /* .. */
2147 /* rhs is a non-zero integer */
2148 if (n<0) n=-n; /* use abs(n) */
2150 aset=*set; /* clone the context */
2151 aset.round=DEC_ROUND_HALF_EVEN; /* internally use balanced */
2152 /* calculate the working DIGITS */
2153 aset.digits=reqdigits+(rhs->digits+rhs->exponent)+2;
2155 if (!set->extended) aset.digits--; /* use classic precision */
2157 /* it's an error if this is more than can be handled */
2158 if (aset.digits>DECNUMMAXP) {status|=DEC_Invalid_operation; break;}
2159 } /* integer path */
2161 /* aset.digits is the count of digits for the accumulator needed */
2162 /* if accumulator is too long for local storage, then allocate */
2163 needbytes=sizeof(decNumber)+(D2U(aset.digits)-1)*sizeof(Unit);
2164 /* [needbytes also used below if 1/lhs needed] */
2165 if (needbytes>sizeof(dacbuff)) {
2166 allocdac=(decNumber *)malloc(needbytes);
2167 if (allocdac==NULL) { /* hopeless -- abandon */
2168 status|=DEC_Insufficient_storage;
2170 dac=allocdac; /* use the allocated space */
2172 /* here, aset is set up and accumulator is ready for use */
2174 if (!useint) { /* non-integral rhs */
2175 /* x ** y; special-case x=1 here as it will otherwise always */
2176 /* reduce to integer 1; decLnOp has a fastpath which detects */
2177 /* the case of x=1 */
2178 decLnOp(dac, lhs, &aset, &status); /* dac=ln(lhs) */
2179 /* [no error possible, as lhs 0 already handled] */
2180 if (ISZERO(dac)) { /* x==1, 1.0, etc. */
2181 /* need to return fully-padded 1.0000 etc., but rhsint->1 */
2182 *dac->lsu=1; /* was 0, make int 1 */
2183 if (!rhsint) { /* add padding */
2184 Int shift=set->digits-1;
2185 dac->digits=decShiftToMost(dac->lsu, 1, shift);
2186 dac->exponent=-shift; /* make 1.0000... */
2187 status|=DEC_Inexact|DEC_Rounded; /* deemed inexact */
2191 decMultiplyOp(dac, dac, rhs, &aset, &status); /* dac=dac*rhs */
2192 decExpOp(dac, dac, &aset, &status); /* dac=exp(dac) */
2194 /* and drop through for final rounding */
2195 } /* non-integer rhs */
2197 else { /* carry on with integer */
2198 uprv_decNumberZero(dac); /* acc=1 */
2199 *dac->lsu=1; /* .. */
2201 /* if a negative power the constant 1 is needed, and if not subset */
2202 /* invert the lhs now rather than inverting the result later */
2203 if (decNumberIsNegative(rhs)) { /* was a **-n [hence digits>0] */
2204 decNumber *inv=invbuff; /* asssume use fixed buffer */
2205 uprv_decNumberCopy(&dnOne, dac); /* dnOne=1; [needed now or later] */
2207 if (set->extended) { /* need to calculate 1/lhs */
2209 /* divide lhs into 1, putting result in dac [dac=1/dac] */
2210 decDivideOp(dac, &dnOne, lhs, &aset, DIVIDE, &status);
2211 /* now locate or allocate space for the inverted lhs */
2212 if (needbytes>sizeof(invbuff)) {
2213 allocinv=(decNumber *)malloc(needbytes);
2214 if (allocinv==NULL) { /* hopeless -- abandon */
2215 status|=DEC_Insufficient_storage;
2217 inv=allocinv; /* use the allocated space */
2219 /* [inv now points to big-enough buffer or allocated storage] */
2220 uprv_decNumberCopy(inv, dac); /* copy the 1/lhs */
2221 uprv_decNumberCopy(dac, &dnOne); /* restore acc=1 */
2222 lhs=inv; /* .. and go forward with new lhs */
2228 /* Raise-to-the-power loop... */
2229 seenbit=0; /* set once a 1-bit is encountered */
2230 for (i=1;;i++){ /* for each bit [top bit ignored] */
2231 /* abandon if had overflow or terminal underflow */
2232 if (status & (DEC_Overflow|DEC_Underflow)) { /* interesting? */
2233 if (status&DEC_Overflow || ISZERO(dac)) break;
2235 /* [the following two lines revealed an optimizer bug in a C++ */
2236 /* compiler, with symptom: 5**3 -> 25, when n=n+n was used] */
2237 n=n<<1; /* move next bit to testable position */
2238 if (n<0) { /* top bit is set */
2239 seenbit=1; /* OK, significant bit seen */
2240 decMultiplyOp(dac, dac, lhs, &aset, &status); /* dac=dac*x */
2242 if (i==31) break; /* that was the last bit */
2243 if (!seenbit) continue; /* no need to square 1 */
2244 decMultiplyOp(dac, dac, dac, &aset, &status); /* dac=dac*dac [square] */
2245 } /*i*/ /* 32 bits */
2247 /* complete internal overflow or underflow processing */
2248 if (status & (DEC_Overflow|DEC_Underflow)) {
2250 /* If subset, and power was negative, reverse the kind of -erflow */
2251 /* [1/x not yet done] */
2252 if (!set->extended && decNumberIsNegative(rhs)) {
2253 if (status & DEC_Overflow)
2254 status^=DEC_Overflow | DEC_Underflow | DEC_Subnormal;
2255 else { /* trickier -- Underflow may or may not be set */
2256 status&=~(DEC_Underflow | DEC_Subnormal); /* [one or both] */
2257 status|=DEC_Overflow;
2261 dac->bits=(dac->bits & ~DECNEG) | bits; /* force correct sign */
2262 /* round subnormals [to set.digits rather than aset.digits] */
2263 /* or set overflow result similarly as required */
2264 decFinalize(dac, set, &residue, &status);
2265 uprv_decNumberCopy(res, dac); /* copy to result (is now OK length) */
2270 if (!set->extended && /* subset math */
2271 decNumberIsNegative(rhs)) { /* was a **-n [hence digits>0] */
2272 /* so divide result into 1 [dac=1/dac] */
2273 decDivideOp(dac, &dnOne, dac, &aset, DIVIDE, &status);
2276 } /* rhs integer path */
2278 /* reduce result to the requested length and copy to result */
2279 decCopyFit(res, dac, set, &residue, &status);
2280 decFinish(res, set, &residue, &status); /* final cleanup */
2282 if (!set->extended) decTrim(res, set, 0, 1, &dropped); /* trailing zeros */
2284 } while(0); /* end protected */
2286 if (allocdac!=NULL) free(allocdac); /* drop any storage used */
2287 if (allocinv!=NULL) free(allocinv); /* .. */
2289 if (alloclhs!=NULL) free(alloclhs); /* .. */
2290 if (allocrhs!=NULL) free(allocrhs); /* .. */
2292 if (status!=0) decStatus(res, status, set);
2294 decCheckInexact(res, set);
2297 } /* decNumberPower */
2299 /* ------------------------------------------------------------------ */
2300 /* decNumberQuantize -- force exponent to requested value */
2302 /* This computes C = op(A, B), where op adjusts the coefficient */
2303 /* of C (by rounding or shifting) such that the exponent (-scale) */
2304 /* of C has exponent of B. The numerical value of C will equal A, */
2305 /* except for the effects of any rounding that occurred. */
2307 /* res is C, the result. C may be A or B */
2308 /* lhs is A, the number to adjust */
2309 /* rhs is B, the number with exponent to match */
2310 /* set is the context */
2312 /* C must have space for set->digits digits. */
2314 /* Unless there is an error or the result is infinite, the exponent */
2315 /* after the operation is guaranteed to be equal to that of B. */
2316 /* ------------------------------------------------------------------ */
2317 U_CAPI decNumber * U_EXPORT2 uprv_decNumberQuantize(decNumber *res, const decNumber *lhs,
2318 const decNumber *rhs, decContext *set) {
2319 uInt status=0; /* accumulator */
2320 decQuantizeOp(res, lhs, rhs, set, 1, &status);
2321 if (status!=0) decStatus(res, status, set);
2323 } /* decNumberQuantize */
2325 /* ------------------------------------------------------------------ */
2326 /* decNumberReduce -- remove trailing zeros */
2328 /* This computes C = 0 + A, and normalizes the result */
2330 /* res is C, the result. C may be A */
2332 /* set is the context */
2334 /* C must have space for set->digits digits. */
2335 /* ------------------------------------------------------------------ */
2336 /* Previously known as Normalize */
2337 U_CAPI decNumber * U_EXPORT2 uprv_decNumberNormalize(decNumber *res, const decNumber *rhs,
2339 return uprv_decNumberReduce(res, rhs, set);
2340 } /* decNumberNormalize */
2342 U_CAPI decNumber * U_EXPORT2 uprv_decNumberReduce(decNumber *res, const decNumber *rhs,
2345 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */
2347 uInt status=0; /* as usual */
2348 Int residue=0; /* as usual */
2349 Int dropped; /* work */
2352 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
2355 do { /* protect allocated storage */
2357 if (!set->extended) {
2358 /* reduce operand and set lostDigits status, as needed */
2359 if (rhs->digits>set->digits) {
2360 allocrhs=decRoundOperand(rhs, set, &status);
2361 if (allocrhs==NULL) break;
2366 /* [following code does not require input rounding] */
2368 /* Infinities copy through; NaNs need usual treatment */
2369 if (decNumberIsNaN(rhs)) {
2370 decNaNs(res, rhs, NULL, set, &status);
2374 /* reduce result to the requested length and copy to result */
2375 decCopyFit(res, rhs, set, &residue, &status); /* copy & round */
2376 decFinish(res, set, &residue, &status); /* cleanup/set flags */
2377 decTrim(res, set, 1, 0, &dropped); /* normalize in place */
2379 } while(0); /* end protected */
2382 if (allocrhs !=NULL) free(allocrhs); /* .. */
2384 if (status!=0) decStatus(res, status, set);/* then report status */
2386 } /* decNumberReduce */
2388 /* ------------------------------------------------------------------ */
2389 /* decNumberRescale -- force exponent to requested value */
2391 /* This computes C = op(A, B), where op adjusts the coefficient */
2392 /* of C (by rounding or shifting) such that the exponent (-scale) */
2393 /* of C has the value B. The numerical value of C will equal A, */
2394 /* except for the effects of any rounding that occurred. */
2396 /* res is C, the result. C may be A or B */
2397 /* lhs is A, the number to adjust */
2398 /* rhs is B, the requested exponent */
2399 /* set is the context */
2401 /* C must have space for set->digits digits. */
2403 /* Unless there is an error or the result is infinite, the exponent */
2404 /* after the operation is guaranteed to be equal to B. */
2405 /* ------------------------------------------------------------------ */
2406 U_CAPI decNumber * U_EXPORT2 uprv_decNumberRescale(decNumber *res, const decNumber *lhs,
2407 const decNumber *rhs, decContext *set) {
2408 uInt status=0; /* accumulator */
2409 decQuantizeOp(res, lhs, rhs, set, 0, &status);
2410 if (status!=0) decStatus(res, status, set);
2412 } /* decNumberRescale */
2414 /* ------------------------------------------------------------------ */
2415 /* decNumberRemainder -- divide and return remainder */
2417 /* This computes C = A % B */
2419 /* res is C, the result. C may be A and/or B (e.g., X=X%X) */
2422 /* set is the context */
2424 /* C must have space for set->digits digits. */
2425 /* ------------------------------------------------------------------ */
2426 U_CAPI decNumber * U_EXPORT2 uprv_decNumberRemainder(decNumber *res, const decNumber *lhs,
2427 const decNumber *rhs, decContext *set) {
2428 uInt status=0; /* accumulator */
2429 decDivideOp(res, lhs, rhs, set, REMAINDER, &status);
2430 if (status!=0) decStatus(res, status, set);
2432 decCheckInexact(res, set);
2435 } /* decNumberRemainder */
2437 /* ------------------------------------------------------------------ */
2438 /* decNumberRemainderNear -- divide and return remainder from nearest */
2440 /* This computes C = A % B, where % is the IEEE remainder operator */
2442 /* res is C, the result. C may be A and/or B (e.g., X=X%X) */
2445 /* set is the context */
2447 /* C must have space for set->digits digits. */
2448 /* ------------------------------------------------------------------ */
2449 U_CAPI decNumber * U_EXPORT2 uprv_decNumberRemainderNear(decNumber *res, const decNumber *lhs,
2450 const decNumber *rhs, decContext *set) {
2451 uInt status=0; /* accumulator */
2452 decDivideOp(res, lhs, rhs, set, REMNEAR, &status);
2453 if (status!=0) decStatus(res, status, set);
2455 decCheckInexact(res, set);
2458 } /* decNumberRemainderNear */
2460 /* ------------------------------------------------------------------ */
2461 /* decNumberRotate -- rotate the coefficient of a Number left/right */
2463 /* This computes C = A rot B (in base ten and rotating set->digits */
2466 /* res is C, the result. C may be A and/or B (e.g., X=XrotX) */
2468 /* rhs is B, the number of digits to rotate (-ve to right) */
2469 /* set is the context */
2471 /* The digits of the coefficient of A are rotated to the left (if B */
2472 /* is positive) or to the right (if B is negative) without adjusting */
2473 /* the exponent or the sign of A. If lhs->digits is less than */
2474 /* set->digits the coefficient is padded with zeros on the left */
2475 /* before the rotate. Any leading zeros in the result are removed */
2478 /* B must be an integer (q=0) and in the range -set->digits through */
2480 /* C must have space for set->digits digits. */
2481 /* NaNs are propagated as usual. Infinities are unaffected (but */
2482 /* B must be valid). No status is set unless B is invalid or an */
2483 /* operand is an sNaN. */
2484 /* ------------------------------------------------------------------ */
2485 U_CAPI decNumber * U_EXPORT2 uprv_decNumberRotate(decNumber *res, const decNumber *lhs,
2486 const decNumber *rhs, decContext *set) {
2487 uInt status=0; /* accumulator */
2488 Int rotate; /* rhs as an Int */
2491 if (decCheckOperands(res, lhs, rhs, set)) return res;
2494 /* NaNs propagate as normal */
2495 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2496 decNaNs(res, lhs, rhs, set, &status);
2497 /* rhs must be an integer */
2498 else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2499 status=DEC_Invalid_operation;
2500 else { /* both numeric, rhs is an integer */
2501 rotate=decGetInt(rhs); /* [cannot fail] */
2502 if (rotate==BADINT /* something bad .. */
2503 || rotate==BIGODD || rotate==BIGEVEN /* .. very big .. */
2504 || abs(rotate)>set->digits) /* .. or out of range */
2505 status=DEC_Invalid_operation;
2506 else { /* rhs is OK */
2507 uprv_decNumberCopy(res, lhs);
2508 /* convert -ve rotate to equivalent positive rotation */
2509 if (rotate<0) rotate=set->digits+rotate;
2510 if (rotate!=0 && rotate!=set->digits /* zero or full rotation */
2511 && !decNumberIsInfinite(res)) { /* lhs was infinite */
2512 /* left-rotate to do; 0 < rotate < set->digits */
2513 uInt units, shift; /* work */
2514 uInt msudigits; /* digits in result msu */
2515 Unit *msu=res->lsu+D2U(res->digits)-1; /* current msu */
2516 Unit *msumax=res->lsu+D2U(set->digits)-1; /* rotation msu */
2517 for (msu++; msu<=msumax; msu++) *msu=0; /* ensure high units=0 */
2518 res->digits=set->digits; /* now full-length */
2519 msudigits=MSUDIGITS(res->digits); /* actual digits in msu */
2521 /* rotation here is done in-place, in three steps */
2522 /* 1. shift all to least up to one unit to unit-align final */
2523 /* lsd [any digits shifted out are rotated to the left, */
2524 /* abutted to the original msd (which may require split)] */
2526 /* [if there are no whole units left to rotate, the */
2527 /* rotation is now complete] */
2529 /* 2. shift to least, from below the split point only, so that */
2530 /* the final msd is in the right place in its Unit [any */
2531 /* digits shifted out will fit exactly in the current msu, */
2532 /* left aligned, no split required] */
2534 /* 3. rotate all the units by reversing left part, right */
2535 /* part, and then whole */
2537 /* example: rotate right 8 digits (2 units + 2), DECDPUN=3. */
2539 /* start: 00a bcd efg hij klm npq */
2541 /* 1a 000 0ab cde fgh|ijk lmn [pq saved] */
2542 /* 1b 00p qab cde fgh|ijk lmn */
2544 /* 2a 00p qab cde fgh|00i jkl [mn saved] */
2545 /* 2b mnp qab cde fgh|00i jkl */
2547 /* 3a fgh cde qab mnp|00i jkl */
2548 /* 3b fgh cde qab mnp|jkl 00i */
2549 /* 3c 00i jkl mnp qab cde fgh */
2551 /* Step 1: amount to shift is the partial right-rotate count */
2552 rotate=set->digits-rotate; /* make it right-rotate */
2553 units=rotate/DECDPUN; /* whole units to rotate */
2554 shift=rotate%DECDPUN; /* left-over digits count */
2555 if (shift>0) { /* not an exact number of units */
2556 uInt save=res->lsu[0]%powers[shift]; /* save low digit(s) */
2557 decShiftToLeast(res->lsu, D2U(res->digits), shift);
2558 if (shift>msudigits) { /* msumax-1 needs >0 digits */
2559 uInt rem=save%powers[shift-msudigits];/* split save */
2560 *msumax=(Unit)(save/powers[shift-msudigits]); /* and insert */
2561 *(msumax-1)=*(msumax-1)
2562 +(Unit)(rem*powers[DECDPUN-(shift-msudigits)]); /* .. */
2564 else { /* all fits in msumax */
2565 *msumax=*msumax+(Unit)(save*powers[msudigits-shift]); /* [maybe *1] */
2567 } /* digits shift needed */
2569 /* If whole units to rotate... */
2570 if (units>0) { /* some to do */
2571 /* Step 2: the units to touch are the whole ones in rotate, */
2572 /* if any, and the shift is DECDPUN-msudigits (which may be */
2574 shift=DECDPUN-msudigits;
2575 if (shift>0) { /* not an exact number of units */
2576 uInt save=res->lsu[0]%powers[shift]; /* save low digit(s) */
2577 decShiftToLeast(res->lsu, units, shift);
2578 *msumax=*msumax+(Unit)(save*powers[msudigits]);
2579 } /* partial shift needed */
2581 /* Step 3: rotate the units array using triple reverse */
2582 /* (reversing is easy and fast) */
2583 decReverse(res->lsu+units, msumax); /* left part */
2584 decReverse(res->lsu, res->lsu+units-1); /* right part */
2585 decReverse(res->lsu, msumax); /* whole */
2586 } /* whole units to rotate */
2587 /* the rotation may have left an undetermined number of zeros */
2588 /* on the left, so true length needs to be calculated */
2589 res->digits=decGetDigits(res->lsu, msumax-res->lsu+1);
2590 } /* rotate needed */
2593 if (status!=0) decStatus(res, status, set);
2595 } /* decNumberRotate */
2597 /* ------------------------------------------------------------------ */
2598 /* decNumberSameQuantum -- test for equal exponents */
2600 /* res is the result number, which will contain either 0 or 1 */
2601 /* lhs is a number to test */
2602 /* rhs is the second (usually a pattern) */
2604 /* No errors are possible and no context is needed. */
2605 /* ------------------------------------------------------------------ */
2606 U_CAPI decNumber * U_EXPORT2 uprv_decNumberSameQuantum(decNumber *res, const decNumber *lhs,
2607 const decNumber *rhs) {
2608 Unit ret=0; /* return value */
2611 if (decCheckOperands(res, lhs, rhs, DECUNCONT)) return res;
2615 if (decNumberIsNaN(lhs) && decNumberIsNaN(rhs)) ret=1;
2616 else if (decNumberIsInfinite(lhs) && decNumberIsInfinite(rhs)) ret=1;
2617 /* [anything else with a special gives 0] */
2619 else if (lhs->exponent==rhs->exponent) ret=1;
2621 uprv_decNumberZero(res); /* OK to overwrite an operand now */
2624 } /* decNumberSameQuantum */
2626 /* ------------------------------------------------------------------ */
2627 /* decNumberScaleB -- multiply by a power of 10 */
2629 /* This computes C = A x 10**B where B is an integer (q=0) with */
2630 /* maximum magnitude 2*(emax+digits) */
2632 /* res is C, the result. C may be A or B */
2633 /* lhs is A, the number to adjust */
2634 /* rhs is B, the requested power of ten to use */
2635 /* set is the context */
2637 /* C must have space for set->digits digits. */
2639 /* The result may underflow or overflow. */
2640 /* ------------------------------------------------------------------ */
2641 U_CAPI decNumber * U_EXPORT2 uprv_decNumberScaleB(decNumber *res, const decNumber *lhs,
2642 const decNumber *rhs, decContext *set) {
2643 Int reqexp; /* requested exponent change [B] */
2644 uInt status=0; /* accumulator */
2645 Int residue; /* work */
2648 if (decCheckOperands(res, lhs, rhs, set)) return res;
2651 /* Handle special values except lhs infinite */
2652 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2653 decNaNs(res, lhs, rhs, set, &status);
2654 /* rhs must be an integer */
2655 else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2656 status=DEC_Invalid_operation;
2658 /* lhs is a number; rhs is a finite with q==0 */
2659 reqexp=decGetInt(rhs); /* [cannot fail] */
2660 if (reqexp==BADINT /* something bad .. */
2661 || reqexp==BIGODD || reqexp==BIGEVEN /* .. very big .. */
2662 || abs(reqexp)>(2*(set->digits+set->emax))) /* .. or out of range */
2663 status=DEC_Invalid_operation;
2664 else { /* rhs is OK */
2665 uprv_decNumberCopy(res, lhs); /* all done if infinite lhs */
2666 if (!decNumberIsInfinite(res)) { /* prepare to scale */
2667 res->exponent+=reqexp; /* adjust the exponent */
2669 decFinalize(res, set, &residue, &status); /* .. and check */
2673 if (status!=0) decStatus(res, status, set);
2675 } /* decNumberScaleB */
2677 /* ------------------------------------------------------------------ */
2678 /* decNumberShift -- shift the coefficient of a Number left or right */
2680 /* This computes C = A << B or C = A >> -B (in base ten). */
2682 /* res is C, the result. C may be A and/or B (e.g., X=X<<X) */
2684 /* rhs is B, the number of digits to shift (-ve to right) */
2685 /* set is the context */
2687 /* The digits of the coefficient of A are shifted to the left (if B */
2688 /* is positive) or to the right (if B is negative) without adjusting */
2689 /* the exponent or the sign of A. */
2691 /* B must be an integer (q=0) and in the range -set->digits through */
2693 /* C must have space for set->digits digits. */
2694 /* NaNs are propagated as usual. Infinities are unaffected (but */
2695 /* B must be valid). No status is set unless B is invalid or an */
2696 /* operand is an sNaN. */
2697 /* ------------------------------------------------------------------ */
2698 U_CAPI decNumber * U_EXPORT2 uprv_decNumberShift(decNumber *res, const decNumber *lhs,
2699 const decNumber *rhs, decContext *set) {
2700 uInt status=0; /* accumulator */
2701 Int shift; /* rhs as an Int */
2704 if (decCheckOperands(res, lhs, rhs, set)) return res;
2707 /* NaNs propagate as normal */
2708 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2709 decNaNs(res, lhs, rhs, set, &status);
2710 /* rhs must be an integer */
2711 else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2712 status=DEC_Invalid_operation;
2713 else { /* both numeric, rhs is an integer */
2714 shift=decGetInt(rhs); /* [cannot fail] */
2715 if (shift==BADINT /* something bad .. */
2716 || shift==BIGODD || shift==BIGEVEN /* .. very big .. */
2717 || abs(shift)>set->digits) /* .. or out of range */
2718 status=DEC_Invalid_operation;
2719 else { /* rhs is OK */
2720 uprv_decNumberCopy(res, lhs);
2721 if (shift!=0 && !decNumberIsInfinite(res)) { /* something to do */
2722 if (shift>0) { /* to left */
2723 if (shift==set->digits) { /* removing all */
2724 *res->lsu=0; /* so place 0 */
2725 res->digits=1; /* .. */
2728 /* first remove leading digits if necessary */
2729 if (res->digits+shift>set->digits) {
2730 decDecap(res, res->digits+shift-set->digits);
2731 /* that updated res->digits; may have gone to 1 (for a */
2732 /* single digit or for zero */
2734 if (res->digits>1 || *res->lsu) /* if non-zero.. */
2735 res->digits=decShiftToMost(res->lsu, res->digits, shift);
2736 } /* partial left */
2738 else { /* to right */
2739 if (-shift>=res->digits) { /* discarding all */
2740 *res->lsu=0; /* so place 0 */
2741 res->digits=1; /* .. */
2744 decShiftToLeast(res->lsu, D2U(res->digits), -shift);
2745 res->digits-=(-shift);
2748 } /* non-0 non-Inf shift */
2751 if (status!=0) decStatus(res, status, set);
2753 } /* decNumberShift */
2755 /* ------------------------------------------------------------------ */
2756 /* decNumberSquareRoot -- square root operator */
2758 /* This computes C = squareroot(A) */
2760 /* res is C, the result. C may be A */
2762 /* set is the context; note that rounding mode has no effect */
2764 /* C must have space for set->digits digits. */
2765 /* ------------------------------------------------------------------ */
2766 /* This uses the following varying-precision algorithm in: */
2768 /* Properly Rounded Variable Precision Square Root, T. E. Hull and */
2769 /* A. Abrham, ACM Transactions on Mathematical Software, Vol 11 #3, */
2770 /* pp229-237, ACM, September 1985. */
2772 /* The square-root is calculated using Newton's method, after which */
2773 /* a check is made to ensure the result is correctly rounded. */
2775 /* % [Reformatted original Numerical Turing source code follows.] */
2776 /* function sqrt(x : real) : real */
2777 /* % sqrt(x) returns the properly rounded approximation to the square */
2778 /* % root of x, in the precision of the calling environment, or it */
2779 /* % fails if x < 0. */
2780 /* % t e hull and a abrham, august, 1984 */
2781 /* if x <= 0 then */
2788 /* var f := setexp(x, 0) % fraction part of x [0.1 <= x < 1] */
2789 /* var e := getexp(x) % exponent part of x */
2790 /* var approx : real */
2791 /* if e mod 2 = 0 then */
2792 /* approx := .259 + .819 * f % approx to root of f */
2794 /* f := f/l0 % adjustments */
2795 /* e := e + 1 % for odd */
2796 /* approx := .0819 + 2.59 * f % exponent */
2800 /* const maxp := currentprecision + 2 */
2802 /* p := min(2*p - 2, maxp) % p = 4,6,10, . . . , maxp */
2804 /* approx := .5 * (approx + f/approx) */
2805 /* exit when p = maxp */
2808 /* % approx is now within 1 ulp of the properly rounded square root */
2809 /* % of f; to ensure proper rounding, compare squares of (approx - */
2810 /* % l/2 ulp) and (approx + l/2 ulp) with f. */
2811 /* p := currentprecision */
2813 /* precision p + 2 */
2814 /* const approxsubhalf := approx - setexp(.5, -p) */
2815 /* if mulru(approxsubhalf, approxsubhalf) > f then */
2816 /* approx := approx - setexp(.l, -p + 1) */
2818 /* const approxaddhalf := approx + setexp(.5, -p) */
2819 /* if mulrd(approxaddhalf, approxaddhalf) < f then */
2820 /* approx := approx + setexp(.l, -p + 1) */
2824 /* result setexp(approx, e div 2) % fix exponent */
2826 /* ------------------------------------------------------------------ */
2827 #if defined(__clang__) || U_GCC_MAJOR_MINOR >= 406
2828 #pragma GCC diagnostic push
2829 #pragma GCC diagnostic ignored "-Warray-bounds"
2831 U_CAPI decNumber * U_EXPORT2 uprv_decNumberSquareRoot(decNumber *res, const decNumber *rhs,
2833 decContext workset, approxset; /* work contexts */
2834 decNumber dzero; /* used for constant zero */
2835 Int maxp; /* largest working precision */
2836 Int workp; /* working precision */
2837 Int residue=0; /* rounding residue */
2838 uInt status=0, ignore=0; /* status accumulators */
2839 uInt rstatus; /* .. */
2840 Int exp; /* working exponent */
2841 Int ideal; /* ideal (preferred) exponent */
2842 Int needbytes; /* work */
2843 Int dropped; /* .. */
2846 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */
2848 /* buffer for f [needs +1 in case DECBUFFER 0] */
2849 decNumber buff[D2N(DECBUFFER+1)];
2850 /* buffer for a [needs +2 to match likely maxp] */
2851 decNumber bufa[D2N(DECBUFFER+2)];
2852 /* buffer for temporary, b [must be same size as a] */
2853 decNumber bufb[D2N(DECBUFFER+2)];
2854 decNumber *allocbuff=NULL; /* -> allocated buff, iff allocated */
2855 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
2856 decNumber *allocbufb=NULL; /* -> allocated bufb, iff allocated */
2857 decNumber *f=buff; /* reduced fraction */
2858 decNumber *a=bufa; /* approximation to result */
2859 decNumber *b=bufb; /* intermediate result */
2860 /* buffer for temporary variable, up to 3 digits */
2861 decNumber buft[D2N(3)];
2862 decNumber *t=buft; /* up-to-3-digit constant or work */
2865 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
2868 do { /* protect allocated storage */
2870 if (!set->extended) {
2871 /* reduce operand and set lostDigits status, as needed */
2872 if (rhs->digits>set->digits) {
2873 allocrhs=decRoundOperand(rhs, set, &status);
2874 if (allocrhs==NULL) break;
2875 /* [Note: 'f' allocation below could reuse this buffer if */
2876 /* used, but as this is rare they are kept separate for clarity.] */
2881 /* [following code does not require input rounding] */
2883 /* handle infinities and NaNs */
2885 if (decNumberIsInfinite(rhs)) { /* an infinity */
2886 if (decNumberIsNegative(rhs)) status|=DEC_Invalid_operation;
2887 else uprv_decNumberCopy(res, rhs); /* +Infinity */
2889 else decNaNs(res, rhs, NULL, set, &status); /* a NaN */
2893 /* calculate the ideal (preferred) exponent [floor(exp/2)] */
2894 /* [It would be nicer to write: ideal=rhs->exponent>>1, but this */
2895 /* generates a compiler warning. Generated code is the same.] */
2896 ideal=(rhs->exponent&~1)/2; /* target */
2900 uprv_decNumberCopy(res, rhs); /* could be 0 or -0 */
2901 res->exponent=ideal; /* use the ideal [safe] */
2902 /* use decFinish to clamp any out-of-range exponent, etc. */
2903 decFinish(res, set, &residue, &status);
2907 /* any other -x is an oops */
2908 if (decNumberIsNegative(rhs)) {
2909 status|=DEC_Invalid_operation;
2913 /* space is needed for three working variables */
2914 /* f -- the same precision as the RHS, reduced to 0.01->0.99... */
2915 /* a -- Hull's approximation -- precision, when assigned, is */
2916 /* currentprecision+1 or the input argument precision, */
2917 /* whichever is larger (+2 for use as temporary) */
2918 /* b -- intermediate temporary result (same size as a) */
2919 /* if any is too long for local storage, then allocate */
2920 workp=MAXI(set->digits+1, rhs->digits); /* actual rounding precision */
2921 workp=MAXI(workp, 7); /* at least 7 for low cases */
2922 maxp=workp+2; /* largest working precision */
2924 needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
2925 if (needbytes>(Int)sizeof(buff)) {
2926 allocbuff=(decNumber *)malloc(needbytes);
2927 if (allocbuff==NULL) { /* hopeless -- abandon */
2928 status|=DEC_Insufficient_storage;
2930 f=allocbuff; /* use the allocated space */
2932 /* a and b both need to be able to hold a maxp-length number */
2933 needbytes=sizeof(decNumber)+(D2U(maxp)-1)*sizeof(Unit);
2934 if (needbytes>(Int)sizeof(bufa)) { /* [same applies to b] */
2935 allocbufa=(decNumber *)malloc(needbytes);
2936 allocbufb=(decNumber *)malloc(needbytes);
2937 if (allocbufa==NULL || allocbufb==NULL) { /* hopeless */
2938 status|=DEC_Insufficient_storage;
2940 a=allocbufa; /* use the allocated spaces */
2941 b=allocbufb; /* .. */
2944 /* copy rhs -> f, save exponent, and reduce so 0.1 <= f < 1 */
2945 uprv_decNumberCopy(f, rhs);
2946 exp=f->exponent+f->digits; /* adjusted to Hull rules */
2947 f->exponent=-(f->digits); /* to range */
2949 /* set up working context */
2950 uprv_decContextDefault(&workset, DEC_INIT_DECIMAL64);
2951 workset.emax=DEC_MAX_EMAX;
2952 workset.emin=DEC_MIN_EMIN;
2954 /* [Until further notice, no error is possible and status bits */
2955 /* (Rounded, etc.) should be ignored, not accumulated.] */
2957 /* Calculate initial approximation, and allow for odd exponent */
2958 workset.digits=workp; /* p for initial calculation */
2959 t->bits=0; t->digits=3;
2960 a->bits=0; a->digits=3;
2961 if ((exp & 1)==0) { /* even exponent */
2962 /* Set t=0.259, a=0.819 */
2969 t->lsu[0]=59; t->lsu[1]=2;
2970 a->lsu[0]=19; a->lsu[1]=8;
2972 t->lsu[0]=9; t->lsu[1]=5; t->lsu[2]=2;
2973 a->lsu[0]=9; a->lsu[1]=1; a->lsu[2]=8;
2976 else { /* odd exponent */
2977 /* Set t=0.0819, a=2.59 */
2978 f->exponent--; /* f=f/10 */
2986 t->lsu[0]=19; t->lsu[1]=8;
2987 a->lsu[0]=59; a->lsu[1]=2;
2989 t->lsu[0]=9; t->lsu[1]=1; t->lsu[2]=8;
2990 a->lsu[0]=9; a->lsu[1]=5; a->lsu[2]=2;
2994 decMultiplyOp(a, a, f, &workset, &ignore); /* a=a*f */
2995 decAddOp(a, a, t, &workset, 0, &ignore); /* ..+t */
2996 /* [a is now the initial approximation for sqrt(f), calculated with */
2997 /* currentprecision, which is also a's precision.] */
2999 /* the main calculation loop */
3000 uprv_decNumberZero(&dzero); /* make 0 */
3001 uprv_decNumberZero(t); /* set t = 0.5 */
3002 t->lsu[0]=5; /* .. */
3003 t->exponent=-1; /* .. */
3004 workset.digits=3; /* initial p */
3005 for (; workset.digits<maxp;) {
3006 /* set p to min(2*p - 2, maxp) [hence 3; or: 4, 6, 10, ... , maxp] */
3007 workset.digits=MINI(workset.digits*2-2, maxp);
3008 /* a = 0.5 * (a + f/a) */
3009 /* [calculated at p then rounded to currentprecision] */
3010 decDivideOp(b, f, a, &workset, DIVIDE, &ignore); /* b=f/a */
3011 decAddOp(b, b, a, &workset, 0, &ignore); /* b=b+a */
3012 decMultiplyOp(a, b, t, &workset, &ignore); /* a=b*0.5 */
3015 /* Here, 0.1 <= a < 1 [Hull], and a has maxp digits */
3016 /* now reduce to length, etc.; this needs to be done with a */
3017 /* having the correct exponent so as to handle subnormals */
3019 approxset=*set; /* get emin, emax, etc. */
3020 approxset.round=DEC_ROUND_HALF_EVEN;
3021 a->exponent+=exp/2; /* set correct exponent */
3022 rstatus=0; /* clear status */
3023 residue=0; /* .. and accumulator */
3024 decCopyFit(a, a, &approxset, &residue, &rstatus); /* reduce (if needed) */
3025 decFinish(a, &approxset, &residue, &rstatus); /* clean and finalize */
3027 /* Overflow was possible if the input exponent was out-of-range, */
3028 /* in which case quit */
3029 if (rstatus&DEC_Overflow) {
3030 status=rstatus; /* use the status as-is */
3031 uprv_decNumberCopy(res, a); /* copy to result */
3035 /* Preserve status except Inexact/Rounded */
3036 status|=(rstatus & ~(DEC_Rounded|DEC_Inexact));
3038 /* Carry out the Hull correction */
3039 a->exponent-=exp/2; /* back to 0.1->1 */
3041 /* a is now at final precision and within 1 ulp of the properly */
3042 /* rounded square root of f; to ensure proper rounding, compare */
3043 /* squares of (a - l/2 ulp) and (a + l/2 ulp) with f. */
3044 /* Here workset.digits=maxp and t=0.5, and a->digits determines */
3046 workset.digits--; /* maxp-1 is OK now */
3047 t->exponent=-a->digits-1; /* make 0.5 ulp */
3048 decAddOp(b, a, t, &workset, DECNEG, &ignore); /* b = a - 0.5 ulp */
3049 workset.round=DEC_ROUND_UP;
3050 decMultiplyOp(b, b, b, &workset, &ignore); /* b = mulru(b, b) */
3051 decCompareOp(b, f, b, &workset, COMPARE, &ignore); /* b ? f, reversed */
3052 if (decNumberIsNegative(b)) { /* f < b [i.e., b > f] */
3053 /* this is the more common adjustment, though both are rare */
3054 t->exponent++; /* make 1.0 ulp */
3055 t->lsu[0]=1; /* .. */
3056 decAddOp(a, a, t, &workset, DECNEG, &ignore); /* a = a - 1 ulp */
3057 /* assign to approx [round to length] */
3058 approxset.emin-=exp/2; /* adjust to match a */
3059 approxset.emax-=exp/2;
3060 decAddOp(a, &dzero, a, &approxset, 0, &ignore);
3063 decAddOp(b, a, t, &workset, 0, &ignore); /* b = a + 0.5 ulp */
3064 workset.round=DEC_ROUND_DOWN;
3065 decMultiplyOp(b, b, b, &workset, &ignore); /* b = mulrd(b, b) */
3066 decCompareOp(b, b, f, &workset, COMPARE, &ignore); /* b ? f */
3067 if (decNumberIsNegative(b)) { /* b < f */
3068 t->exponent++; /* make 1.0 ulp */
3069 t->lsu[0]=1; /* .. */
3070 decAddOp(a, a, t, &workset, 0, &ignore); /* a = a + 1 ulp */
3071 /* assign to approx [round to length] */
3072 approxset.emin-=exp/2; /* adjust to match a */
3073 approxset.emax-=exp/2;
3074 decAddOp(a, &dzero, a, &approxset, 0, &ignore);
3077 /* [no errors are possible in the above, and rounding/inexact during */
3078 /* estimation are irrelevant, so status was not accumulated] */
3080 /* Here, 0.1 <= a < 1 (still), so adjust back */
3081 a->exponent+=exp/2; /* set correct exponent */
3083 /* count droppable zeros [after any subnormal rounding] by */
3084 /* trimming a copy */
3085 uprv_decNumberCopy(b, a);
3086 decTrim(b, set, 1, 1, &dropped); /* [drops trailing zeros] */
3088 /* Set Inexact and Rounded. The answer can only be exact if */
3089 /* it is short enough so that squaring it could fit in workp */
3090 /* digits, so this is the only (relatively rare) condition that */
3091 /* a careful check is needed */
3092 if (b->digits*2-1 > workp) { /* cannot fit */
3093 status|=DEC_Inexact|DEC_Rounded;
3095 else { /* could be exact/unrounded */
3096 uInt mstatus=0; /* local status */
3097 decMultiplyOp(b, b, b, &workset, &mstatus); /* try the multiply */
3098 if (mstatus&DEC_Overflow) { /* result just won't fit */
3099 status|=DEC_Inexact|DEC_Rounded;
3101 else { /* plausible */
3102 decCompareOp(t, b, rhs, &workset, COMPARE, &mstatus); /* b ? rhs */
3103 if (!ISZERO(t)) status|=DEC_Inexact|DEC_Rounded; /* not equal */
3104 else { /* is Exact */
3105 /* here, dropped is the count of trailing zeros in 'a' */
3106 /* use closest exponent to ideal... */
3107 Int todrop=ideal-a->exponent; /* most that can be dropped */
3108 if (todrop<0) status|=DEC_Rounded; /* ideally would add 0s */
3109 else { /* unrounded */
3110 /* there are some to drop, but emax may not allow all */
3111 Int maxexp=set->emax-set->digits+1;
3112 Int maxdrop=maxexp-a->exponent;
3113 if (todrop>maxdrop && set->clamp) { /* apply clamping */
3115 status|=DEC_Clamped;
3117 if (dropped<todrop) { /* clamp to those available */
3119 status|=DEC_Clamped;
3121 if (todrop>0) { /* have some to drop */
3122 decShiftToLeast(a->lsu, D2U(a->digits), todrop);
3123 a->exponent+=todrop; /* maintain numerical value */
3124 a->digits-=todrop; /* new length */
3131 /* double-check Underflow, as perhaps the result could not have */
3132 /* been subnormal (initial argument too big), or it is now Exact */
3133 if (status&DEC_Underflow) {
3134 Int ae=rhs->exponent+rhs->digits-1; /* adjusted exponent */
3135 /* check if truly subnormal */
3136 #if DECEXTFLAG /* DEC_Subnormal too */
3137 if (ae>=set->emin*2) status&=~(DEC_Subnormal|DEC_Underflow);
3139 if (ae>=set->emin*2) status&=~DEC_Underflow;
3141 /* check if truly inexact */
3142 if (!(status&DEC_Inexact)) status&=~DEC_Underflow;
3145 uprv_decNumberCopy(res, a); /* a is now the result */
3146 } while(0); /* end protected */
3148 if (allocbuff!=NULL) free(allocbuff); /* drop any storage used */
3149 if (allocbufa!=NULL) free(allocbufa); /* .. */
3150 if (allocbufb!=NULL) free(allocbufb); /* .. */
3152 if (allocrhs !=NULL) free(allocrhs); /* .. */
3154 if (status!=0) decStatus(res, status, set);/* then report status */
3156 decCheckInexact(res, set);
3159 } /* decNumberSquareRoot */
3160 #if defined(__clang__) || U_GCC_MAJOR_MINOR >= 406
3161 #pragma GCC diagnostic pop
3164 /* ------------------------------------------------------------------ */
3165 /* decNumberSubtract -- subtract two Numbers */
3167 /* This computes C = A - B */
3169 /* res is C, the result. C may be A and/or B (e.g., X=X-X) */
3172 /* set is the context */
3174 /* C must have space for set->digits digits. */
3175 /* ------------------------------------------------------------------ */
3176 U_CAPI decNumber * U_EXPORT2 uprv_decNumberSubtract(decNumber *res, const decNumber *lhs,
3177 const decNumber *rhs, decContext *set) {
3178 uInt status=0; /* accumulator */
3180 decAddOp(res, lhs, rhs, set, DECNEG, &status);
3181 if (status!=0) decStatus(res, status, set);
3183 decCheckInexact(res, set);
3186 } /* decNumberSubtract */
3188 /* ------------------------------------------------------------------ */
3189 /* decNumberToIntegralExact -- round-to-integral-value with InExact */
3190 /* decNumberToIntegralValue -- round-to-integral-value */
3192 /* res is the result */
3193 /* rhs is input number */
3194 /* set is the context */
3196 /* res must have space for any value of rhs. */
3198 /* This implements the IEEE special operators and therefore treats */
3199 /* special values as valid. For finite numbers it returns */
3200 /* rescale(rhs, 0) if rhs->exponent is <0. */
3201 /* Otherwise the result is rhs (so no error is possible, except for */
3204 /* The context is used for rounding mode and status after sNaN, but */
3205 /* the digits setting is ignored. The Exact version will signal */
3206 /* Inexact if the result differs numerically from rhs; the other */
3207 /* never signals Inexact. */
3208 /* ------------------------------------------------------------------ */
3209 U_CAPI decNumber * U_EXPORT2 uprv_decNumberToIntegralExact(decNumber *res, const decNumber *rhs,
3212 decContext workset; /* working context */
3213 uInt status=0; /* accumulator */
3216 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
3219 /* handle infinities and NaNs */
3221 if (decNumberIsInfinite(rhs)) uprv_decNumberCopy(res, rhs); /* an Infinity */
3222 else decNaNs(res, rhs, NULL, set, &status); /* a NaN */
3225 /* have a finite number; no error possible (res must be big enough) */
3226 if (rhs->exponent>=0) return uprv_decNumberCopy(res, rhs);
3227 /* that was easy, but if negative exponent there is work to do... */
3228 workset=*set; /* clone rounding, etc. */
3229 workset.digits=rhs->digits; /* no length rounding */
3230 workset.traps=0; /* no traps */
3231 uprv_decNumberZero(&dn); /* make a number with exponent 0 */
3232 uprv_decNumberQuantize(res, rhs, &dn, &workset);
3233 status|=workset.status;
3235 if (status!=0) decStatus(res, status, set);
3237 } /* decNumberToIntegralExact */
3239 U_CAPI decNumber * U_EXPORT2 uprv_decNumberToIntegralValue(decNumber *res, const decNumber *rhs,
3241 decContext workset=*set; /* working context */
3242 workset.traps=0; /* no traps */
3243 uprv_decNumberToIntegralExact(res, rhs, &workset);
3244 /* this never affects set, except for sNaNs; NaN will have been set */
3245 /* or propagated already, so no need to call decStatus */
3246 set->status|=workset.status&DEC_Invalid_operation;
3248 } /* decNumberToIntegralValue */
3250 /* ------------------------------------------------------------------ */
3251 /* decNumberXor -- XOR two Numbers, digitwise */
3253 /* This computes C = A ^ B */
3255 /* res is C, the result. C may be A and/or B (e.g., X=X^X) */
3258 /* set is the context (used for result length and error report) */
3260 /* C must have space for set->digits digits. */
3262 /* Logical function restrictions apply (see above); a NaN is */
3263 /* returned with Invalid_operation if a restriction is violated. */
3264 /* ------------------------------------------------------------------ */
3265 U_CAPI decNumber * U_EXPORT2 uprv_decNumberXor(decNumber *res, const decNumber *lhs,
3266 const decNumber *rhs, decContext *set) {
3267 const Unit *ua, *ub; /* -> operands */
3268 const Unit *msua, *msub; /* -> operand msus */
3269 Unit *uc, *msuc; /* -> result and its msu */
3270 Int msudigs; /* digits in res msu */
3272 if (decCheckOperands(res, lhs, rhs, set)) return res;
3275 if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
3276 || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
3277 decStatus(res, DEC_Invalid_operation, set);
3280 /* operands are valid */
3281 ua=lhs->lsu; /* bottom-up */
3282 ub=rhs->lsu; /* .. */
3283 uc=res->lsu; /* .. */
3284 msua=ua+D2U(lhs->digits)-1; /* -> msu of lhs */
3285 msub=ub+D2U(rhs->digits)-1; /* -> msu of rhs */
3286 msuc=uc+D2U(set->digits)-1; /* -> msu of result */
3287 msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */
3288 for (; uc<=msuc; ua++, ub++, uc++) { /* Unit loop */
3289 Unit a, b; /* extract units */
3294 *uc=0; /* can now write back */
3295 if (a|b) { /* maybe 1 bits to examine */
3297 /* This loop could be unrolled and/or use BIN2BCD tables */
3298 for (i=0; i<DECDPUN; i++) {
3299 if ((a^b)&1) *uc=*uc+(Unit)powers[i]; /* effect XOR */
3305 decStatus(res, DEC_Invalid_operation, set);
3308 if (uc==msuc && i==msudigs-1) break; /* just did final digit */
3312 /* [here uc-1 is the msu of the result] */
3313 res->digits=decGetDigits(res->lsu, uc-res->lsu);
3314 res->exponent=0; /* integer */
3315 res->bits=0; /* sign=0 */
3316 return res; /* [no status to set] */
3317 } /* decNumberXor */
3320 /* ================================================================== */
3321 /* Utility routines */
3322 /* ================================================================== */
3324 /* ------------------------------------------------------------------ */
3325 /* decNumberClass -- return the decClass of a decNumber */
3326 /* dn -- the decNumber to test */
3327 /* set -- the context to use for Emin */
3328 /* returns the decClass enum */
3329 /* ------------------------------------------------------------------ */
3330 enum decClass uprv_decNumberClass(const decNumber *dn, decContext *set) {
3331 if (decNumberIsSpecial(dn)) {
3332 if (decNumberIsQNaN(dn)) return DEC_CLASS_QNAN;
3333 if (decNumberIsSNaN(dn)) return DEC_CLASS_SNAN;
3334 /* must be an infinity */
3335 if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_INF;
3336 return DEC_CLASS_POS_INF;
3339 if (uprv_decNumberIsNormal(dn, set)) { /* most common */
3340 if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_NORMAL;
3341 return DEC_CLASS_POS_NORMAL;
3343 /* is subnormal or zero */
3344 if (decNumberIsZero(dn)) { /* most common */
3345 if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_ZERO;
3346 return DEC_CLASS_POS_ZERO;
3348 if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_SUBNORMAL;
3349 return DEC_CLASS_POS_SUBNORMAL;
3350 } /* decNumberClass */
3352 /* ------------------------------------------------------------------ */
3353 /* decNumberClassToString -- convert decClass to a string */
3355 /* eclass is a valid decClass */
3356 /* returns a constant string describing the class (max 13+1 chars) */
3357 /* ------------------------------------------------------------------ */
3358 const char *uprv_decNumberClassToString(enum decClass eclass) {
3359 if (eclass==DEC_CLASS_POS_NORMAL) return DEC_ClassString_PN;
3360 if (eclass==DEC_CLASS_NEG_NORMAL) return DEC_ClassString_NN;
3361 if (eclass==DEC_CLASS_POS_ZERO) return DEC_ClassString_PZ;
3362 if (eclass==DEC_CLASS_NEG_ZERO) return DEC_ClassString_NZ;
3363 if (eclass==DEC_CLASS_POS_SUBNORMAL) return DEC_ClassString_PS;
3364 if (eclass==DEC_CLASS_NEG_SUBNORMAL) return DEC_ClassString_NS;
3365 if (eclass==DEC_CLASS_POS_INF) return DEC_ClassString_PI;
3366 if (eclass==DEC_CLASS_NEG_INF) return DEC_ClassString_NI;
3367 if (eclass==DEC_CLASS_QNAN) return DEC_ClassString_QN;
3368 if (eclass==DEC_CLASS_SNAN) return DEC_ClassString_SN;
3369 return DEC_ClassString_UN; /* Unknown */
3370 } /* decNumberClassToString */
3372 /* ------------------------------------------------------------------ */
3373 /* decNumberCopy -- copy a number */
3375 /* dest is the target decNumber */
3376 /* src is the source decNumber */
3379 /* (dest==src is allowed and is a no-op) */
3380 /* All fields are updated as required. This is a utility operation, */
3381 /* so special values are unchanged and no error is possible. */
3382 /* ------------------------------------------------------------------ */
3383 U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopy(decNumber *dest, const decNumber *src) {
3386 if (src==NULL) return uprv_decNumberZero(dest);
3389 if (dest==src) return dest; /* no copy required */
3391 /* Use explicit assignments here as structure assignment could copy */
3392 /* more than just the lsu (for small DECDPUN). This would not affect */
3393 /* the value of the results, but could disturb test harness spill */
3395 dest->bits=src->bits;
3396 dest->exponent=src->exponent;
3397 dest->digits=src->digits;
3398 dest->lsu[0]=src->lsu[0];
3399 if (src->digits>DECDPUN) { /* more Units to come */
3400 const Unit *smsup, *s; /* work */
3402 /* memcpy for the remaining Units would be safe as they cannot */
3403 /* overlap. However, this explicit loop is faster in short cases. */
3404 d=dest->lsu+1; /* -> first destination */
3405 smsup=src->lsu+D2U(src->digits); /* -> source msu+1 */
3406 for (s=src->lsu+1; s<smsup; s++, d++) *d=*s;
3409 } /* decNumberCopy */
3411 /* ------------------------------------------------------------------ */
3412 /* decNumberCopyAbs -- quiet absolute value operator */
3414 /* This sets C = abs(A) */
3416 /* res is C, the result. C may be A */
3419 /* C must have space for set->digits digits. */
3420 /* No exception or error can occur; this is a quiet bitwise operation.*/
3421 /* See also decNumberAbs for a checking version of this. */
3422 /* ------------------------------------------------------------------ */
3423 U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopyAbs(decNumber *res, const decNumber *rhs) {
3425 if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3427 uprv_decNumberCopy(res, rhs);
3428 res->bits&=~DECNEG; /* turn off sign */
3430 } /* decNumberCopyAbs */
3432 /* ------------------------------------------------------------------ */
3433 /* decNumberCopyNegate -- quiet negate value operator */
3435 /* This sets C = negate(A) */
3437 /* res is C, the result. C may be A */
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 decNumberMinus for a checking version of this. */
3443 /* ------------------------------------------------------------------ */
3444 U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopyNegate(decNumber *res, const decNumber *rhs) {
3446 if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3448 uprv_decNumberCopy(res, rhs);
3449 res->bits^=DECNEG; /* invert the sign */
3451 } /* decNumberCopyNegate */
3453 /* ------------------------------------------------------------------ */
3454 /* decNumberCopySign -- quiet copy and set sign operator */
3456 /* This sets C = A with the sign of B */
3458 /* res is C, the result. C may be A */
3462 /* C must have space for set->digits digits. */
3463 /* No exception or error can occur; this is a quiet bitwise operation.*/
3464 /* ------------------------------------------------------------------ */
3465 U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopySign(decNumber *res, const decNumber *lhs,
3466 const decNumber *rhs) {
3467 uByte sign; /* rhs sign */
3469 if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3471 sign=rhs->bits & DECNEG; /* save sign bit */
3472 uprv_decNumberCopy(res, lhs);
3473 res->bits&=~DECNEG; /* clear the sign */
3474 res->bits|=sign; /* set from rhs */
3476 } /* decNumberCopySign */
3478 /* ------------------------------------------------------------------ */
3479 /* decNumberGetBCD -- get the coefficient in BCD8 */
3480 /* dn is the source decNumber */
3481 /* bcd is the uInt array that will receive dn->digits BCD bytes, */
3482 /* most-significant at offset 0 */
3485 /* bcd must have at least dn->digits bytes. No error is possible; if */
3486 /* dn is a NaN or Infinite, digits must be 1 and the coefficient 0. */
3487 /* ------------------------------------------------------------------ */
3488 U_CAPI uByte * U_EXPORT2 uprv_decNumberGetBCD(const decNumber *dn, uByte *bcd) {
3489 uByte *ub=bcd+dn->digits-1; /* -> lsd */
3490 const Unit *up=dn->lsu; /* Unit pointer, -> lsu */
3492 #if DECDPUN==1 /* trivial simple copy */
3493 for (; ub>=bcd; ub--, up++) *ub=*up;
3494 #else /* chopping needed */
3495 uInt u=*up; /* work */
3496 uInt cut=DECDPUN; /* downcounter through unit */
3497 for (; ub>=bcd; ub--) {
3498 *ub=(uByte)(u%10); /* [*6554 trick inhibits, here] */
3501 if (cut>0) continue; /* more in this unit */
3508 } /* decNumberGetBCD */
3510 /* ------------------------------------------------------------------ */
3511 /* decNumberSetBCD -- set (replace) the coefficient from BCD8 */
3512 /* dn is the target decNumber */
3513 /* bcd is the uInt array that will source n BCD bytes, most- */
3514 /* significant at offset 0 */
3515 /* n is the number of digits in the source BCD array (bcd) */
3518 /* dn must have space for at least n digits. No error is possible; */
3519 /* if dn is a NaN, or Infinite, or is to become a zero, n must be 1 */
3520 /* and bcd[0] zero. */
3521 /* ------------------------------------------------------------------ */
3522 U_CAPI decNumber * U_EXPORT2 uprv_decNumberSetBCD(decNumber *dn, const uByte *bcd, uInt n) {
3523 Unit *up=dn->lsu+D2U(dn->digits)-1; /* -> msu [target pointer] */
3524 const uByte *ub=bcd; /* -> source msd */
3526 #if DECDPUN==1 /* trivial simple copy */
3527 for (; ub<bcd+n; ub++, up--) *up=*ub;
3528 #else /* some assembly needed */
3529 /* calculate how many digits in msu, and hence first cut */
3530 Int cut=MSUDIGITS(n); /* [faster than remainder] */
3531 for (;up>=dn->lsu; up--) { /* each Unit from msu */
3532 *up=0; /* will take <=DECDPUN digits */
3533 for (; cut>0; ub++, cut--) *up=X10(*up)+*ub;
3534 cut=DECDPUN; /* next Unit has all digits */
3537 dn->digits=n; /* set digit count */
3539 } /* decNumberSetBCD */
3541 /* ------------------------------------------------------------------ */
3542 /* decNumberIsNormal -- test normality of a decNumber */
3543 /* dn is the decNumber to test */
3544 /* set is the context to use for Emin */
3545 /* returns 1 if |dn| is finite and >=Nmin, 0 otherwise */
3546 /* ------------------------------------------------------------------ */
3547 Int uprv_decNumberIsNormal(const decNumber *dn, decContext *set) {
3548 Int ae; /* adjusted exponent */
3550 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
3553 if (decNumberIsSpecial(dn)) return 0; /* not finite */
3554 if (decNumberIsZero(dn)) return 0; /* not non-zero */
3556 ae=dn->exponent+dn->digits-1; /* adjusted exponent */
3557 if (ae<set->emin) return 0; /* is subnormal */
3559 } /* decNumberIsNormal */
3561 /* ------------------------------------------------------------------ */
3562 /* decNumberIsSubnormal -- test subnormality of a decNumber */
3563 /* dn is the decNumber to test */
3564 /* set is the context to use for Emin */
3565 /* returns 1 if |dn| is finite, non-zero, and <Nmin, 0 otherwise */
3566 /* ------------------------------------------------------------------ */
3567 Int uprv_decNumberIsSubnormal(const decNumber *dn, decContext *set) {
3568 Int ae; /* adjusted exponent */
3570 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
3573 if (decNumberIsSpecial(dn)) return 0; /* not finite */
3574 if (decNumberIsZero(dn)) return 0; /* not non-zero */
3576 ae=dn->exponent+dn->digits-1; /* adjusted exponent */
3577 if (ae<set->emin) return 1; /* is subnormal */
3579 } /* decNumberIsSubnormal */
3581 /* ------------------------------------------------------------------ */
3582 /* decNumberTrim -- remove insignificant zeros */
3584 /* dn is the number to trim */
3587 /* All fields are updated as required. This is a utility operation, */
3588 /* so special values are unchanged and no error is possible. The */
3589 /* zeros are removed unconditionally. */
3590 /* ------------------------------------------------------------------ */
3591 U_CAPI decNumber * U_EXPORT2 uprv_decNumberTrim(decNumber *dn) {
3592 Int dropped; /* work */
3593 decContext set; /* .. */
3595 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, DECUNCONT)) return dn;
3597 uprv_decContextDefault(&set, DEC_INIT_BASE); /* clamp=0 */
3598 return decTrim(dn, &set, 0, 1, &dropped);
3599 } /* decNumberTrim */
3601 /* ------------------------------------------------------------------ */
3602 /* decNumberVersion -- return the name and version of this module */
3604 /* No error is possible. */
3605 /* ------------------------------------------------------------------ */
3606 const char * uprv_decNumberVersion(void) {
3608 } /* decNumberVersion */
3610 /* ------------------------------------------------------------------ */
3611 /* decNumberZero -- set a number to 0 */
3613 /* dn is the number to set, with space for one digit */
3616 /* No error is possible. */
3617 /* ------------------------------------------------------------------ */
3618 /* Memset is not used as it is much slower in some environments. */
3619 U_CAPI decNumber * U_EXPORT2 uprv_decNumberZero(decNumber *dn) {
3622 if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
3630 } /* decNumberZero */
3632 /* ================================================================== */
3633 /* Local routines */
3634 /* ================================================================== */
3636 /* ------------------------------------------------------------------ */
3637 /* decToString -- lay out a number into a string */
3639 /* dn is the number to lay out */
3640 /* string is where to lay out the number */
3641 /* eng is 1 if Engineering, 0 if Scientific */
3643 /* string must be at least dn->digits+14 characters long */
3644 /* No error is possible. */
3646 /* Note that this routine can generate a -0 or 0.000. These are */
3647 /* never generated in subset to-number or arithmetic, but can occur */
3648 /* in non-subset arithmetic (e.g., -1*0 or 1.234-1.234). */
3649 /* ------------------------------------------------------------------ */
3650 /* If DECCHECK is enabled the string "?" is returned if a number is */
3652 static void decToString(const decNumber *dn, char *string, Flag eng) {
3653 Int exp=dn->exponent; /* local copy */
3654 Int e; /* E-part value */
3655 Int pre; /* digits before the '.' */
3656 Int cut; /* for counting digits in a Unit */
3657 char *c=string; /* work [output pointer] */
3658 const Unit *up=dn->lsu+D2U(dn->digits)-1; /* -> msu [input pointer] */
3659 uInt u, pow; /* work */
3662 if (decCheckOperands(DECUNRESU, dn, DECUNUSED, DECUNCONT)) {
3663 strcpy(string, "?");
3667 if (decNumberIsNegative(dn)) { /* Negatives get a minus */
3671 if (dn->bits&DECSPECIAL) { /* Is a special value */
3672 if (decNumberIsInfinite(dn)) {
3674 strcpy(c+3, "inity");
3677 if (dn->bits&DECSNAN) { /* signalling NaN */
3682 c+=3; /* step past */
3683 /* if not a clean non-zero coefficient, that's all there is in a */
3685 if (exp!=0 || (*dn->lsu==0 && dn->digits==1)) return;
3686 /* [drop through to add integer] */
3689 /* calculate how many digits in msu, and hence first cut */
3690 cut=MSUDIGITS(dn->digits); /* [faster than remainder] */
3691 cut--; /* power of ten for digit */
3693 if (exp==0) { /* simple integer [common fastpath] */
3694 for (;up>=dn->lsu; up--) { /* each Unit from msu */
3695 u=*up; /* contains DECDPUN digits to lay out */
3696 for (; cut>=0; c++, cut--) TODIGIT(u, cut, c, pow);
3697 cut=DECDPUN-1; /* next Unit has all digits */
3699 *c='\0'; /* terminate the string */
3702 /* non-0 exponent -- assume plain form */
3703 pre=dn->digits+exp; /* digits before '.' */
3705 if ((exp>0) || (pre<-5)) { /* need exponential form */
3706 e=exp+dn->digits-1; /* calculate E value */
3707 pre=1; /* assume one digit before '.' */
3708 if (eng && (e!=0)) { /* engineering: may need to adjust */
3709 Int adj; /* adjustment */
3710 /* The C remainder operator is undefined for negative numbers, so */
3711 /* a positive remainder calculation must be used here */
3714 if (adj!=0) adj=3-adj;
3720 /* if dealing with zero still produce an exponent which is a */
3721 /* multiple of three, as expected, but there will only be the */
3722 /* one zero before the E, still. Otherwise note the padding. */
3723 if (!ISZERO(dn)) pre+=adj;
3724 else { /* is zero */
3725 if (adj!=0) { /* 0.00Esnn needed */
3731 } /* need exponent */
3733 /* lay out the digits of the coefficient, adding 0s and . as needed */
3735 if (pre>0) { /* xxx.xxx or xx00 (engineering) form */
3737 for (; pre>0; pre--, c++, cut--) {
3738 if (cut<0) { /* need new Unit */
3739 if (up==dn->lsu) break; /* out of input digits (pre>digits) */
3744 TODIGIT(u, cut, c, pow);
3746 if (n<dn->digits) { /* more to come, after '.' */
3748 for (;; c++, cut--) {
3749 if (cut<0) { /* need new Unit */
3750 if (up==dn->lsu) break; /* out of input digits */
3755 TODIGIT(u, cut, c, pow);
3758 else for (; pre>0; pre--, c++) *c='0'; /* 0 padding (for engineering) needed */
3760 else { /* 0.xxx or 0.000xxx form */
3763 for (; pre<0; pre++, c++) *c='0'; /* add any 0's after '.' */
3764 for (; ; c++, cut--) {
3765 if (cut<0) { /* need new Unit */
3766 if (up==dn->lsu) break; /* out of input digits */
3771 TODIGIT(u, cut, c, pow);
3775 /* Finally add the E-part, if needed. It will never be 0, has a
3776 base maximum and minimum of +999999999 through -999999999, but
3777 could range down to -1999999998 for anormal numbers */
3779 Flag had=0; /* 1=had non-zero */
3781 *c='+'; c++; /* assume positive */
3784 *(c-1)='-'; /* oops, need - */
3785 u=-e; /* uInt, please */
3787 /* lay out the exponent [_itoa or equivalent is not ANSI C] */
3788 for (cut=9; cut>=0; cut--) {
3789 TODIGIT(u, cut, c, pow);
3790 if (*c=='0' && !had) continue; /* skip leading zeros */
3791 had=1; /* had non-0 */
3792 c++; /* step for next */
3795 *c='\0'; /* terminate the string (all paths) */
3799 /* ------------------------------------------------------------------ */
3800 /* decAddOp -- add/subtract operation */
3802 /* This computes C = A + B */
3804 /* res is C, the result. C may be A and/or B (e.g., X=X+X) */
3807 /* set is the context */
3808 /* negate is DECNEG if rhs should be negated, or 0 otherwise */
3809 /* status accumulates status for the caller */
3811 /* C must have space for set->digits digits. */
3812 /* Inexact in status must be 0 for correct Exact zero sign in result */
3813 /* ------------------------------------------------------------------ */
3814 /* If possible, the coefficient is calculated directly into C. */
3816 /* -- a digits+1 calculation is needed because the numbers are */
3817 /* unaligned and span more than set->digits digits */
3818 /* -- a carry to digits+1 digits looks possible */
3819 /* -- C is the same as A or B, and the result would destructively */
3820 /* overlap the A or B coefficient */
3821 /* then the result must be calculated into a temporary buffer. In */
3822 /* this case a local (stack) buffer is used if possible, and only if */
3823 /* too long for that does malloc become the final resort. */
3825 /* Misalignment is handled as follows: */
3826 /* Apad: (AExp>BExp) Swap operands and proceed as for BExp>AExp. */
3827 /* BPad: Apply the padding by a combination of shifting (whole */
3828 /* units) and multiplication (part units). */
3830 /* Addition, especially x=x+1, is speed-critical. */
3831 /* The static buffer is larger than might be expected to allow for */
3832 /* calls from higher-level funtions (notable exp). */
3833 /* ------------------------------------------------------------------ */
3834 static decNumber * decAddOp(decNumber *res, const decNumber *lhs,
3835 const decNumber *rhs, decContext *set,
3836 uByte negate, uInt *status) {
3838 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */
3839 decNumber *allocrhs=NULL; /* .., rhs */
3841 Int rhsshift; /* working shift (in Units) */
3842 Int maxdigits; /* longest logical length */
3843 Int mult; /* multiplier */
3844 Int residue; /* rounding accumulator */
3845 uByte bits; /* result bits */
3846 Flag diffsign; /* non-0 if arguments have different sign */
3847 Unit *acc; /* accumulator for result */
3848 Unit accbuff[SD2U(DECBUFFER*2+20)]; /* local buffer [*2+20 reduces many */
3849 /* allocations when called from */
3850 /* other operations, notable exp] */
3851 Unit *allocacc=NULL; /* -> allocated acc buffer, iff allocated */
3852 Int reqdigits=set->digits; /* local copy; requested DIGITS */
3853 Int padding; /* work */
3856 if (decCheckOperands(res, lhs, rhs, set)) return res;
3859 do { /* protect allocated storage */
3861 if (!set->extended) {
3862 /* reduce operands and set lostDigits status, as needed */
3863 if (lhs->digits>reqdigits) {
3864 alloclhs=decRoundOperand(lhs, set, status);
3865 if (alloclhs==NULL) break;
3868 if (rhs->digits>reqdigits) {
3869 allocrhs=decRoundOperand(rhs, set, status);
3870 if (allocrhs==NULL) break;
3875 /* [following code does not require input rounding] */
3877 /* note whether signs differ [used all paths] */
3878 diffsign=(Flag)((lhs->bits^rhs->bits^negate)&DECNEG);
3880 /* handle infinities and NaNs */
3881 if (SPECIALARGS) { /* a special bit set */
3882 if (SPECIALARGS & (DECSNAN | DECNAN)) /* a NaN */
3883 decNaNs(res, lhs, rhs, set, status);
3884 else { /* one or two infinities */
3885 if (decNumberIsInfinite(lhs)) { /* LHS is infinity */
3886 /* two infinities with different signs is invalid */
3887 if (decNumberIsInfinite(rhs) && diffsign) {
3888 *status|=DEC_Invalid_operation;
3891 bits=lhs->bits & DECNEG; /* get sign from LHS */
3893 else bits=(rhs->bits^negate) & DECNEG;/* RHS must be Infinity */
3895 uprv_decNumberZero(res);
3896 res->bits=bits; /* set +/- infinity */
3901 /* Quick exit for add 0s; return the non-0, modified as need be */
3903 Int adjust; /* work */
3904 Int lexp=lhs->exponent; /* save in case LHS==RES */
3905 bits=lhs->bits; /* .. */
3906 residue=0; /* clear accumulator */
3907 decCopyFit(res, rhs, set, &residue, status); /* copy (as needed) */
3908 res->bits^=negate; /* flip if rhs was negated */
3910 if (set->extended) { /* exponents on zeros count */
3912 /* exponent will be the lower of the two */
3913 adjust=lexp-res->exponent; /* adjustment needed [if -ve] */
3914 if (ISZERO(res)) { /* both 0: special IEEE 754 rules */
3915 if (adjust<0) res->exponent=lexp; /* set exponent */
3916 /* 0-0 gives +0 unless rounding to -infinity, and -0-0 gives -0 */
3918 if (set->round!=DEC_ROUND_FLOOR) res->bits=0;
3919 else res->bits=DECNEG; /* preserve 0 sign */
3922 else { /* non-0 res */
3923 if (adjust<0) { /* 0-padding needed */
3924 if ((res->digits-adjust)>set->digits) {
3925 adjust=res->digits-set->digits; /* to fit exactly */
3926 *status|=DEC_Rounded; /* [but exact] */
3928 res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
3929 res->exponent+=adjust; /* set the exponent. */
3935 decFinish(res, set, &residue, status); /* clean and finalize */
3938 if (ISZERO(rhs)) { /* [lhs is non-zero] */
3939 Int adjust; /* work */
3940 Int rexp=rhs->exponent; /* save in case RHS==RES */
3941 bits=rhs->bits; /* be clean */
3942 residue=0; /* clear accumulator */
3943 decCopyFit(res, lhs, set, &residue, status); /* copy (as needed) */
3945 if (set->extended) { /* exponents on zeros count */
3947 /* exponent will be the lower of the two */
3948 /* [0-0 case handled above] */
3949 adjust=rexp-res->exponent; /* adjustment needed [if -ve] */
3950 if (adjust<0) { /* 0-padding needed */
3951 if ((res->digits-adjust)>set->digits) {
3952 adjust=res->digits-set->digits; /* to fit exactly */
3953 *status|=DEC_Rounded; /* [but exact] */
3955 res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
3956 res->exponent+=adjust; /* set the exponent. */
3961 decFinish(res, set, &residue, status); /* clean and finalize */
3964 /* [NB: both fastpath and mainpath code below assume these cases */
3965 /* (notably 0-0) have already been handled] */
3967 /* calculate the padding needed to align the operands */
3968 padding=rhs->exponent-lhs->exponent;
3970 /* Fastpath cases where the numbers are aligned and normal, the RHS */
3971 /* is all in one unit, no operand rounding is needed, and no carry, */
3972 /* lengthening, or borrow is needed */
3974 && rhs->digits<=DECDPUN
3975 && rhs->exponent>=set->emin /* [some normals drop through] */
3976 && rhs->exponent<=set->emax-set->digits+1 /* [could clamp] */
3977 && rhs->digits<=reqdigits
3978 && lhs->digits<=reqdigits) {
3979 Int partial=*lhs->lsu;
3980 if (!diffsign) { /* adding */
3982 if ((partial<=DECDPUNMAX) /* result fits in unit */
3983 && (lhs->digits>=DECDPUN || /* .. and no digits-count change */
3984 partial<(Int)powers[lhs->digits])) { /* .. */
3985 if (res!=lhs) uprv_decNumberCopy(res, lhs); /* not in place */
3986 *res->lsu=(Unit)partial; /* [copy could have overwritten RHS] */
3989 /* else drop out for careful add */
3991 else { /* signs differ */
3993 if (partial>0) { /* no borrow needed, and non-0 result */
3994 if (res!=lhs) uprv_decNumberCopy(res, lhs); /* not in place */
3995 *res->lsu=(Unit)partial;
3996 /* this could have reduced digits [but result>0] */
3997 res->digits=decGetDigits(res->lsu, D2U(res->digits));
4000 /* else drop out for careful subtract */
4004 /* Now align (pad) the lhs or rhs so they can be added or */
4005 /* subtracted, as necessary. If one number is much larger than */
4006 /* the other (that is, if in plain form there is a least one */
4007 /* digit between the lowest digit of one and the highest of the */
4008 /* other) padding with up to DIGITS-1 trailing zeros may be */
4009 /* needed; then apply rounding (as exotic rounding modes may be */
4010 /* affected by the residue). */
4011 rhsshift=0; /* rhs shift to left (padding) in Units */
4012 bits=lhs->bits; /* assume sign is that of LHS */
4013 mult=1; /* likely multiplier */
4015 /* [if padding==0 the operands are aligned; no padding is needed] */
4017 /* some padding needed; always pad the RHS, as any required */
4018 /* padding can then be effected by a simple combination of */
4019 /* shifts and a multiply */
4021 if (padding<0) { /* LHS needs the padding */
4023 padding=-padding; /* will be +ve */
4024 bits=(uByte)(rhs->bits^negate); /* assumed sign is now that of RHS */
4025 t=lhs; lhs=rhs; rhs=t;
4029 /* If, after pad, rhs would be longer than lhs by digits+1 or */
4030 /* more then lhs cannot affect the answer, except as a residue, */
4031 /* so only need to pad up to a length of DIGITS+1. */
4032 if (rhs->digits+padding > lhs->digits+reqdigits+1) {
4033 /* The RHS is sufficient */
4034 /* for residue use the relative sign indication... */
4035 Int shift=reqdigits-rhs->digits; /* left shift needed */
4036 residue=1; /* residue for rounding */
4037 if (diffsign) residue=-residue; /* signs differ */
4038 /* copy, shortening if necessary */
4039 decCopyFit(res, rhs, set, &residue, status);
4040 /* if it was already shorter, then need to pad with zeros */
4042 res->digits=decShiftToMost(res->lsu, res->digits, shift);
4043 res->exponent-=shift; /* adjust the exponent. */
4045 /* flip the result sign if unswapped and rhs was negated */
4046 if (!swapped) res->bits^=negate;
4047 decFinish(res, set, &residue, status); /* done */
4050 /* LHS digits may affect result */
4051 rhsshift=D2U(padding+1)-1; /* this much by Unit shift .. */
4052 mult=powers[padding-(rhsshift*DECDPUN)]; /* .. this by multiplication */
4053 } /* padding needed */
4055 if (diffsign) mult=-mult; /* signs differ */
4057 /* determine the longer operand */
4058 maxdigits=rhs->digits+padding; /* virtual length of RHS */
4059 if (lhs->digits>maxdigits) maxdigits=lhs->digits;
4061 /* Decide on the result buffer to use; if possible place directly */
4063 acc=res->lsu; /* assume add direct to result */
4064 /* If destructive overlap, or the number is too long, or a carry or */
4065 /* borrow to DIGITS+1 might be possible, a buffer must be used. */
4066 /* [Might be worth more sophisticated tests when maxdigits==reqdigits] */
4067 if ((maxdigits>=reqdigits) /* is, or could be, too large */
4068 || (res==rhs && rhsshift>0)) { /* destructive overlap */
4069 /* buffer needed, choose it; units for maxdigits digits will be */
4070 /* needed, +1 Unit for carry or borrow */
4071 Int need=D2U(maxdigits)+1;
4072 acc=accbuff; /* assume use local buffer */
4073 if (need*sizeof(Unit)>sizeof(accbuff)) {
4074 /* printf("malloc add %ld %ld\n", need, sizeof(accbuff)); */
4075 allocacc=(Unit *)malloc(need*sizeof(Unit));
4076 if (allocacc==NULL) { /* hopeless -- abandon */
4077 *status|=DEC_Insufficient_storage;
4083 res->bits=(uByte)(bits&DECNEG); /* it's now safe to overwrite.. */
4084 res->exponent=lhs->exponent; /* .. operands (even if aliased) */
4087 decDumpAr('A', lhs->lsu, D2U(lhs->digits));
4088 decDumpAr('B', rhs->lsu, D2U(rhs->digits));
4089 printf(" :h: %ld %ld\n", rhsshift, mult);
4092 /* add [A+B*m] or subtract [A+B*(-m)] */
4093 U_ASSERT(rhs->digits > 0);
4094 U_ASSERT(lhs->digits > 0);
4095 res->digits=decUnitAddSub(lhs->lsu, D2U(lhs->digits),
4096 rhs->lsu, D2U(rhs->digits),
4097 rhsshift, acc, mult)
4098 *DECDPUN; /* [units -> digits] */
4099 if (res->digits<0) { /* borrowed... */
4100 res->digits=-res->digits;
4101 res->bits^=DECNEG; /* flip the sign */
4104 decDumpAr('+', acc, D2U(res->digits));
4107 /* If a buffer was used the result must be copied back, possibly */
4108 /* shortening. (If no buffer was used then the result must have */
4109 /* fit, so can't need rounding and residue must be 0.) */
4110 residue=0; /* clear accumulator */
4111 if (acc!=res->lsu) {
4113 if (set->extended) { /* round from first significant digit */
4115 /* remove leading zeros that were added due to rounding up to */
4116 /* integral Units -- before the test for rounding. */
4117 if (res->digits>reqdigits)
4118 res->digits=decGetDigits(acc, D2U(res->digits));
4119 decSetCoeff(res, set, acc, res->digits, &residue, status);
4122 else { /* subset arithmetic rounds from original significant digit */
4123 /* May have an underestimate. This only occurs when both */
4124 /* numbers fit in DECDPUN digits and are padding with a */
4125 /* negative multiple (-10, -100...) and the top digit(s) become */
4126 /* 0. (This only matters when using X3.274 rules where the */
4127 /* leading zero could be included in the rounding.) */
4128 if (res->digits<maxdigits) {
4129 *(acc+D2U(res->digits))=0; /* ensure leading 0 is there */
4130 res->digits=maxdigits;
4133 /* remove leading zeros that added due to rounding up to */
4134 /* integral Units (but only those in excess of the original */
4135 /* maxdigits length, unless extended) before test for rounding. */
4136 if (res->digits>reqdigits) {
4137 res->digits=decGetDigits(acc, D2U(res->digits));
4138 if (res->digits<maxdigits) res->digits=maxdigits;
4141 decSetCoeff(res, set, acc, res->digits, &residue, status);
4142 /* Now apply rounding if needed before removing leading zeros. */
4143 /* This is safe because subnormals are not a possibility */
4145 decApplyRound(res, set, residue, status);
4146 residue=0; /* did what needed to be done */
4152 /* strip leading zeros [these were left on in case of subset subtract] */
4153 res->digits=decGetDigits(res->lsu, D2U(res->digits));
4155 /* apply checks and rounding */
4156 decFinish(res, set, &residue, status);
4158 /* "When the sum of two operands with opposite signs is exactly */
4159 /* zero, the sign of that sum shall be '+' in all rounding modes */
4160 /* except round toward -Infinity, in which mode that sign shall be */
4161 /* '-'." [Subset zeros also never have '-', set by decFinish.] */
4162 if (ISZERO(res) && diffsign
4166 && (*status&DEC_Inexact)==0) {
4167 if (set->round==DEC_ROUND_FLOOR) res->bits|=DECNEG; /* sign - */
4168 else res->bits&=~DECNEG; /* sign + */
4170 } while(0); /* end protected */
4172 if (allocacc!=NULL) free(allocacc); /* drop any storage used */
4174 if (allocrhs!=NULL) free(allocrhs); /* .. */
4175 if (alloclhs!=NULL) free(alloclhs); /* .. */
4180 /* ------------------------------------------------------------------ */
4181 /* decDivideOp -- division operation */
4183 /* This routine performs the calculations for all four division */
4184 /* operators (divide, divideInteger, remainder, remainderNear). */
4188 /* res is C, the result. C may be A and/or B (e.g., X=X/X) */
4191 /* set is the context */
4192 /* op is DIVIDE, DIVIDEINT, REMAINDER, or REMNEAR respectively. */
4193 /* status is the usual accumulator */
4195 /* C must have space for set->digits digits. */
4197 /* ------------------------------------------------------------------ */
4198 /* The underlying algorithm of this routine is the same as in the */
4199 /* 1981 S/370 implementation, that is, non-restoring long division */
4200 /* with bi-unit (rather than bi-digit) estimation for each unit */
4201 /* multiplier. In this pseudocode overview, complications for the */
4202 /* Remainder operators and division residues for exact rounding are */
4203 /* omitted for clarity. */
4205 /* Prepare operands and handle special values */
4206 /* Test for x/0 and then 0/x */
4207 /* Exp =Exp1 - Exp2 */
4208 /* Exp =Exp +len(var1) -len(var2) */
4209 /* Sign=Sign1 * Sign2 */
4210 /* Pad accumulator (Var1) to double-length with 0's (pad1) */
4211 /* Pad Var2 to same length as Var1 */
4212 /* msu2pair/plus=1st 2 or 1 units of var2, +1 to allow for round */
4214 /* Do until (have=digits+1 OR residue=0) */
4215 /* if exp<0 then if integer divide/residue then leave */
4218 /* compare numbers */
4219 /* if <0 then leave inner_loop */
4220 /* if =0 then (* quick exit without subtract *) do */
4221 /* this_unit=this_unit+1; output this_unit */
4222 /* leave outer_loop; end */
4223 /* Compare lengths of numbers (mantissae): */
4224 /* If same then tops2=msu2pair -- {units 1&2 of var2} */
4225 /* else tops2=msu2plus -- {0, unit 1 of var2} */
4226 /* tops1=first_unit_of_Var1*10**DECDPUN +second_unit_of_var1 */
4227 /* mult=tops1/tops2 -- Good and safe guess at divisor */
4228 /* if mult=0 then mult=1 */
4229 /* this_unit=this_unit+mult */
4231 /* end inner_loop */
4232 /* if have\=0 | this_unit\=0 then do */
4233 /* output this_unit */
4234 /* have=have+1; end */
4237 /* end outer_loop */
4238 /* exp=exp+1 -- set the proper exponent */
4239 /* if have=0 then generate answer=0 */
4240 /* Return (Result is defined by Var1) */
4242 /* ------------------------------------------------------------------ */
4243 /* Two working buffers are needed during the division; one (digits+ */
4244 /* 1) to accumulate the result, and the other (up to 2*digits+1) for */
4245 /* long subtractions. These are acc and var1 respectively. */
4246 /* var1 is a copy of the lhs coefficient, var2 is the rhs coefficient.*/
4247 /* The static buffers may be larger than might be expected to allow */
4248 /* for calls from higher-level funtions (notable exp). */
4249 /* ------------------------------------------------------------------ */
4250 static decNumber * decDivideOp(decNumber *res,
4251 const decNumber *lhs, const decNumber *rhs,
4252 decContext *set, Flag op, uInt *status) {
4254 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */
4255 decNumber *allocrhs=NULL; /* .., rhs */
4257 Unit accbuff[SD2U(DECBUFFER+DECDPUN+10)]; /* local buffer */
4258 Unit *acc=accbuff; /* -> accumulator array for result */
4259 Unit *allocacc=NULL; /* -> allocated buffer, iff allocated */
4260 Unit *accnext; /* -> where next digit will go */
4261 Int acclength; /* length of acc needed [Units] */
4262 Int accunits; /* count of units accumulated */
4263 Int accdigits; /* count of digits accumulated */
4265 Unit varbuff[SD2U(DECBUFFER*2+DECDPUN)]; /* buffer for var1 */
4266 Unit *var1=varbuff; /* -> var1 array for long subtraction */
4267 Unit *varalloc=NULL; /* -> allocated buffer, iff used */
4268 Unit *msu1; /* -> msu of var1 */
4270 const Unit *var2; /* -> var2 array */
4271 const Unit *msu2; /* -> msu of var2 */
4272 Int msu2plus; /* msu2 plus one [does not vary] */
4273 eInt msu2pair; /* msu2 pair plus one [does not vary] */
4275 Int var1units, var2units; /* actual lengths */
4276 Int var2ulen; /* logical length (units) */
4277 Int var1initpad=0; /* var1 initial padding (digits) */
4278 Int maxdigits; /* longest LHS or required acc length */
4279 Int mult; /* multiplier for subtraction */
4280 Unit thisunit; /* current unit being accumulated */
4281 Int residue; /* for rounding */
4282 Int reqdigits=set->digits; /* requested DIGITS */
4283 Int exponent; /* working exponent */
4284 Int maxexponent=0; /* DIVIDE maximum exponent if unrounded */
4285 uByte bits; /* working sign */
4286 Unit *target; /* work */
4287 const Unit *source; /* .. */
4288 uInt const *pow; /* .. */
4289 Int shift, cut; /* .. */
4291 Int dropped; /* work */
4295 if (decCheckOperands(res, lhs, rhs, set)) return res;
4298 do { /* protect allocated storage */
4300 if (!set->extended) {
4301 /* reduce operands and set lostDigits status, as needed */
4302 if (lhs->digits>reqdigits) {
4303 alloclhs=decRoundOperand(lhs, set, status);
4304 if (alloclhs==NULL) break;
4307 if (rhs->digits>reqdigits) {
4308 allocrhs=decRoundOperand(rhs, set, status);
4309 if (allocrhs==NULL) break;
4314 /* [following code does not require input rounding] */
4316 bits=(lhs->bits^rhs->bits)&DECNEG; /* assumed sign for divisions */
4318 /* handle infinities and NaNs */
4319 if (SPECIALARGS) { /* a special bit set */
4320 if (SPECIALARGS & (DECSNAN | DECNAN)) { /* one or two NaNs */
4321 decNaNs(res, lhs, rhs, set, status);
4324 /* one or two infinities */
4325 if (decNumberIsInfinite(lhs)) { /* LHS (dividend) is infinite */
4326 if (decNumberIsInfinite(rhs) || /* two infinities are invalid .. */
4327 op & (REMAINDER | REMNEAR)) { /* as is remainder of infinity */
4328 *status|=DEC_Invalid_operation;
4331 /* [Note that infinity/0 raises no exceptions] */
4332 uprv_decNumberZero(res);
4333 res->bits=bits|DECINF; /* set +/- infinity */
4336 else { /* RHS (divisor) is infinite */
4338 if (op&(REMAINDER|REMNEAR)) {
4339 /* result is [finished clone of] lhs */
4340 decCopyFit(res, lhs, set, &residue, status);
4342 else { /* a division */
4343 uprv_decNumberZero(res);
4344 res->bits=bits; /* set +/- zero */
4345 /* for DIVIDEINT the exponent is always 0. For DIVIDE, result */
4346 /* is a 0 with infinitely negative exponent, clamped to minimum */
4348 res->exponent=set->emin-set->digits+1;
4349 *status|=DEC_Clamped;
4352 decFinish(res, set, &residue, status);
4357 /* handle 0 rhs (x/0) */
4358 if (ISZERO(rhs)) { /* x/0 is always exceptional */
4360 uprv_decNumberZero(res); /* [after lhs test] */
4361 *status|=DEC_Division_undefined;/* 0/0 will become NaN */
4364 uprv_decNumberZero(res);
4365 if (op&(REMAINDER|REMNEAR)) *status|=DEC_Invalid_operation;
4367 *status|=DEC_Division_by_zero; /* x/0 */
4368 res->bits=bits|DECINF; /* .. is +/- Infinity */
4373 /* handle 0 lhs (0/x) */
4374 if (ISZERO(lhs)) { /* 0/x [x!=0] */
4376 if (!set->extended) uprv_decNumberZero(res);
4381 exponent=lhs->exponent-rhs->exponent; /* ideal exponent */
4382 uprv_decNumberCopy(res, lhs); /* [zeros always fit] */
4383 res->bits=bits; /* sign as computed */
4384 res->exponent=exponent; /* exponent, too */
4385 decFinalize(res, set, &residue, status); /* check exponent */
4387 else if (op&DIVIDEINT) {
4388 uprv_decNumberZero(res); /* integer 0 */
4389 res->bits=bits; /* sign as computed */
4391 else { /* a remainder */
4392 exponent=rhs->exponent; /* [save in case overwrite] */
4393 uprv_decNumberCopy(res, lhs); /* [zeros always fit] */
4394 if (exponent<res->exponent) res->exponent=exponent; /* use lower */
4401 /* Precalculate exponent. This starts off adjusted (and hence fits */
4402 /* in 31 bits) and becomes the usual unadjusted exponent as the */
4403 /* division proceeds. The order of evaluation is important, here, */
4404 /* to avoid wrap. */
4405 exponent=(lhs->exponent+lhs->digits)-(rhs->exponent+rhs->digits);
4407 /* If the working exponent is -ve, then some quick exits are */
4408 /* possible because the quotient is known to be <1 */
4409 /* [for REMNEAR, it needs to be < -1, as -0.5 could need work] */
4410 if (exponent<0 && !(op==DIVIDE)) {
4412 uprv_decNumberZero(res); /* integer part is 0 */
4416 res->bits=bits; /* set +/- zero */
4418 /* fastpath remainders so long as the lhs has the smaller */
4419 /* (or equal) exponent */
4420 if (lhs->exponent<=rhs->exponent) {
4421 if (op&REMAINDER || exponent<-1) {
4422 /* It is REMAINDER or safe REMNEAR; result is [finished */
4423 /* clone of] lhs (r = x - 0*y) */
4425 decCopyFit(res, lhs, set, &residue, status);
4426 decFinish(res, set, &residue, status);
4429 /* [unsafe REMNEAR drops through] */
4433 /* Long (slow) division is needed; roll up the sleeves... */
4435 /* The accumulator will hold the quotient of the division. */
4436 /* If it needs to be too long for stack storage, then allocate. */
4437 acclength=D2U(reqdigits+DECDPUN); /* in Units */
4438 if (acclength*sizeof(Unit)>sizeof(accbuff)) {
4439 /* printf("malloc dvacc %ld units\n", acclength); */
4440 allocacc=(Unit *)malloc(acclength*sizeof(Unit));
4441 if (allocacc==NULL) { /* hopeless -- abandon */
4442 *status|=DEC_Insufficient_storage;
4444 acc=allocacc; /* use the allocated space */
4447 /* var1 is the padded LHS ready for subtractions. */
4448 /* If it needs to be too long for stack storage, then allocate. */
4449 /* The maximum units needed for var1 (long subtraction) is: */
4451 /* (rhs->digits+reqdigits-1) -- to allow full slide to right */
4452 /* or (lhs->digits) -- to allow for long lhs */
4453 /* whichever is larger */
4454 /* +1 -- for rounding of slide to right */
4455 /* +1 -- for leading 0s */
4456 /* +1 -- for pre-adjust if a remainder or DIVIDEINT */
4457 /* [Note: unused units do not participate in decUnitAddSub data] */
4458 maxdigits=rhs->digits+reqdigits-1;
4459 if (lhs->digits>maxdigits) maxdigits=lhs->digits;
4460 var1units=D2U(maxdigits)+2;
4461 /* allocate a guard unit above msu1 for REMAINDERNEAR */
4462 if (!(op&DIVIDE)) var1units++;
4463 if ((var1units+1)*sizeof(Unit)>sizeof(varbuff)) {
4464 /* printf("malloc dvvar %ld units\n", var1units+1); */
4465 varalloc=(Unit *)malloc((var1units+1)*sizeof(Unit));
4466 if (varalloc==NULL) { /* hopeless -- abandon */
4467 *status|=DEC_Insufficient_storage;
4469 var1=varalloc; /* use the allocated space */
4472 /* Extend the lhs and rhs to full long subtraction length. The lhs */
4473 /* is truly extended into the var1 buffer, with 0 padding, so a */
4474 /* subtract in place is always possible. The rhs (var2) has */
4475 /* virtual padding (implemented by decUnitAddSub). */
4476 /* One guard unit was allocated above msu1 for rem=rem+rem in */
4477 /* REMAINDERNEAR. */
4478 msu1=var1+var1units-1; /* msu of var1 */
4479 source=lhs->lsu+D2U(lhs->digits)-1; /* msu of input array */
4480 for (target=msu1; source>=lhs->lsu; source--, target--) *target=*source;
4481 for (; target>=var1; target--) *target=0;
4483 /* rhs (var2) is left-aligned with var1 at the start */
4484 var2ulen=var1units; /* rhs logical length (units) */
4485 var2units=D2U(rhs->digits); /* rhs actual length (units) */
4486 var2=rhs->lsu; /* -> rhs array */
4487 msu2=var2+var2units-1; /* -> msu of var2 [never changes] */
4488 /* now set up the variables which will be used for estimating the */
4489 /* multiplication factor. If these variables are not exact, add */
4490 /* 1 to make sure that the multiplier is never overestimated. */
4491 msu2plus=*msu2; /* it's value .. */
4492 if (var2units>1) msu2plus++; /* .. +1 if any more */
4493 msu2pair=(eInt)*msu2*(DECDPUNMAX+1);/* top two pair .. */
4494 if (var2units>1) { /* .. [else treat 2nd as 0] */
4495 msu2pair+=*(msu2-1); /* .. */
4496 if (var2units>2) msu2pair++; /* .. +1 if any more */
4499 /* The calculation is working in units, which may have leading zeros, */
4500 /* but the exponent was calculated on the assumption that they are */
4501 /* both left-aligned. Adjust the exponent to compensate: add the */
4502 /* number of leading zeros in var1 msu and subtract those in var2 msu. */
4503 /* [This is actually done by counting the digits and negating, as */
4504 /* lead1=DECDPUN-digits1, and similarly for lead2.] */
4505 for (pow=&powers[1]; *msu1>=*pow; pow++) exponent--;
4506 for (pow=&powers[1]; *msu2>=*pow; pow++) exponent++;
4508 /* Now, if doing an integer divide or remainder, ensure that */
4509 /* the result will be Unit-aligned. To do this, shift the var1 */
4510 /* accumulator towards least if need be. (It's much easier to */
4511 /* do this now than to reassemble the residue afterwards, if */
4512 /* doing a remainder.) Also ensure the exponent is not negative. */
4515 /* save the initial 'false' padding of var1, in digits */
4516 var1initpad=(var1units-D2U(lhs->digits))*DECDPUN;
4517 /* Determine the shift to do. */
4518 if (exponent<0) cut=-exponent;
4519 else cut=DECDPUN-exponent%DECDPUN;
4520 decShiftToLeast(var1, var1units, cut);
4521 exponent+=cut; /* maintain numerical value */
4522 var1initpad-=cut; /* .. and reduce padding */
4523 /* clean any most-significant units which were just emptied */
4524 for (u=msu1; cut>=DECDPUN; cut-=DECDPUN, u--) *u=0;
4526 else { /* is DIVIDE */
4527 maxexponent=lhs->exponent-rhs->exponent; /* save */
4528 /* optimization: if the first iteration will just produce 0, */
4529 /* preadjust to skip it [valid for DIVIDE only] */
4531 var2ulen--; /* shift down */
4532 exponent-=DECDPUN; /* update the exponent */
4536 /* ---- start the long-division loops ------------------------------ */
4537 accunits=0; /* no units accumulated yet */
4538 accdigits=0; /* .. or digits */
4539 accnext=acc+acclength-1; /* -> msu of acc [NB: allows digits+1] */
4540 for (;;) { /* outer forever loop */
4541 thisunit=0; /* current unit assumed 0 */
4542 /* find the next unit */
4543 for (;;) { /* inner forever loop */
4544 /* strip leading zero units [from either pre-adjust or from */
4545 /* subtract last time around]. Leave at least one unit. */
4546 for (; *msu1==0 && msu1>var1; msu1--) var1units--;
4548 if (var1units<var2ulen) break; /* var1 too low for subtract */
4549 if (var1units==var2ulen) { /* unit-by-unit compare needed */
4550 /* compare the two numbers, from msu */
4551 const Unit *pv1, *pv2;
4552 Unit v2; /* units to compare */
4553 pv2=msu2; /* -> msu */
4554 for (pv1=msu1; ; pv1--, pv2--) {
4555 /* v1=*pv1 -- always OK */
4556 v2=0; /* assume in padding */
4557 if (pv2>=var2) v2=*pv2; /* in range */
4558 if (*pv1!=v2) break; /* no longer the same */
4559 if (pv1==var1) break; /* done; leave pv1 as is */
4561 /* here when all inspected or a difference seen */
4562 if (*pv1<v2) break; /* var1 too low to subtract */
4563 if (*pv1==v2) { /* var1 == var2 */
4564 /* reach here if var1 and var2 are identical; subtraction */
4565 /* would increase digit by one, and the residue will be 0 so */
4566 /* the calculation is done; leave the loop with residue=0. */
4567 thisunit++; /* as though subtracted */
4568 *var1=0; /* set var1 to 0 */
4569 var1units=1; /* .. */
4570 break; /* from inner */
4571 } /* var1 == var2 */
4572 /* *pv1>v2. Prepare for real subtraction; the lengths are equal */
4573 /* Estimate the multiplier (there's always a msu1-1)... */
4574 /* Bring in two units of var2 to provide a good estimate. */
4575 mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2pair);
4576 } /* lengths the same */
4577 else { /* var1units > var2ulen, so subtraction is safe */
4578 /* The var2 msu is one unit towards the lsu of the var1 msu, */
4579 /* so only one unit for var2 can be used. */
4580 mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2plus);
4582 if (mult==0) mult=1; /* must always be at least 1 */
4583 /* subtraction needed; var1 is > var2 */
4584 thisunit=(Unit)(thisunit+mult); /* accumulate */
4585 /* subtract var1-var2, into var1; only the overlap needs */
4586 /* processing, as this is an in-place calculation */
4587 shift=var2ulen-var2units;
4589 decDumpAr('1', &var1[shift], var1units-shift);
4590 decDumpAr('2', var2, var2units);
4591 printf("m=%ld\n", -mult);
4593 decUnitAddSub(&var1[shift], var1units-shift,
4595 &var1[shift], -mult);
4597 decDumpAr('#', &var1[shift], var1units-shift);
4599 /* var1 now probably has leading zeros; these are removed at the */
4600 /* top of the inner loop. */
4603 /* The next unit has been calculated in full; unless it's a */
4604 /* leading zero, add to acc */
4605 if (accunits!=0 || thisunit!=0) { /* is first or non-zero */
4606 *accnext=thisunit; /* store in accumulator */
4607 /* account exactly for the new digits */
4609 accdigits++; /* at least one */
4610 for (pow=&powers[1]; thisunit>=*pow; pow++) accdigits++;
4612 else accdigits+=DECDPUN;
4613 accunits++; /* update count */
4614 accnext--; /* ready for next */
4615 if (accdigits>reqdigits) break; /* have enough digits */
4618 /* if the residue is zero, the operation is done (unless divide */
4619 /* or divideInteger and still not enough digits yet) */
4620 if (*var1==0 && var1units==1) { /* residue is 0 */
4621 if (op&(REMAINDER|REMNEAR)) break;
4622 if ((op&DIVIDE) && (exponent<=maxexponent)) break;
4623 /* [drop through if divideInteger] */
4625 /* also done enough if calculating remainder or integer */
4626 /* divide and just did the last ('units') unit */
4627 if (exponent==0 && !(op&DIVIDE)) break;
4629 /* to get here, var1 is less than var2, so divide var2 by the per- */
4630 /* Unit power of ten and go for the next digit */
4631 var2ulen--; /* shift down */
4632 exponent-=DECDPUN; /* update the exponent */
4635 /* ---- division is complete --------------------------------------- */
4636 /* here: acc has at least reqdigits+1 of good results (or fewer */
4637 /* if early stop), starting at accnext+1 (its lsu) */
4638 /* var1 has any residue at the stopping point */
4639 /* accunits is the number of digits collected in acc */
4640 if (accunits==0) { /* acc is 0 */
4641 accunits=1; /* show have a unit .. */
4642 accdigits=1; /* .. */
4643 *accnext=0; /* .. whose value is 0 */
4645 else accnext++; /* back to last placed */
4646 /* accnext now -> lowest unit of result */
4648 residue=0; /* assume no residue */
4650 /* record the presence of any residue, for rounding */
4651 if (*var1!=0 || var1units>1) residue=1;
4652 else { /* no residue */
4653 /* Had an exact division; clean up spurious trailing 0s. */
4654 /* There will be at most DECDPUN-1, from the final multiply, */
4655 /* and then only if the result is non-0 (and even) and the */
4656 /* exponent is 'loose'. */
4659 if (!(lsu&0x01) && (lsu!=0)) {
4660 /* count the trailing zeros */
4662 for (;; drop++) { /* [will terminate because lsu!=0] */
4663 if (exponent>=maxexponent) break; /* don't chop real 0s */
4665 if ((lsu-QUOT10(lsu, drop+1)
4666 *powers[drop+1])!=0) break; /* found non-0 digit */
4668 if (lsu%powers[drop+1]!=0) break; /* found non-0 digit */
4673 accunits=decShiftToLeast(accnext, accunits, drop);
4674 accdigits=decGetDigits(accnext, accunits);
4675 accunits=D2U(accdigits);
4676 /* [exponent was adjusted in the loop] */
4678 } /* neither odd nor 0 */
4680 } /* exact divide */
4682 else /* op!=DIVIDE */ {
4683 /* check for coefficient overflow */
4684 if (accdigits+exponent>reqdigits) {
4685 *status|=DEC_Division_impossible;
4688 if (op & (REMAINDER|REMNEAR)) {
4689 /* [Here, the exponent will be 0, because var1 was adjusted */
4690 /* appropriately.] */
4691 Int postshift; /* work */
4692 Flag wasodd=0; /* integer was odd */
4693 Unit *quotlsu; /* for save */
4694 Int quotdigits; /* .. */
4696 bits=lhs->bits; /* remainder sign is always as lhs */
4698 /* Fastpath when residue is truly 0 is worthwhile [and */
4699 /* simplifies the code below] */
4700 if (*var1==0 && var1units==1) { /* residue is 0 */
4701 Int exp=lhs->exponent; /* save min(exponents) */
4702 if (rhs->exponent<exp) exp=rhs->exponent;
4703 uprv_decNumberZero(res); /* 0 coefficient */
4707 res->exponent=exp; /* .. with proper exponent */
4708 res->bits=(uByte)(bits&DECNEG); /* [cleaned] */
4709 decFinish(res, set, &residue, status); /* might clamp */
4712 /* note if the quotient was odd */
4713 if (*accnext & 0x01) wasodd=1; /* acc is odd */
4714 quotlsu=accnext; /* save in case need to reinspect */
4715 quotdigits=accdigits; /* .. */
4717 /* treat the residue, in var1, as the value to return, via acc */
4718 /* calculate the unused zero digits. This is the smaller of: */
4719 /* var1 initial padding (saved above) */
4720 /* var2 residual padding, which happens to be given by: */
4721 postshift=var1initpad+exponent-lhs->exponent+rhs->exponent;
4722 /* [the 'exponent' term accounts for the shifts during divide] */
4723 if (var1initpad<postshift) postshift=var1initpad;
4725 /* shift var1 the requested amount, and adjust its digits */
4726 var1units=decShiftToLeast(var1, var1units, postshift);
4728 accdigits=decGetDigits(var1, var1units);
4729 accunits=D2U(accdigits);
4731 exponent=lhs->exponent; /* exponent is smaller of lhs & rhs */
4732 if (rhs->exponent<exponent) exponent=rhs->exponent;
4734 /* Now correct the result if doing remainderNear; if it */
4735 /* (looking just at coefficients) is > rhs/2, or == rhs/2 and */
4736 /* the integer was odd then the result should be rem-rhs. */
4738 Int compare, tarunits; /* work */
4740 /* calculate remainder*2 into the var1 buffer (which has */
4741 /* 'headroom' of an extra unit and hence enough space) */
4742 /* [a dedicated 'double' loop would be faster, here] */
4743 tarunits=decUnitAddSub(accnext, accunits, accnext, accunits,
4745 /* decDumpAr('r', accnext, tarunits); */
4747 /* Here, accnext (var1) holds tarunits Units with twice the */
4748 /* remainder's coefficient, which must now be compared to the */
4749 /* RHS. The remainder's exponent may be smaller than the RHS's. */
4750 compare=decUnitCompare(accnext, tarunits, rhs->lsu, D2U(rhs->digits),
4751 rhs->exponent-exponent);
4752 if (compare==BADINT) { /* deep trouble */
4753 *status|=DEC_Insufficient_storage;
4756 /* now restore the remainder by dividing by two; the lsu */
4757 /* is known to be even. */
4758 for (up=accnext; up<accnext+tarunits; up++) {
4759 Int half; /* half to add to lower unit */
4761 *up/=2; /* [shift] */
4762 if (!half) continue;
4763 *(up-1)+=(DECDPUNMAX+1)/2;
4765 /* [accunits still describes the original remainder length] */
4767 if (compare>0 || (compare==0 && wasodd)) { /* adjustment needed */
4768 Int exp, expunits, exprem; /* work */
4769 /* This is effectively causing round-up of the quotient, */
4770 /* so if it was the rare case where it was full and all */
4771 /* nines, it would overflow and hence division-impossible */
4772 /* should be raised */
4773 Flag allnines=0; /* 1 if quotient all nines */
4774 if (quotdigits==reqdigits) { /* could be borderline */
4775 for (up=quotlsu; ; up++) {
4776 if (quotdigits>DECDPUN) {
4777 if (*up!=DECDPUNMAX) break;/* non-nines */
4779 else { /* this is the last Unit */
4780 if (*up==powers[quotdigits]-1) allnines=1;
4783 quotdigits-=DECDPUN; /* checked those digits */
4785 } /* borderline check */
4787 *status|=DEC_Division_impossible;
4790 /* rem-rhs is needed; the sign will invert. Again, var1 */
4791 /* can safely be used for the working Units array. */
4792 exp=rhs->exponent-exponent; /* RHS padding needed */
4793 /* Calculate units and remainder from exponent. */
4794 expunits=exp/DECDPUN;
4796 /* subtract [A+B*(-m)]; the result will always be negative */
4797 accunits=-decUnitAddSub(accnext, accunits,
4798 rhs->lsu, D2U(rhs->digits),
4799 expunits, accnext, -(Int)powers[exprem]);
4800 accdigits=decGetDigits(accnext, accunits); /* count digits exactly */
4801 accunits=D2U(accdigits); /* and recalculate the units for copy */
4802 /* [exponent is as for original remainder] */
4803 bits^=DECNEG; /* flip the sign */
4806 } /* REMAINDER or REMNEAR */
4809 /* Set exponent and bits */
4810 res->exponent=exponent;
4811 res->bits=(uByte)(bits&DECNEG); /* [cleaned] */
4813 /* Now the coefficient. */
4814 decSetCoeff(res, set, accnext, accdigits, &residue, status);
4816 decFinish(res, set, &residue, status); /* final cleanup */
4819 /* If a divide then strip trailing zeros if subset [after round] */
4820 if (!set->extended && (op==DIVIDE)) decTrim(res, set, 0, 1, &dropped);
4822 } while(0); /* end protected */
4824 if (varalloc!=NULL) free(varalloc); /* drop any storage used */
4825 if (allocacc!=NULL) free(allocacc); /* .. */
4827 if (allocrhs!=NULL) free(allocrhs); /* .. */
4828 if (alloclhs!=NULL) free(alloclhs); /* .. */
4833 /* ------------------------------------------------------------------ */
4834 /* decMultiplyOp -- multiplication operation */
4836 /* This routine performs the multiplication C=A x B. */
4838 /* res is C, the result. C may be A and/or B (e.g., X=X*X) */
4841 /* set is the context */
4842 /* status is the usual accumulator */
4844 /* C must have space for set->digits digits. */
4846 /* ------------------------------------------------------------------ */
4847 /* 'Classic' multiplication is used rather than Karatsuba, as the */
4848 /* latter would give only a minor improvement for the short numbers */
4849 /* expected to be handled most (and uses much more memory). */
4851 /* There are two major paths here: the general-purpose ('old code') */
4852 /* path which handles all DECDPUN values, and a fastpath version */
4853 /* which is used if 64-bit ints are available, DECDPUN<=4, and more */
4854 /* than two calls to decUnitAddSub would be made. */
4856 /* The fastpath version lumps units together into 8-digit or 9-digit */
4857 /* chunks, and also uses a lazy carry strategy to minimise expensive */
4858 /* 64-bit divisions. The chunks are then broken apart again into */
4859 /* units for continuing processing. Despite this overhead, the */
4860 /* fastpath can speed up some 16-digit operations by 10x (and much */
4861 /* more for higher-precision calculations). */
4863 /* A buffer always has to be used for the accumulator; in the */
4864 /* fastpath, buffers are also always needed for the chunked copies of */
4865 /* of the operand coefficients. */
4866 /* Static buffers are larger than needed just for multiply, to allow */
4867 /* for calls from other operations (notably exp). */
4868 /* ------------------------------------------------------------------ */
4869 #define FASTMUL (DECUSE64 && DECDPUN<5)
4870 static decNumber * decMultiplyOp(decNumber *res, const decNumber *lhs,
4871 const decNumber *rhs, decContext *set,
4873 Int accunits; /* Units of accumulator in use */
4874 Int exponent; /* work */
4875 Int residue=0; /* rounding residue */
4876 uByte bits; /* result sign */
4877 Unit *acc; /* -> accumulator Unit array */
4878 Int needbytes; /* size calculator */
4879 void *allocacc=NULL; /* -> allocated accumulator, iff allocated */
4880 Unit accbuff[SD2U(DECBUFFER*4+1)]; /* buffer (+1 for DECBUFFER==0, */
4881 /* *4 for calls from other operations) */
4882 const Unit *mer, *mermsup; /* work */
4883 Int madlength; /* Units in multiplicand */
4884 Int shift; /* Units to shift multiplicand by */
4887 /* if DECDPUN is 1 or 3 work in base 10**9, otherwise */
4888 /* (DECDPUN is 2 or 4) then work in base 10**8 */
4889 #if DECDPUN & 1 /* odd */
4890 #define FASTBASE 1000000000 /* base */
4891 #define FASTDIGS 9 /* digits in base */
4892 #define FASTLAZY 18 /* carry resolution point [1->18] */
4894 #define FASTBASE 100000000
4896 #define FASTLAZY 1844 /* carry resolution point [1->1844] */
4898 /* three buffers are used, two for chunked copies of the operands */
4899 /* (base 10**8 or base 10**9) and one base 2**64 accumulator with */
4900 /* lazy carry evaluation */
4901 uInt zlhibuff[(DECBUFFER*2+1)/8+1]; /* buffer (+1 for DECBUFFER==0) */
4902 uInt *zlhi=zlhibuff; /* -> lhs array */
4903 uInt *alloclhi=NULL; /* -> allocated buffer, iff allocated */
4904 uInt zrhibuff[(DECBUFFER*2+1)/8+1]; /* buffer (+1 for DECBUFFER==0) */
4905 uInt *zrhi=zrhibuff; /* -> rhs array */
4906 uInt *allocrhi=NULL; /* -> allocated buffer, iff allocated */
4907 uLong zaccbuff[(DECBUFFER*2+1)/4+2]; /* buffer (+1 for DECBUFFER==0) */
4908 /* [allocacc is shared for both paths, as only one will run] */
4909 uLong *zacc=zaccbuff; /* -> accumulator array for exact result */
4911 Int zoff; /* accumulator offset */
4913 uInt *lip, *rip; /* item pointers */
4914 uInt *lmsi, *rmsi; /* most significant items */
4915 Int ilhs, irhs, iacc; /* item counts in the arrays */
4916 Int lazy; /* lazy carry counter */
4917 uLong lcarry; /* uLong carry */
4918 uInt carry; /* carry (NB not uLong) */
4919 Int count; /* work */
4920 const Unit *cup; /* .. */
4927 decNumber *alloclhs=NULL; /* -> allocated buffer, iff allocated */
4928 decNumber *allocrhs=NULL; /* -> allocated buffer, iff allocated */
4932 if (decCheckOperands(res, lhs, rhs, set)) return res;
4935 /* precalculate result sign */
4936 bits=(uByte)((lhs->bits^rhs->bits)&DECNEG);
4938 /* handle infinities and NaNs */
4939 if (SPECIALARGS) { /* a special bit set */
4940 if (SPECIALARGS & (DECSNAN | DECNAN)) { /* one or two NaNs */
4941 decNaNs(res, lhs, rhs, set, status);
4943 /* one or two infinities; Infinity * 0 is invalid */
4944 if (((lhs->bits & DECINF)==0 && ISZERO(lhs))
4945 ||((rhs->bits & DECINF)==0 && ISZERO(rhs))) {
4946 *status|=DEC_Invalid_operation;
4948 uprv_decNumberZero(res);
4949 res->bits=bits|DECINF; /* infinity */
4952 /* For best speed, as in DMSRCN [the original Rexx numerics */
4953 /* module], use the shorter number as the multiplier (rhs) and */
4954 /* the longer as the multiplicand (lhs) to minimise the number of */
4955 /* adds (partial products) */
4956 if (lhs->digits<rhs->digits) { /* swap... */
4957 const decNumber *hold=lhs;
4962 do { /* protect allocated storage */
4964 if (!set->extended) {
4965 /* reduce operands and set lostDigits status, as needed */
4966 if (lhs->digits>set->digits) {
4967 alloclhs=decRoundOperand(lhs, set, status);
4968 if (alloclhs==NULL) break;
4971 if (rhs->digits>set->digits) {
4972 allocrhs=decRoundOperand(rhs, set, status);
4973 if (allocrhs==NULL) break;
4978 /* [following code does not require input rounding] */
4980 #if FASTMUL /* fastpath can be used */
4981 /* use the fast path if there are enough digits in the shorter */
4982 /* operand to make the setup and takedown worthwhile */
4983 #define NEEDTWO (DECDPUN*2) /* within two decUnitAddSub calls */
4984 if (rhs->digits>NEEDTWO) { /* use fastpath... */
4985 /* calculate the number of elements in each array */
4986 ilhs=(lhs->digits+FASTDIGS-1)/FASTDIGS; /* [ceiling] */
4987 irhs=(rhs->digits+FASTDIGS-1)/FASTDIGS; /* .. */
4990 /* allocate buffers if required, as usual */
4991 needbytes=ilhs*sizeof(uInt);
4992 if (needbytes>(Int)sizeof(zlhibuff)) {
4993 alloclhi=(uInt *)malloc(needbytes);
4995 needbytes=irhs*sizeof(uInt);
4996 if (needbytes>(Int)sizeof(zrhibuff)) {
4997 allocrhi=(uInt *)malloc(needbytes);
5000 /* Allocating the accumulator space needs a special case when */
5001 /* DECDPUN=1 because when converting the accumulator to Units */
5002 /* after the multiplication each 8-byte item becomes 9 1-byte */
5003 /* units. Therefore iacc extra bytes are needed at the front */
5004 /* (rounded up to a multiple of 8 bytes), and the uLong */
5005 /* accumulator starts offset the appropriate number of units */
5006 /* to the right to avoid overwrite during the unchunking. */
5008 /* Make sure no signed int overflow below. This is always true */
5009 /* if the given numbers have less digits than DEC_MAX_DIGITS. */
5010 U_ASSERT(iacc <= INT32_MAX/sizeof(uLong));
5011 needbytes=iacc*sizeof(uLong);
5013 zoff=(iacc+7)/8; /* items to offset by */
5016 if (needbytes>(Int)sizeof(zaccbuff)) {
5017 allocacc=(uLong *)malloc(needbytes);
5018 zacc=(uLong *)allocacc;}
5019 if (zlhi==NULL||zrhi==NULL||zacc==NULL) {
5020 *status|=DEC_Insufficient_storage;
5023 acc=(Unit *)zacc; /* -> target Unit array */
5025 zacc+=zoff; /* start uLong accumulator to right */
5028 /* assemble the chunked copies of the left and right sides */
5029 for (count=lhs->digits, cup=lhs->lsu, lip=zlhi; count>0; lip++)
5030 for (p=0, *lip=0; p<FASTDIGS && count>0;
5031 p+=DECDPUN, cup++, count-=DECDPUN)
5032 *lip+=*cup*powers[p];
5033 lmsi=lip-1; /* save -> msi */
5034 for (count=rhs->digits, cup=rhs->lsu, rip=zrhi; count>0; rip++)
5035 for (p=0, *rip=0; p<FASTDIGS && count>0;
5036 p+=DECDPUN, cup++, count-=DECDPUN)
5037 *rip+=*cup*powers[p];
5038 rmsi=rip-1; /* save -> msi */
5040 /* zero the accumulator */
5041 for (lp=zacc; lp<zacc+iacc; lp++) *lp=0;
5043 /* Start the multiplication */
5044 /* Resolving carries can dominate the cost of accumulating the */
5045 /* partial products, so this is only done when necessary. */
5046 /* Each uLong item in the accumulator can hold values up to */
5047 /* 2**64-1, and each partial product can be as large as */
5048 /* (10**FASTDIGS-1)**2. When FASTDIGS=9, this can be added to */
5049 /* itself 18.4 times in a uLong without overflowing, so during */
5050 /* the main calculation resolution is carried out every 18th */
5051 /* add -- every 162 digits. Similarly, when FASTDIGS=8, the */
5052 /* partial products can be added to themselves 1844.6 times in */
5053 /* a uLong without overflowing, so intermediate carry */
5054 /* resolution occurs only every 14752 digits. Hence for common */
5055 /* short numbers usually only the one final carry resolution */
5057 /* (The count is set via FASTLAZY to simplify experiments to */
5058 /* measure the value of this approach: a 35% improvement on a */
5059 /* [34x34] multiply.) */
5060 lazy=FASTLAZY; /* carry delay count */
5061 for (rip=zrhi; rip<=rmsi; rip++) { /* over each item in rhs */
5062 lp=zacc+(rip-zrhi); /* where to add the lhs */
5063 for (lip=zlhi; lip<=lmsi; lip++, lp++) { /* over each item in lhs */
5064 *lp+=(uLong)(*lip)*(*rip); /* [this should in-line] */
5067 if (lazy>0 && rip!=rmsi) continue;
5068 lazy=FASTLAZY; /* reset delay count */
5069 /* spin up the accumulator resolving overflows */
5070 for (lp=zacc; lp<zacc+iacc; lp++) {
5071 if (*lp<FASTBASE) continue; /* it fits */
5072 lcarry=*lp/FASTBASE; /* top part [slow divide] */
5073 /* lcarry can exceed 2**32-1, so check again; this check */
5074 /* and occasional extra divide (slow) is well worth it, as */
5075 /* it allows FASTLAZY to be increased to 18 rather than 4 */
5076 /* in the FASTDIGS=9 case */
5077 if (lcarry<FASTBASE) carry=(uInt)lcarry; /* [usual] */
5078 else { /* two-place carry [fairly rare] */
5079 uInt carry2=(uInt)(lcarry/FASTBASE); /* top top part */
5080 *(lp+2)+=carry2; /* add to item+2 */
5081 *lp-=((uLong)FASTBASE*FASTBASE*carry2); /* [slow] */
5082 carry=(uInt)(lcarry-((uLong)FASTBASE*carry2)); /* [inline] */
5084 *(lp+1)+=carry; /* add to item above [inline] */
5085 *lp-=((uLong)FASTBASE*carry); /* [inline] */
5086 } /* carry resolution */
5089 /* The multiplication is complete; time to convert back into */
5090 /* units. This can be done in-place in the accumulator and in */
5091 /* 32-bit operations, because carries were resolved after the */
5092 /* final add. This needs N-1 divides and multiplies for */
5093 /* each item in the accumulator (which will become up to N */
5094 /* units, where 2<=N<=9). */
5095 for (lp=zacc, up=acc; lp<zacc+iacc; lp++) {
5096 uInt item=(uInt)*lp; /* decapitate to uInt */
5097 for (p=0; p<FASTDIGS-DECDPUN; p+=DECDPUN, up++) {
5098 uInt part=item/(DECDPUNMAX+1);
5099 *up=(Unit)(item-(part*(DECDPUNMAX+1)));
5102 *up=(Unit)item; up++; /* [final needs no division] */
5104 accunits=up-acc; /* count of units */
5106 else { /* here to use units directly, without chunking ['old code'] */
5109 /* if accumulator will be too long for local storage, then allocate */
5110 acc=accbuff; /* -> assume buffer for accumulator */
5111 needbytes=(D2U(lhs->digits)+D2U(rhs->digits))*sizeof(Unit);
5112 if (needbytes>(Int)sizeof(accbuff)) {
5113 allocacc=(Unit *)malloc(needbytes);
5114 if (allocacc==NULL) {*status|=DEC_Insufficient_storage; break;}
5115 acc=(Unit *)allocacc; /* use the allocated space */
5118 /* Now the main long multiplication loop */
5119 /* Unlike the equivalent in the IBM Java implementation, there */
5120 /* is no advantage in calculating from msu to lsu. So, do it */
5121 /* by the book, as it were. */
5122 /* Each iteration calculates ACC=ACC+MULTAND*MULT */
5123 accunits=1; /* accumulator starts at '0' */
5124 *acc=0; /* .. (lsu=0) */
5125 shift=0; /* no multiplicand shift at first */
5126 madlength=D2U(lhs->digits); /* this won't change */
5127 mermsup=rhs->lsu+D2U(rhs->digits); /* -> msu+1 of multiplier */
5129 for (mer=rhs->lsu; mer<mermsup; mer++) {
5130 /* Here, *mer is the next Unit in the multiplier to use */
5131 /* If non-zero [optimization] add it... */
5132 if (*mer!=0) accunits=decUnitAddSub(&acc[shift], accunits-shift,
5133 lhs->lsu, madlength, 0,
5136 else { /* extend acc with a 0; it will be used shortly */
5137 *(acc+accunits)=0; /* [this avoids length of <=0 later] */
5140 /* multiply multiplicand by 10**DECDPUN for next Unit to left */
5141 shift++; /* add this for 'logical length' */
5144 } /* unchunked units */
5146 /* common end-path */
5148 decDumpAr('*', acc, accunits); /* Show exact result */
5151 /* acc now contains the exact result of the multiplication, */
5152 /* possibly with a leading zero unit; build the decNumber from */
5153 /* it, noting if any residue */
5154 res->bits=bits; /* set sign */
5155 res->digits=decGetDigits(acc, accunits); /* count digits exactly */
5157 /* There can be a 31-bit wrap in calculating the exponent. */
5158 /* This can only happen if both input exponents are negative and */
5159 /* both their magnitudes are large. If there was a wrap, set a */
5160 /* safe very negative exponent, from which decFinalize() will */
5161 /* raise a hard underflow shortly. */
5162 exponent=lhs->exponent+rhs->exponent; /* calculate exponent */
5163 if (lhs->exponent<0 && rhs->exponent<0 && exponent>0)
5164 exponent=-2*DECNUMMAXE; /* force underflow */
5165 res->exponent=exponent; /* OK to overwrite now */
5168 /* Set the coefficient. If any rounding, residue records */
5169 decSetCoeff(res, set, acc, res->digits, &residue, status);
5170 decFinish(res, set, &residue, status); /* final cleanup */
5171 } while(0); /* end protected */
5173 if (allocacc!=NULL) free(allocacc); /* drop any storage used */
5175 if (allocrhs!=NULL) free(allocrhs); /* .. */
5176 if (alloclhs!=NULL) free(alloclhs); /* .. */
5179 if (allocrhi!=NULL) free(allocrhi); /* .. */
5180 if (alloclhi!=NULL) free(alloclhi); /* .. */
5183 } /* decMultiplyOp */
5185 /* ------------------------------------------------------------------ */
5186 /* decExpOp -- effect exponentiation */
5188 /* This computes C = exp(A) */
5190 /* res is C, the result. C may be A */
5192 /* set is the context; note that rounding mode has no effect */
5194 /* C must have space for set->digits digits. status is updated but */
5199 /* digits, emax, and -emin in the context must be less than */
5200 /* 2*DEC_MAX_MATH (1999998), and the rhs must be within these */
5201 /* bounds or a zero. This is an internal routine, so these */
5202 /* restrictions are contractual and not enforced. */
5204 /* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will */
5205 /* almost always be correctly rounded, but may be up to 1 ulp in */
5206 /* error in rare cases. */
5208 /* Finite results will always be full precision and Inexact, except */
5209 /* when A is a zero or -Infinity (giving 1 or 0 respectively). */
5210 /* ------------------------------------------------------------------ */
5211 /* This approach used here is similar to the algorithm described in */
5213 /* Variable Precision Exponential Function, T. E. Hull and */
5214 /* A. Abrham, ACM Transactions on Mathematical Software, Vol 12 #2, */
5215 /* pp79-91, ACM, June 1986. */
5217 /* with the main difference being that the iterations in the series */
5218 /* evaluation are terminated dynamically (which does not require the */
5219 /* extra variable-precision variables which are expensive in this */
5222 /* The error analysis in Hull & Abrham's paper applies except for the */
5223 /* round-off error accumulation during the series evaluation. This */
5224 /* code does not precalculate the number of iterations and so cannot */
5225 /* use Horner's scheme. Instead, the accumulation is done at double- */
5226 /* precision, which ensures that the additions of the terms are exact */
5227 /* and do not accumulate round-off (and any round-off errors in the */
5228 /* terms themselves move 'to the right' faster than they can */
5229 /* accumulate). This code also extends the calculation by allowing, */
5230 /* in the spirit of other decNumber operators, the input to be more */
5231 /* precise than the result (the precision used is based on the more */
5232 /* precise of the input or requested result). */
5234 /* Implementation notes: */
5236 /* 1. This is separated out as decExpOp so it can be called from */
5237 /* other Mathematical functions (notably Ln) with a wider range */
5238 /* than normal. In particular, it can handle the slightly wider */
5239 /* (double) range needed by Ln (which has to be able to calculate */
5240 /* exp(-x) where x can be the tiniest number (Ntiny). */
5242 /* 2. Normalizing x to be <=0.1 (instead of <=1) reduces loop */
5243 /* iterations by appoximately a third with additional (although */
5244 /* diminishing) returns as the range is reduced to even smaller */
5245 /* fractions. However, h (the power of 10 used to correct the */
5246 /* result at the end, see below) must be kept <=8 as otherwise */
5247 /* the final result cannot be computed. Hence the leverage is a */
5248 /* sliding value (8-h), where potentially the range is reduced */
5249 /* more for smaller values. */
5251 /* The leverage that can be applied in this way is severely */
5252 /* limited by the cost of the raise-to-the power at the end, */
5253 /* which dominates when the number of iterations is small (less */
5254 /* than ten) or when rhs is short. As an example, the adjustment */
5255 /* x**10,000,000 needs 31 multiplications, all but one full-width. */
5257 /* 3. The restrictions (especially precision) could be raised with */
5258 /* care, but the full decNumber range seems very hard within the */
5259 /* 32-bit limits. */
5261 /* 4. The working precisions for the static buffers are twice the */
5262 /* obvious size to allow for calls from decNumberPower. */
5263 /* ------------------------------------------------------------------ */
5264 decNumber * decExpOp(decNumber *res, const decNumber *rhs,
5265 decContext *set, uInt *status) {
5266 uInt ignore=0; /* working status */
5267 Int h; /* adjusted exponent for 0.xxxx */
5268 Int p; /* working precision */
5269 Int residue; /* rounding residue */
5270 uInt needbytes; /* for space calculations */
5271 const decNumber *x=rhs; /* (may point to safe copy later) */
5272 decContext aset, tset, dset; /* working contexts */
5273 Int comp; /* work */
5275 /* the argument is often copied to normalize it, so (unusually) it */
5276 /* is treated like other buffers, using DECBUFFER, +1 in case */
5277 /* DECBUFFER is 0 */
5278 decNumber bufr[D2N(DECBUFFER*2+1)];
5279 decNumber *allocrhs=NULL; /* non-NULL if rhs buffer allocated */
5281 /* the working precision will be no more than set->digits+8+1 */
5282 /* so for on-stack buffers DECBUFFER+9 is used, +1 in case DECBUFFER */
5283 /* is 0 (and twice that for the accumulator) */
5285 /* buffer for t, term (working precision plus) */
5286 decNumber buft[D2N(DECBUFFER*2+9+1)];
5287 decNumber *allocbuft=NULL; /* -> allocated buft, iff allocated */
5288 decNumber *t=buft; /* term */
5289 /* buffer for a, accumulator (working precision * 2), at least 9 */
5290 decNumber bufa[D2N(DECBUFFER*4+18+1)];
5291 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
5292 decNumber *a=bufa; /* accumulator */
5293 /* decNumber for the divisor term; this needs at most 9 digits */
5294 /* and so can be fixed size [16 so can use standard context] */
5295 decNumber bufd[D2N(16)];
5296 decNumber *d=bufd; /* divisor */
5297 decNumber numone; /* constant 1 */
5300 Int iterations=0; /* for later sanity check */
5301 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
5304 do { /* protect allocated storage */
5305 if (SPECIALARG) { /* handle infinities and NaNs */
5306 if (decNumberIsInfinite(rhs)) { /* an infinity */
5307 if (decNumberIsNegative(rhs)) /* -Infinity -> +0 */
5308 uprv_decNumberZero(res);
5309 else uprv_decNumberCopy(res, rhs); /* +Infinity -> self */
5311 else decNaNs(res, rhs, NULL, set, status); /* a NaN */
5314 if (ISZERO(rhs)) { /* zeros -> exact 1 */
5315 uprv_decNumberZero(res); /* make clean 1 */
5316 *res->lsu=1; /* .. */
5317 break;} /* [no status to set] */
5319 /* e**x when 0 < x < 0.66 is < 1+3x/2, hence can fast-path */
5320 /* positive and negative tiny cases which will result in inexact */
5321 /* 1. This also allows the later add-accumulate to always be */
5322 /* exact (because its length will never be more than twice the */
5323 /* working precision). */
5324 /* The comparator (tiny) needs just one digit, so use the */
5325 /* decNumber d for it (reused as the divisor, etc., below); its */
5326 /* exponent is such that if x is positive it will have */
5327 /* set->digits-1 zeros between the decimal point and the digit, */
5328 /* which is 4, and if x is negative one more zero there as the */
5329 /* more precise result will be of the form 0.9999999 rather than */
5330 /* 1.0000001. Hence, tiny will be 0.0000004 if digits=7 and x>0 */
5331 /* or 0.00000004 if digits=7 and x<0. If RHS not larger than */
5332 /* this then the result will be 1.000000 */
5333 uprv_decNumberZero(d); /* clean */
5334 *d->lsu=4; /* set 4 .. */
5335 d->exponent=-set->digits; /* * 10**(-d) */
5336 if (decNumberIsNegative(rhs)) d->exponent--; /* negative case */
5337 comp=decCompare(d, rhs, 1); /* signless compare */
5339 *status|=DEC_Insufficient_storage;
5341 if (comp>=0) { /* rhs < d */
5342 Int shift=set->digits-1;
5343 uprv_decNumberZero(res); /* set 1 */
5344 *res->lsu=1; /* .. */
5345 res->digits=decShiftToMost(res->lsu, 1, shift);
5346 res->exponent=-shift; /* make 1.0000... */
5347 *status|=DEC_Inexact | DEC_Rounded; /* .. inexactly */
5350 /* set up the context to be used for calculating a, as this is */
5351 /* used on both paths below */
5352 uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64);
5353 /* accumulator bounds are as requested (could underflow) */
5354 aset.emax=set->emax; /* usual bounds */
5355 aset.emin=set->emin; /* .. */
5356 aset.clamp=0; /* and no concrete format */
5358 /* calculate the adjusted (Hull & Abrham) exponent (where the */
5359 /* decimal point is just to the left of the coefficient msd) */
5360 h=rhs->exponent+rhs->digits;
5361 /* if h>8 then 10**h cannot be calculated safely; however, when */
5362 /* h=8 then exp(|rhs|) will be at least exp(1E+7) which is at */
5363 /* least 6.59E+4342944, so (due to the restriction on Emax/Emin) */
5364 /* overflow (or underflow to 0) is guaranteed -- so this case can */
5365 /* be handled by simply forcing the appropriate excess */
5366 if (h>8) { /* overflow/underflow */
5367 /* set up here so Power call below will over or underflow to */
5368 /* zero; set accumulator to either 2 or 0.02 */
5369 /* [stack buffer for a is always big enough for this] */
5370 uprv_decNumberZero(a);
5371 *a->lsu=2; /* not 1 but < exp(1) */
5372 if (decNumberIsNegative(rhs)) a->exponent=-2; /* make 0.02 */
5373 h=8; /* clamp so 10**h computable */
5374 p=9; /* set a working precision */
5377 Int maxlever=(rhs->digits>8?1:0);
5378 /* [could/should increase this for precisions >40 or so, too] */
5380 /* if h is 8, cannot normalize to a lower upper limit because */
5381 /* the final result will not be computable (see notes above), */
5382 /* but leverage can be applied whenever h is less than 8. */
5383 /* Apply as much as possible, up to a MAXLEVER digits, which */
5384 /* sets the tradeoff against the cost of the later a**(10**h). */
5385 /* As h is increased, the working precision below also */
5386 /* increases to compensate for the "constant digits at the */
5387 /* front" effect. */
5388 Int lever=MINI(8-h, maxlever); /* leverage attainable */
5389 Int use=-rhs->digits-lever; /* exponent to use for RHS */
5390 h+=lever; /* apply leverage selected */
5391 if (h<0) { /* clamp */
5392 use+=h; /* [may end up subnormal] */
5395 /* Take a copy of RHS if it needs normalization (true whenever x>=1) */
5396 if (rhs->exponent!=use) {
5397 decNumber *newrhs=bufr; /* assume will fit on stack */
5398 needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
5399 if (needbytes>sizeof(bufr)) { /* need malloc space */
5400 allocrhs=(decNumber *)malloc(needbytes);
5401 if (allocrhs==NULL) { /* hopeless -- abandon */
5402 *status|=DEC_Insufficient_storage;
5404 newrhs=allocrhs; /* use the allocated space */
5406 uprv_decNumberCopy(newrhs, rhs); /* copy to safe space */
5407 newrhs->exponent=use; /* normalize; now <1 */
5408 x=newrhs; /* ready for use */
5409 /* decNumberShow(x); */
5412 /* Now use the usual power series to evaluate exp(x). The */
5413 /* series starts as 1 + x + x^2/2 ... so prime ready for the */
5414 /* third term by setting the term variable t=x, the accumulator */
5415 /* a=1, and the divisor d=2. */
5417 /* First determine the working precision. From Hull & Abrham */
5418 /* this is set->digits+h+2. However, if x is 'over-precise' we */
5419 /* need to allow for all its digits to potentially participate */
5420 /* (consider an x where all the excess digits are 9s) so in */
5421 /* this case use x->digits+h+2 */
5422 p=MAXI(x->digits, set->digits)+h+2; /* [h<=8] */
5424 /* a and t are variable precision, and depend on p, so space */
5425 /* must be allocated for them if necessary */
5427 /* the accumulator needs to be able to hold 2p digits so that */
5428 /* the additions on the second and subsequent iterations are */
5429 /* sufficiently exact. */
5430 needbytes=sizeof(decNumber)+(D2U(p*2)-1)*sizeof(Unit);
5431 if (needbytes>sizeof(bufa)) { /* need malloc space */
5432 allocbufa=(decNumber *)malloc(needbytes);
5433 if (allocbufa==NULL) { /* hopeless -- abandon */
5434 *status|=DEC_Insufficient_storage;
5436 a=allocbufa; /* use the allocated space */
5438 /* the term needs to be able to hold p digits (which is */
5439 /* guaranteed to be larger than x->digits, so the initial copy */
5440 /* is safe); it may also be used for the raise-to-power */
5441 /* calculation below, which needs an extra two digits */
5442 needbytes=sizeof(decNumber)+(D2U(p+2)-1)*sizeof(Unit);
5443 if (needbytes>sizeof(buft)) { /* need malloc space */
5444 allocbuft=(decNumber *)malloc(needbytes);
5445 if (allocbuft==NULL) { /* hopeless -- abandon */
5446 *status|=DEC_Insufficient_storage;
5448 t=allocbuft; /* use the allocated space */
5451 uprv_decNumberCopy(t, x); /* term=x */
5452 uprv_decNumberZero(a); *a->lsu=1; /* accumulator=1 */
5453 uprv_decNumberZero(d); *d->lsu=2; /* divisor=2 */
5454 uprv_decNumberZero(&numone); *numone.lsu=1; /* constant 1 for increment */
5456 /* set up the contexts for calculating a, t, and d */
5457 uprv_decContextDefault(&tset, DEC_INIT_DECIMAL64);
5459 /* accumulator bounds are set above, set precision now */
5460 aset.digits=p*2; /* double */
5461 /* term bounds avoid any underflow or overflow */
5463 tset.emin=DEC_MIN_EMIN; /* [emax is plenty] */
5464 /* [dset.digits=16, etc., are sufficient] */
5466 /* finally ready to roll */
5471 /* only the status from the accumulation is interesting */
5472 /* [but it should remain unchanged after first add] */
5473 decAddOp(a, a, t, &aset, 0, status); /* a=a+t */
5474 decMultiplyOp(t, t, x, &tset, &ignore); /* t=t*x */
5475 decDivideOp(t, t, d, &tset, DIVIDE, &ignore); /* t=t/d */
5476 /* the iteration ends when the term cannot affect the result, */
5477 /* if rounded to p digits, which is when its value is smaller */
5478 /* than the accumulator by p+1 digits. There must also be */
5479 /* full precision in a. */
5480 if (((a->digits+a->exponent)>=(t->digits+t->exponent+p+1))
5481 && (a->digits>=p)) break;
5482 decAddOp(d, d, &numone, &dset, 0, &ignore); /* d=d+1 */
5486 /* just a sanity check; comment out test to show always */
5488 printf("Exp iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
5489 (LI)iterations, (LI)*status, (LI)p, (LI)x->digits);
5493 /* apply postconditioning: a=a**(10**h) -- this is calculated */
5494 /* at a slightly higher precision than Hull & Abrham suggest */
5496 Int seenbit=0; /* set once a 1-bit is seen */
5497 Int i; /* counter */
5498 Int n=powers[h]; /* always positive */
5499 aset.digits=p+2; /* sufficient precision */
5500 /* avoid the overhead and many extra digits of decNumberPower */
5501 /* as all that is needed is the short 'multipliers' loop; here */
5502 /* accumulate the answer into t */
5503 uprv_decNumberZero(t); *t->lsu=1; /* acc=1 */
5504 for (i=1;;i++){ /* for each bit [top bit ignored] */
5505 /* abandon if have had overflow or terminal underflow */
5506 if (*status & (DEC_Overflow|DEC_Underflow)) { /* interesting? */
5507 if (*status&DEC_Overflow || ISZERO(t)) break;}
5508 n=n<<1; /* move next bit to testable position */
5509 if (n<0) { /* top bit is set */
5510 seenbit=1; /* OK, have a significant bit */
5511 decMultiplyOp(t, t, a, &aset, status); /* acc=acc*x */
5513 if (i==31) break; /* that was the last bit */
5514 if (!seenbit) continue; /* no need to square 1 */
5515 decMultiplyOp(t, t, t, &aset, status); /* acc=acc*acc [square] */
5516 } /*i*/ /* 32 bits */
5517 /* decNumberShow(t); */
5518 a=t; /* and carry on using t instead of a */
5521 /* Copy and round the result to res */
5522 residue=1; /* indicate dirt to right .. */
5523 if (ISZERO(a)) residue=0; /* .. unless underflowed to 0 */
5524 aset.digits=set->digits; /* [use default rounding] */
5525 decCopyFit(res, a, &aset, &residue, status); /* copy & shorten */
5526 decFinish(res, set, &residue, status); /* cleanup/set flags */
5527 } while(0); /* end protected */
5529 if (allocrhs !=NULL) free(allocrhs); /* drop any storage used */
5530 if (allocbufa!=NULL) free(allocbufa); /* .. */
5531 if (allocbuft!=NULL) free(allocbuft); /* .. */
5532 /* [status is handled by caller] */
5536 /* ------------------------------------------------------------------ */
5537 /* Initial-estimate natural logarithm table */
5539 /* LNnn -- 90-entry 16-bit table for values from .10 through .99. */
5540 /* The result is a 4-digit encode of the coefficient (c=the */
5541 /* top 14 bits encoding 0-9999) and a 2-digit encode of the */
5542 /* exponent (e=the bottom 2 bits encoding 0-3) */
5544 /* The resulting value is given by: */
5546 /* v = -c * 10**(-e-3) */
5548 /* where e and c are extracted from entry k = LNnn[x-10] */
5549 /* where x is truncated (NB) into the range 10 through 99, */
5550 /* and then c = k>>2 and e = k&3. */
5551 /* ------------------------------------------------------------------ */
5552 static const uShort LNnn[90]={9016, 8652, 8316, 8008, 7724, 7456, 7208,
5553 6972, 6748, 6540, 6340, 6148, 5968, 5792, 5628, 5464, 5312,
5554 5164, 5020, 4884, 4748, 4620, 4496, 4376, 4256, 4144, 4032,
5555 39233, 38181, 37157, 36157, 35181, 34229, 33297, 32389, 31501, 30629,
5556 29777, 28945, 28129, 27329, 26545, 25777, 25021, 24281, 23553, 22837,
5557 22137, 21445, 20769, 20101, 19445, 18801, 18165, 17541, 16925, 16321,
5558 15721, 15133, 14553, 13985, 13421, 12865, 12317, 11777, 11241, 10717,
5559 10197, 9685, 9177, 8677, 8185, 7697, 7213, 6737, 6269, 5801,
5560 5341, 4889, 4437, 39930, 35534, 31186, 26886, 22630, 18418, 14254,
5561 10130, 6046, 20055};
5563 /* ------------------------------------------------------------------ */
5564 /* decLnOp -- effect natural logarithm */
5566 /* This computes C = ln(A) */
5568 /* res is C, the result. C may be A */
5570 /* set is the context; note that rounding mode has no effect */
5572 /* C must have space for set->digits digits. */
5574 /* Notable cases: */
5575 /* A<0 -> Invalid */
5576 /* A=0 -> -Infinity (Exact) */
5577 /* A=+Infinity -> +Infinity (Exact) */
5578 /* A=1 exactly -> 0 (Exact) */
5580 /* Restrictions (as for Exp): */
5582 /* digits, emax, and -emin in the context must be less than */
5583 /* DEC_MAX_MATH+11 (1000010), and the rhs must be within these */
5584 /* bounds or a zero. This is an internal routine, so these */
5585 /* restrictions are contractual and not enforced. */
5587 /* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will */
5588 /* almost always be correctly rounded, but may be up to 1 ulp in */
5589 /* error in rare cases. */
5590 /* ------------------------------------------------------------------ */
5591 /* The result is calculated using Newton's method, with each */
5592 /* iteration calculating a' = a + x * exp(-a) - 1. See, for example, */
5593 /* Epperson 1989. */
5595 /* The iteration ends when the adjustment x*exp(-a)-1 is tiny enough. */
5596 /* This has to be calculated at the sum of the precision of x and the */
5597 /* working precision. */
5599 /* Implementation notes: */
5601 /* 1. This is separated out as decLnOp so it can be called from */
5602 /* other Mathematical functions (e.g., Log 10) with a wider range */
5603 /* than normal. In particular, it can handle the slightly wider */
5604 /* (+9+2) range needed by a power function. */
5606 /* 2. The speed of this function is about 10x slower than exp, as */
5607 /* it typically needs 4-6 iterations for short numbers, and the */
5608 /* extra precision needed adds a squaring effect, twice. */
5610 /* 3. Fastpaths are included for ln(10) and ln(2), up to length 40, */
5611 /* as these are common requests. ln(10) is used by log10(x). */
5613 /* 4. An iteration might be saved by widening the LNnn table, and */
5614 /* would certainly save at least one if it were made ten times */
5615 /* bigger, too (for truncated fractions 0.100 through 0.999). */
5616 /* However, for most practical evaluations, at least four or five */
5617 /* iterations will be neede -- so this would only speed up by */
5618 /* 20-25% and that probably does not justify increasing the table */
5621 /* 5. The static buffers are larger than might be expected to allow */
5622 /* for calls from decNumberPower. */
5623 /* ------------------------------------------------------------------ */
5624 #if defined(__clang__) || U_GCC_MAJOR_MINOR >= 406
5625 #pragma GCC diagnostic push
5626 #pragma GCC diagnostic ignored "-Warray-bounds"
5628 decNumber * decLnOp(decNumber *res, const decNumber *rhs,
5629 decContext *set, uInt *status) {
5630 uInt ignore=0; /* working status accumulator */
5631 uInt needbytes; /* for space calculations */
5632 Int residue; /* rounding residue */
5633 Int r; /* rhs=f*10**r [see below] */
5634 Int p; /* working precision */
5635 Int pp; /* precision for iteration */
5638 /* buffers for a (accumulator, typically precision+2) and b */
5639 /* (adjustment calculator, same size) */
5640 decNumber bufa[D2N(DECBUFFER+12)];
5641 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
5642 decNumber *a=bufa; /* accumulator/work */
5643 decNumber bufb[D2N(DECBUFFER*2+2)];
5644 decNumber *allocbufb=NULL; /* -> allocated bufa, iff allocated */
5645 decNumber *b=bufb; /* adjustment/work */
5647 decNumber numone; /* constant 1 */
5648 decNumber cmp; /* work */
5649 decContext aset, bset; /* working contexts */
5652 Int iterations=0; /* for later sanity check */
5653 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
5656 do { /* protect allocated storage */
5657 if (SPECIALARG) { /* handle infinities and NaNs */
5658 if (decNumberIsInfinite(rhs)) { /* an infinity */
5659 if (decNumberIsNegative(rhs)) /* -Infinity -> error */
5660 *status|=DEC_Invalid_operation;
5661 else uprv_decNumberCopy(res, rhs); /* +Infinity -> self */
5663 else decNaNs(res, rhs, NULL, set, status); /* a NaN */
5666 if (ISZERO(rhs)) { /* +/- zeros -> -Infinity */
5667 uprv_decNumberZero(res); /* make clean */
5668 res->bits=DECINF|DECNEG; /* set - infinity */
5669 break;} /* [no status to set] */
5671 /* Non-zero negatives are bad... */
5672 if (decNumberIsNegative(rhs)) { /* -x -> error */
5673 *status|=DEC_Invalid_operation;
5676 /* Here, rhs is positive, finite, and in range */
5678 /* lookaside fastpath code for ln(2) and ln(10) at common lengths */
5679 if (rhs->exponent==0 && set->digits<=40) {
5681 if (rhs->lsu[0]==0 && rhs->lsu[1]==1 && rhs->digits==2) { /* ln(10) */
5683 if (rhs->lsu[0]==10 && rhs->digits==2) { /* ln(10) */
5685 aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
5686 #define LN10 "2.302585092994045684017991454684364207601"
5687 uprv_decNumberFromString(res, LN10, &aset);
5688 *status|=(DEC_Inexact | DEC_Rounded); /* is inexact */
5690 if (rhs->lsu[0]==2 && rhs->digits==1) { /* ln(2) */
5691 aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
5692 #define LN2 "0.6931471805599453094172321214581765680755"
5693 uprv_decNumberFromString(res, LN2, &aset);
5694 *status|=(DEC_Inexact | DEC_Rounded);
5696 } /* integer and short */
5698 /* Determine the working precision. This is normally the */
5699 /* requested precision + 2, with a minimum of 9. However, if */
5700 /* the rhs is 'over-precise' then allow for all its digits to */
5701 /* potentially participate (consider an rhs where all the excess */
5702 /* digits are 9s) so in this case use rhs->digits+2. */
5703 p=MAXI(rhs->digits, MAXI(set->digits, 7))+2;
5705 /* Allocate space for the accumulator and the high-precision */
5706 /* adjustment calculator, if necessary. The accumulator must */
5707 /* be able to hold p digits, and the adjustment up to */
5708 /* rhs->digits+p digits. They are also made big enough for 16 */
5709 /* digits so that they can be used for calculating the initial */
5711 needbytes=sizeof(decNumber)+(D2U(MAXI(p,16))-1)*sizeof(Unit);
5712 if (needbytes>sizeof(bufa)) { /* need malloc space */
5713 allocbufa=(decNumber *)malloc(needbytes);
5714 if (allocbufa==NULL) { /* hopeless -- abandon */
5715 *status|=DEC_Insufficient_storage;
5717 a=allocbufa; /* use the allocated space */
5720 needbytes=sizeof(decNumber)+(D2U(MAXI(pp,16))-1)*sizeof(Unit);
5721 if (needbytes>sizeof(bufb)) { /* need malloc space */
5722 allocbufb=(decNumber *)malloc(needbytes);
5723 if (allocbufb==NULL) { /* hopeless -- abandon */
5724 *status|=DEC_Insufficient_storage;
5726 b=allocbufb; /* use the allocated space */
5729 /* Prepare an initial estimate in acc. Calculate this by */
5730 /* considering the coefficient of x to be a normalized fraction, */
5731 /* f, with the decimal point at far left and multiplied by */
5732 /* 10**r. Then, rhs=f*10**r and 0.1<=f<1, and */
5733 /* ln(x) = ln(f) + ln(10)*r */
5734 /* Get the initial estimate for ln(f) from a small lookup */
5735 /* table (see above) indexed by the first two digits of f, */
5738 uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64); /* 16-digit extended */
5739 r=rhs->exponent+rhs->digits; /* 'normalised' exponent */
5740 uprv_decNumberFromInt32(a, r); /* a=r */
5741 uprv_decNumberFromInt32(b, 2302585); /* b=ln(10) (2.302585) */
5742 b->exponent=-6; /* .. */
5743 decMultiplyOp(a, a, b, &aset, &ignore); /* a=a*b */
5744 /* now get top two digits of rhs into b by simple truncate and */
5745 /* force to integer */
5746 residue=0; /* (no residue) */
5747 aset.digits=2; aset.round=DEC_ROUND_DOWN;
5748 decCopyFit(b, rhs, &aset, &residue, &ignore); /* copy & shorten */
5749 b->exponent=0; /* make integer */
5750 t=decGetInt(b); /* [cannot fail] */
5751 if (t<10) t=X10(t); /* adjust single-digit b */
5752 t=LNnn[t-10]; /* look up ln(b) */
5753 uprv_decNumberFromInt32(b, t>>2); /* b=ln(b) coefficient */
5754 b->exponent=-(t&3)-3; /* set exponent */
5755 b->bits=DECNEG; /* ln(0.10)->ln(0.99) always -ve */
5756 aset.digits=16; aset.round=DEC_ROUND_HALF_EVEN; /* restore */
5757 decAddOp(a, a, b, &aset, 0, &ignore); /* acc=a+b */
5758 /* the initial estimate is now in a, with up to 4 digits correct. */
5759 /* When rhs is at or near Nmax the estimate will be low, so we */
5760 /* will approach it from below, avoiding overflow when calling exp. */
5762 uprv_decNumberZero(&numone); *numone.lsu=1; /* constant 1 for adjustment */
5764 /* accumulator bounds are as requested (could underflow, but */
5765 /* cannot overflow) */
5766 aset.emax=set->emax;
5767 aset.emin=set->emin;
5768 aset.clamp=0; /* no concrete format */
5769 /* set up a context to be used for the multiply and subtract */
5771 bset.emax=DEC_MAX_MATH*2; /* use double bounds for the */
5772 bset.emin=-DEC_MAX_MATH*2; /* adjustment calculation */
5773 /* [see decExpOp call below] */
5774 /* for each iteration double the number of digits to calculate, */
5775 /* up to a maximum of p */
5776 pp=9; /* initial precision */
5777 /* [initially 9 as then the sequence starts 7+2, 16+2, and */
5778 /* 34+2, which is ideal for standard-sized numbers] */
5779 aset.digits=pp; /* working context */
5780 bset.digits=pp+rhs->digits; /* wider context */
5781 for (;;) { /* iterate */
5784 if (iterations>24) break; /* consider 9 * 2**24 */
5786 /* calculate the adjustment (exp(-a)*x-1) into b. This is a */
5787 /* catastrophic subtraction but it really is the difference */
5788 /* from 1 that is of interest. */
5789 /* Use the internal entry point to Exp as it allows the double */
5790 /* range for calculating exp(-a) when a is the tiniest subnormal. */
5791 a->bits^=DECNEG; /* make -a */
5792 decExpOp(b, a, &bset, &ignore); /* b=exp(-a) */
5793 a->bits^=DECNEG; /* restore sign of a */
5794 /* now multiply by rhs and subtract 1, at the wider precision */
5795 decMultiplyOp(b, b, rhs, &bset, &ignore); /* b=b*rhs */
5796 decAddOp(b, b, &numone, &bset, DECNEG, &ignore); /* b=b-1 */
5798 /* the iteration ends when the adjustment cannot affect the */
5799 /* result by >=0.5 ulp (at the requested digits), which */
5800 /* is when its value is smaller than the accumulator by */
5801 /* set->digits+1 digits (or it is zero) -- this is a looser */
5802 /* requirement than for Exp because all that happens to the */
5803 /* accumulator after this is the final rounding (but note that */
5804 /* there must also be full precision in a, or a=0). */
5806 if (decNumberIsZero(b) ||
5807 (a->digits+a->exponent)>=(b->digits+b->exponent+set->digits+1)) {
5808 if (a->digits==p) break;
5809 if (decNumberIsZero(a)) {
5810 decCompareOp(&cmp, rhs, &numone, &aset, COMPARE, &ignore); /* rhs=1 ? */
5811 if (cmp.lsu[0]==0) a->exponent=0; /* yes, exact 0 */
5812 else *status|=(DEC_Inexact | DEC_Rounded); /* no, inexact */
5815 /* force padding if adjustment has gone to 0 before full length */
5816 if (decNumberIsZero(b)) b->exponent=a->exponent-p;
5819 /* not done yet ... */
5820 decAddOp(a, a, b, &aset, 0, &ignore); /* a=a+b for next estimate */
5821 if (pp==p) continue; /* precision is at maximum */
5822 /* lengthen the next calculation */
5823 pp=pp*2; /* double precision */
5824 if (pp>p) pp=p; /* clamp to maximum */
5825 aset.digits=pp; /* working context */
5826 bset.digits=pp+rhs->digits; /* wider context */
5827 } /* Newton's iteration */
5830 /* just a sanity check; remove the test to show always */
5832 printf("Ln iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
5833 (LI)iterations, (LI)*status, (LI)p, (LI)rhs->digits);
5836 /* Copy and round the result to res */
5837 residue=1; /* indicate dirt to right */
5838 if (ISZERO(a)) residue=0; /* .. unless underflowed to 0 */
5839 aset.digits=set->digits; /* [use default rounding] */
5840 decCopyFit(res, a, &aset, &residue, status); /* copy & shorten */
5841 decFinish(res, set, &residue, status); /* cleanup/set flags */
5842 } while(0); /* end protected */
5844 if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */
5845 if (allocbufb!=NULL) free(allocbufb); /* .. */
5846 /* [status is handled by caller] */
5849 #if defined(__clang__) || U_GCC_MAJOR_MINOR >= 406
5850 #pragma GCC diagnostic pop
5853 /* ------------------------------------------------------------------ */
5854 /* decQuantizeOp -- force exponent to requested value */
5856 /* This computes C = op(A, B), where op adjusts the coefficient */
5857 /* of C (by rounding or shifting) such that the exponent (-scale) */
5858 /* of C has the value B or matches the exponent of B. */
5859 /* The numerical value of C will equal A, except for the effects of */
5860 /* any rounding that occurred. */
5862 /* res is C, the result. C may be A or B */
5863 /* lhs is A, the number to adjust */
5864 /* rhs is B, the requested exponent */
5865 /* set is the context */
5866 /* quant is 1 for quantize or 0 for rescale */
5867 /* status is the status accumulator (this can be called without */
5868 /* risk of control loss) */
5870 /* C must have space for set->digits digits. */
5872 /* Unless there is an error or the result is infinite, the exponent */
5873 /* after the operation is guaranteed to be that requested. */
5874 /* ------------------------------------------------------------------ */
5875 static decNumber * decQuantizeOp(decNumber *res, const decNumber *lhs,
5876 const decNumber *rhs, decContext *set,
5877 Flag quant, uInt *status) {
5879 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */
5880 decNumber *allocrhs=NULL; /* .., rhs */
5882 const decNumber *inrhs=rhs; /* save original rhs */
5883 Int reqdigits=set->digits; /* requested DIGITS */
5884 Int reqexp; /* requested exponent [-scale] */
5885 Int residue=0; /* rounding residue */
5886 Int etiny=set->emin-(reqdigits-1);
5889 if (decCheckOperands(res, lhs, rhs, set)) return res;
5892 do { /* protect allocated storage */
5894 if (!set->extended) {
5895 /* reduce operands and set lostDigits status, as needed */
5896 if (lhs->digits>reqdigits) {
5897 alloclhs=decRoundOperand(lhs, set, status);
5898 if (alloclhs==NULL) break;
5901 if (rhs->digits>reqdigits) { /* [this only checks lostDigits] */
5902 allocrhs=decRoundOperand(rhs, set, status);
5903 if (allocrhs==NULL) break;
5908 /* [following code does not require input rounding] */
5910 /* Handle special values */
5912 /* NaNs get usual processing */
5913 if (SPECIALARGS & (DECSNAN | DECNAN))
5914 decNaNs(res, lhs, rhs, set, status);
5915 /* one infinity but not both is bad */
5916 else if ((lhs->bits ^ rhs->bits) & DECINF)
5917 *status|=DEC_Invalid_operation;
5918 /* both infinity: return lhs */
5919 else uprv_decNumberCopy(res, lhs); /* [nop if in place] */
5923 /* set requested exponent */
5924 if (quant) reqexp=inrhs->exponent; /* quantize -- match exponents */
5925 else { /* rescale -- use value of rhs */
5926 /* Original rhs must be an integer that fits and is in range, */
5927 /* which could be from -1999999997 to +999999999, thanks to */
5929 reqexp=decGetInt(inrhs); /* [cannot fail] */
5933 if (!set->extended) etiny=set->emin; /* no subnormals */
5936 if (reqexp==BADINT /* bad (rescale only) or .. */
5937 || reqexp==BIGODD || reqexp==BIGEVEN /* very big (ditto) or .. */
5938 || (reqexp<etiny) /* < lowest */
5939 || (reqexp>set->emax)) { /* > emax */
5940 *status|=DEC_Invalid_operation;
5943 /* the RHS has been processed, so it can be overwritten now if necessary */
5944 if (ISZERO(lhs)) { /* zero coefficient unchanged */
5945 uprv_decNumberCopy(res, lhs); /* [nop if in place] */
5946 res->exponent=reqexp; /* .. just set exponent */
5948 if (!set->extended) res->bits=0; /* subset specification; no -0 */
5951 else { /* non-zero lhs */
5952 Int adjust=reqexp-lhs->exponent; /* digit adjustment needed */
5953 /* if adjusted coefficient will definitely not fit, give up now */
5954 if ((lhs->digits-adjust)>reqdigits) {
5955 *status|=DEC_Invalid_operation;
5959 if (adjust>0) { /* increasing exponent */
5960 /* this will decrease the length of the coefficient by adjust */
5961 /* digits, and must round as it does so */
5962 decContext workset; /* work */
5963 workset=*set; /* clone rounding, etc. */
5964 workset.digits=lhs->digits-adjust; /* set requested length */
5965 /* [note that the latter can be <1, here] */
5966 decCopyFit(res, lhs, &workset, &residue, status); /* fit to result */
5967 decApplyRound(res, &workset, residue, status); /* .. and round */
5968 residue=0; /* [used] */
5969 /* If just rounded a 999s case, exponent will be off by one; */
5970 /* adjust back (after checking space), if so. */
5971 if (res->exponent>reqexp) {
5972 /* re-check needed, e.g., for quantize(0.9999, 0.001) under */
5973 /* set->digits==3 */
5974 if (res->digits==reqdigits) { /* cannot shift by 1 */
5975 *status&=~(DEC_Inexact | DEC_Rounded); /* [clean these] */
5976 *status|=DEC_Invalid_operation;
5979 res->digits=decShiftToMost(res->lsu, res->digits, 1); /* shift */
5980 res->exponent--; /* (re)adjust the exponent. */
5983 if (ISZERO(res) && !set->extended) res->bits=0; /* subset; no -0 */
5986 else /* adjust<=0 */ { /* decreasing or = exponent */
5987 /* this will increase the length of the coefficient by -adjust */
5988 /* digits, by adding zero or more trailing zeros; this is */
5989 /* already checked for fit, above */
5990 uprv_decNumberCopy(res, lhs); /* [it will fit] */
5991 /* if padding needed (adjust<0), add it now... */
5993 res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
5994 res->exponent+=adjust; /* adjust the exponent */
5999 /* Check for overflow [do not use Finalize in this case, as an */
6000 /* overflow here is a "don't fit" situation] */
6001 if (res->exponent>set->emax-res->digits+1) { /* too big */
6002 *status|=DEC_Invalid_operation;
6006 decFinalize(res, set, &residue, status); /* set subnormal flags */
6007 *status&=~DEC_Underflow; /* suppress Underflow [as per 754] */
6009 } while(0); /* end protected */
6012 if (allocrhs!=NULL) free(allocrhs); /* drop any storage used */
6013 if (alloclhs!=NULL) free(alloclhs); /* .. */
6016 } /* decQuantizeOp */
6018 /* ------------------------------------------------------------------ */
6019 /* decCompareOp -- compare, min, or max two Numbers */
6021 /* This computes C = A ? B and carries out one of four operations: */
6022 /* COMPARE -- returns the signum (as a number) giving the */
6023 /* result of a comparison unless one or both */
6024 /* operands is a NaN (in which case a NaN results) */
6025 /* COMPSIG -- as COMPARE except that a quiet NaN raises */
6026 /* Invalid operation. */
6027 /* COMPMAX -- returns the larger of the operands, using the */
6028 /* 754 maxnum operation */
6029 /* COMPMAXMAG -- ditto, comparing absolute values */
6030 /* COMPMIN -- the 754 minnum operation */
6031 /* COMPMINMAG -- ditto, comparing absolute values */
6032 /* COMTOTAL -- returns the signum (as a number) giving the */
6033 /* result of a comparison using 754 total ordering */
6035 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
6038 /* set is the context */
6039 /* op is the operation flag */
6040 /* status is the usual accumulator */
6042 /* C must have space for one digit for COMPARE or set->digits for */
6043 /* COMPMAX, COMPMIN, COMPMAXMAG, or COMPMINMAG. */
6044 /* ------------------------------------------------------------------ */
6045 /* The emphasis here is on speed for common cases, and avoiding */
6046 /* coefficient comparison if possible. */
6047 /* ------------------------------------------------------------------ */
6048 static decNumber * decCompareOp(decNumber *res, const decNumber *lhs,
6049 const decNumber *rhs, decContext *set,
6050 Flag op, uInt *status) {
6052 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */
6053 decNumber *allocrhs=NULL; /* .., rhs */
6055 Int result=0; /* default result value */
6056 uByte merged; /* work */
6059 if (decCheckOperands(res, lhs, rhs, set)) return res;
6062 do { /* protect allocated storage */
6064 if (!set->extended) {
6065 /* reduce operands and set lostDigits status, as needed */
6066 if (lhs->digits>set->digits) {
6067 alloclhs=decRoundOperand(lhs, set, status);
6068 if (alloclhs==NULL) {result=BADINT; break;}
6071 if (rhs->digits>set->digits) {
6072 allocrhs=decRoundOperand(rhs, set, status);
6073 if (allocrhs==NULL) {result=BADINT; break;}
6078 /* [following code does not require input rounding] */
6080 /* If total ordering then handle differing signs 'up front' */
6081 if (op==COMPTOTAL) { /* total ordering */
6082 if (decNumberIsNegative(lhs) && !decNumberIsNegative(rhs)) {
6086 if (!decNumberIsNegative(lhs) && decNumberIsNegative(rhs)) {
6092 /* handle NaNs specially; let infinities drop through */
6093 /* This assumes sNaN (even just one) leads to NaN. */
6094 merged=(lhs->bits | rhs->bits) & (DECSNAN | DECNAN);
6095 if (merged) { /* a NaN bit set */
6096 if (op==COMPARE); /* result will be NaN */
6097 else if (op==COMPSIG) /* treat qNaN as sNaN */
6098 *status|=DEC_Invalid_operation | DEC_sNaN;
6099 else if (op==COMPTOTAL) { /* total ordering, always finite */
6100 /* signs are known to be the same; compute the ordering here */
6101 /* as if the signs are both positive, then invert for negatives */
6102 if (!decNumberIsNaN(lhs)) result=-1;
6103 else if (!decNumberIsNaN(rhs)) result=+1;
6104 /* here if both NaNs */
6105 else if (decNumberIsSNaN(lhs) && decNumberIsQNaN(rhs)) result=-1;
6106 else if (decNumberIsQNaN(lhs) && decNumberIsSNaN(rhs)) result=+1;
6107 else { /* both NaN or both sNaN */
6108 /* now it just depends on the payload */
6109 result=decUnitCompare(lhs->lsu, D2U(lhs->digits),
6110 rhs->lsu, D2U(rhs->digits), 0);
6111 /* [Error not possible, as these are 'aligned'] */
6112 } /* both same NaNs */
6113 if (decNumberIsNegative(lhs)) result=-result;
6117 else if (merged & DECSNAN); /* sNaN -> qNaN */
6118 else { /* here if MIN or MAX and one or two quiet NaNs */
6119 /* min or max -- 754 rules ignore single NaN */
6120 if (!decNumberIsNaN(lhs) || !decNumberIsNaN(rhs)) {
6121 /* just one NaN; force choice to be the non-NaN operand */
6123 if (lhs->bits & DECNAN) result=-1; /* pick rhs */
6124 else result=+1; /* pick lhs */
6128 op=COMPNAN; /* use special path */
6129 decNaNs(res, lhs, rhs, set, status); /* propagate NaN */
6133 if (op==COMPMAXMAG || op==COMPMINMAG) result=decCompare(lhs, rhs, 1);
6134 else result=decCompare(lhs, rhs, 0); /* sign matters */
6135 } while(0); /* end protected */
6137 if (result==BADINT) *status|=DEC_Insufficient_storage; /* rare */
6139 if (op==COMPARE || op==COMPSIG ||op==COMPTOTAL) { /* returning signum */
6140 if (op==COMPTOTAL && result==0) {
6141 /* operands are numerically equal or same NaN (and same sign, */
6142 /* tested first); if identical, leave result 0 */
6143 if (lhs->exponent!=rhs->exponent) {
6144 if (lhs->exponent<rhs->exponent) result=-1;
6146 if (decNumberIsNegative(lhs)) result=-result;
6148 } /* total-order by exponent */
6149 uprv_decNumberZero(res); /* [always a valid result] */
6150 if (result!=0) { /* must be -1 or +1 */
6152 if (result<0) res->bits=DECNEG;
6155 else if (op==COMPNAN); /* special, drop through */
6156 else { /* MAX or MIN, non-NaN result */
6157 Int residue=0; /* rounding accumulator */
6158 /* choose the operand for the result */
6159 const decNumber *choice;
6160 if (result==0) { /* operands are numerically equal */
6161 /* choose according to sign then exponent (see 754) */
6162 uByte slhs=(lhs->bits & DECNEG);
6163 uByte srhs=(rhs->bits & DECNEG);
6165 if (!set->extended) { /* subset: force left-hand */
6171 if (slhs!=srhs) { /* signs differ */
6172 if (slhs) result=-1; /* rhs is max */
6173 else result=+1; /* lhs is max */
6175 else if (slhs && srhs) { /* both negative */
6176 if (lhs->exponent<rhs->exponent) result=+1;
6178 /* [if equal, use lhs, technically identical] */
6180 else { /* both positive */
6181 if (lhs->exponent>rhs->exponent) result=+1;
6185 } /* numerically equal */
6186 /* here result will be non-0; reverse if looking for MIN */
6187 if (op==COMPMIN || op==COMPMINMAG) result=-result;
6188 choice=(result>0 ? lhs : rhs); /* choose */
6189 /* copy chosen to result, rounding if need be */
6190 decCopyFit(res, choice, set, &residue, status);
6191 decFinish(res, set, &residue, status);
6195 if (allocrhs!=NULL) free(allocrhs); /* free any storage used */
6196 if (alloclhs!=NULL) free(alloclhs); /* .. */
6199 } /* decCompareOp */
6201 /* ------------------------------------------------------------------ */
6202 /* decCompare -- compare two decNumbers by numerical value */
6204 /* This routine compares A ? B without altering them. */
6206 /* Arg1 is A, a decNumber which is not a NaN */
6207 /* Arg2 is B, a decNumber which is not a NaN */
6208 /* Arg3 is 1 for a sign-independent compare, 0 otherwise */
6210 /* returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure */
6211 /* (the only possible failure is an allocation error) */
6212 /* ------------------------------------------------------------------ */
6213 static Int decCompare(const decNumber *lhs, const decNumber *rhs,
6215 Int result; /* result value */
6216 Int sigr; /* rhs signum */
6217 Int compare; /* work */
6219 result=1; /* assume signum(lhs) */
6220 if (ISZERO(lhs)) result=0;
6222 if (ISZERO(rhs)) return result; /* LHS wins or both 0 */
6223 /* RHS is non-zero */
6224 if (result==0) return -1; /* LHS is 0; RHS wins */
6225 /* [here, both non-zero, result=1] */
6227 else { /* signs matter */
6228 if (result && decNumberIsNegative(lhs)) result=-1;
6229 sigr=1; /* compute signum(rhs) */
6230 if (ISZERO(rhs)) sigr=0;
6231 else if (decNumberIsNegative(rhs)) sigr=-1;
6232 if (result > sigr) return +1; /* L > R, return 1 */
6233 if (result < sigr) return -1; /* L < R, return -1 */
6234 if (result==0) return 0; /* both 0 */
6237 /* signums are the same; both are non-zero */
6238 if ((lhs->bits | rhs->bits) & DECINF) { /* one or more infinities */
6239 if (decNumberIsInfinite(rhs)) {
6240 if (decNumberIsInfinite(lhs)) result=0;/* both infinite */
6241 else result=-result; /* only rhs infinite */
6245 /* must compare the coefficients, allowing for exponents */
6246 if (lhs->exponent>rhs->exponent) { /* LHS exponent larger */
6247 /* swap sides, and sign */
6248 const decNumber *temp=lhs;
6253 compare=decUnitCompare(lhs->lsu, D2U(lhs->digits),
6254 rhs->lsu, D2U(rhs->digits),
6255 rhs->exponent-lhs->exponent);
6256 if (compare!=BADINT) compare*=result; /* comparison succeeded */
6260 /* ------------------------------------------------------------------ */
6261 /* decUnitCompare -- compare two >=0 integers in Unit arrays */
6263 /* This routine compares A ? B*10**E where A and B are unit arrays */
6264 /* A is a plain integer */
6265 /* B has an exponent of E (which must be non-negative) */
6267 /* Arg1 is A first Unit (lsu) */
6268 /* Arg2 is A length in Units */
6269 /* Arg3 is B first Unit (lsu) */
6270 /* Arg4 is B length in Units */
6271 /* Arg5 is E (0 if the units are aligned) */
6273 /* returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure */
6274 /* (the only possible failure is an allocation error, which can */
6275 /* only occur if E!=0) */
6276 /* ------------------------------------------------------------------ */
6277 static Int decUnitCompare(const Unit *a, Int alength,
6278 const Unit *b, Int blength, Int exp) {
6279 Unit *acc; /* accumulator for result */
6280 Unit accbuff[SD2U(DECBUFFER*2+1)]; /* local buffer */
6281 Unit *allocacc=NULL; /* -> allocated acc buffer, iff allocated */
6282 Int accunits, need; /* units in use or needed for acc */
6283 const Unit *l, *r, *u; /* work */
6284 Int expunits, exprem, result; /* .. */
6286 if (exp==0) { /* aligned; fastpath */
6287 if (alength>blength) return 1;
6288 if (alength<blength) return -1;
6289 /* same number of units in both -- need unit-by-unit compare */
6292 for (;l>=a; l--, r--) {
6293 if (*l>*r) return 1;
6294 if (*l<*r) return -1;
6296 return 0; /* all units match */
6299 /* Unaligned. If one is >1 unit longer than the other, padded */
6300 /* approximately, then can return easily */
6301 if (alength>blength+(Int)D2U(exp)) return 1;
6302 if (alength+1<blength+(Int)D2U(exp)) return -1;
6304 /* Need to do a real subtract. For this, a result buffer is needed */
6305 /* even though only the sign is of interest. Its length needs */
6306 /* to be the larger of alength and padded blength, +2 */
6307 need=blength+D2U(exp); /* maximum real length of B */
6308 if (need<alength) need=alength;
6310 acc=accbuff; /* assume use local buffer */
6311 if (need*sizeof(Unit)>sizeof(accbuff)) {
6312 allocacc=(Unit *)malloc(need*sizeof(Unit));
6313 if (allocacc==NULL) return BADINT; /* hopeless -- abandon */
6316 /* Calculate units and remainder from exponent. */
6317 expunits=exp/DECDPUN;
6319 /* subtract [A+B*(-m)] */
6320 accunits=decUnitAddSub(a, alength, b, blength, expunits, acc,
6321 -(Int)powers[exprem]);
6322 /* [UnitAddSub result may have leading zeros, even on zero] */
6323 if (accunits<0) result=-1; /* negative result */
6324 else { /* non-negative result */
6325 /* check units of the result before freeing any storage */
6326 for (u=acc; u<acc+accunits-1 && *u==0;) u++;
6327 result=(*u==0 ? 0 : +1);
6329 /* clean up and return the result */
6330 if (allocacc!=NULL) free(allocacc); /* drop any storage used */
6332 } /* decUnitCompare */
6334 /* ------------------------------------------------------------------ */
6335 /* decUnitAddSub -- add or subtract two >=0 integers in Unit arrays */
6337 /* This routine performs the calculation: */
6341 /* Where M is in the range -DECDPUNMAX through +DECDPUNMAX. */
6343 /* A may be shorter or longer than B. */
6345 /* Leading zeros are not removed after a calculation. The result is */
6346 /* either the same length as the longer of A and B (adding any */
6347 /* shift), or one Unit longer than that (if a Unit carry occurred). */
6349 /* A and B content are not altered unless C is also A or B. */
6350 /* C may be the same array as A or B, but only if no zero padding is */
6351 /* requested (that is, C may be B only if bshift==0). */
6352 /* C is filled from the lsu; only those units necessary to complete */
6353 /* the calculation are referenced. */
6355 /* Arg1 is A first Unit (lsu) */
6356 /* Arg2 is A length in Units */
6357 /* Arg3 is B first Unit (lsu) */
6358 /* Arg4 is B length in Units */
6359 /* Arg5 is B shift in Units (>=0; pads with 0 units if positive) */
6360 /* Arg6 is C first Unit (lsu) */
6361 /* Arg7 is M, the multiplier */
6363 /* returns the count of Units written to C, which will be non-zero */
6364 /* and negated if the result is negative. That is, the sign of the */
6365 /* returned Int is the sign of the result (positive for zero) and */
6366 /* the absolute value of the Int is the count of Units. */
6368 /* It is the caller's responsibility to make sure that C size is */
6369 /* safe, allowing space if necessary for a one-Unit carry. */
6371 /* This routine is severely performance-critical; *any* change here */
6372 /* must be measured (timed) to assure no performance degradation. */
6373 /* In particular, trickery here tends to be counter-productive, as */
6374 /* increased complexity of code hurts register optimizations on */
6375 /* register-poor architectures. Avoiding divisions is nearly */
6376 /* always a Good Idea, however. */
6378 /* Special thanks to Rick McGuire (IBM Cambridge, MA) and Dave Clark */
6379 /* (IBM Warwick, UK) for some of the ideas used in this routine. */
6380 /* ------------------------------------------------------------------ */
6381 static Int decUnitAddSub(const Unit *a, Int alength,
6382 const Unit *b, Int blength, Int bshift,
6384 const Unit *alsu=a; /* A lsu [need to remember it] */
6385 Unit *clsu=c; /* C ditto */
6386 Unit *minC; /* low water mark for C */
6387 Unit *maxC; /* high water mark for C */
6388 eInt carry=0; /* carry integer (could be Long) */
6390 #if DECDPUN<=4 /* myriadal, millenary, etc. */
6391 Int est; /* estimated quotient */
6395 if (alength<1 || blength<1)
6396 printf("decUnitAddSub: alen blen m %ld %ld [%ld]\n", alength, blength, m);
6399 maxC=c+alength; /* A is usually the longer */
6400 minC=c+blength; /* .. and B the shorter */
6401 if (bshift!=0) { /* B is shifted; low As copy across */
6403 /* if in place [common], skip copy unless there's a gap [rare] */
6404 if (a==c && bshift<=alength) {
6408 else for (; c<clsu+bshift; a++, c++) { /* copy needed */
6409 if (a<alsu+alength) *c=*a;
6413 if (minC>maxC) { /* swap */
6419 /* For speed, do the addition as two loops; the first where both A */
6420 /* and B contribute, and the second (if necessary) where only one or */
6421 /* other of the numbers contribute. */
6422 /* Carry handling is the same (i.e., duplicated) in each case. */
6423 for (; c<minC; c++) {
6426 carry+=((eInt)*b)*m; /* [special-casing m=1/-1 */
6427 b++; /* here is not a win] */
6428 /* here carry is new Unit of digits; it could be +ve or -ve */
6429 if ((ueInt)carry<=DECDPUNMAX) { /* fastpath 0-DECDPUNMAX */
6434 #if DECDPUN==4 /* use divide-by-multiply */
6436 est=(((ueInt)carry>>11)*53687)>>18;
6437 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6438 carry=est; /* likely quotient [89%] */
6439 if (*c<DECDPUNMAX+1) continue; /* estimate was correct */
6445 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6446 est=(((ueInt)carry>>11)*53687)>>18;
6447 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6448 carry=est-(DECDPUNMAX+1); /* correctly negative */
6449 if (*c<DECDPUNMAX+1) continue; /* was OK */
6454 est=(((ueInt)carry>>3)*16777)>>21;
6455 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6456 carry=est; /* likely quotient [99%] */
6457 if (*c<DECDPUNMAX+1) continue; /* estimate was correct */
6463 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6464 est=(((ueInt)carry>>3)*16777)>>21;
6465 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6466 carry=est-(DECDPUNMAX+1); /* correctly negative */
6467 if (*c<DECDPUNMAX+1) continue; /* was OK */
6471 /* Can use QUOT10 as carry <= 4 digits */
6473 est=QUOT10(carry, DECDPUN);
6474 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6475 carry=est; /* quotient */
6479 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6480 est=QUOT10(carry, DECDPUN);
6481 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6482 carry=est-(DECDPUNMAX+1); /* correctly negative */
6484 /* remainder operator is undefined if negative, so must test */
6485 if ((ueInt)carry<(DECDPUNMAX+1)*2) { /* fastpath carry +1 */
6486 *c=(Unit)(carry-(DECDPUNMAX+1)); /* [helps additions] */
6491 *c=(Unit)(carry%(DECDPUNMAX+1));
6492 carry=carry/(DECDPUNMAX+1);
6496 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6497 *c=(Unit)(carry%(DECDPUNMAX+1));
6498 carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
6502 /* now may have one or other to complete */
6503 /* [pretest to avoid loop setup/shutdown] */
6504 if (c<maxC) for (; c<maxC; c++) {
6505 if (a<alsu+alength) { /* still in A */
6509 else { /* inside B */
6510 carry+=((eInt)*b)*m;
6513 /* here carry is new Unit of digits; it could be +ve or -ve and */
6514 /* magnitude up to DECDPUNMAX squared */
6515 if ((ueInt)carry<=DECDPUNMAX) { /* fastpath 0-DECDPUNMAX */
6520 /* result for this unit is negative or >DECDPUNMAX */
6521 #if DECDPUN==4 /* use divide-by-multiply */
6523 est=(((ueInt)carry>>11)*53687)>>18;
6524 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6525 carry=est; /* likely quotient [79.7%] */
6526 if (*c<DECDPUNMAX+1) continue; /* estimate was correct */
6532 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6533 est=(((ueInt)carry>>11)*53687)>>18;
6534 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6535 carry=est-(DECDPUNMAX+1); /* correctly negative */
6536 if (*c<DECDPUNMAX+1) continue; /* was OK */
6541 est=(((ueInt)carry>>3)*16777)>>21;
6542 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6543 carry=est; /* likely quotient [99%] */
6544 if (*c<DECDPUNMAX+1) continue; /* estimate was correct */
6550 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6551 est=(((ueInt)carry>>3)*16777)>>21;
6552 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6553 carry=est-(DECDPUNMAX+1); /* correctly negative */
6554 if (*c<DECDPUNMAX+1) continue; /* was OK */
6559 est=QUOT10(carry, DECDPUN);
6560 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6561 carry=est; /* quotient */
6565 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6566 est=QUOT10(carry, DECDPUN);
6567 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6568 carry=est-(DECDPUNMAX+1); /* correctly negative */
6570 if ((ueInt)carry<(DECDPUNMAX+1)*2){ /* fastpath carry 1 */
6571 *c=(Unit)(carry-(DECDPUNMAX+1));
6575 /* remainder operator is undefined if negative, so must test */
6577 *c=(Unit)(carry%(DECDPUNMAX+1));
6578 carry=carry/(DECDPUNMAX+1);
6582 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6583 *c=(Unit)(carry%(DECDPUNMAX+1));
6584 carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
6588 /* OK, all A and B processed; might still have carry or borrow */
6589 /* return number of Units in the result, negated if a borrow */
6590 if (carry==0) return c-clsu; /* no carry, so no more to do */
6591 if (carry>0) { /* positive carry */
6592 *c=(Unit)carry; /* place as new unit */
6596 /* -ve carry: it's a borrow; complement needed */
6597 add=1; /* temporary carry... */
6598 for (c=clsu; c<maxC; c++) {
6599 add=DECDPUNMAX+add-*c;
6600 if (add<=DECDPUNMAX) {
6609 /* add an extra unit iff it would be non-zero */
6611 printf("UAS borrow: add %ld, carry %ld\n", add, carry);
6613 if ((add-carry-1)!=0) {
6614 *c=(Unit)(add-carry-1);
6615 c++; /* interesting, include it */
6617 return clsu-c; /* -ve result indicates borrowed */
6618 } /* decUnitAddSub */
6620 /* ------------------------------------------------------------------ */
6621 /* decTrim -- trim trailing zeros or normalize */
6623 /* dn is the number to trim or normalize */
6624 /* set is the context to use to check for clamp */
6625 /* all is 1 to remove all trailing zeros, 0 for just fraction ones */
6626 /* noclamp is 1 to unconditional (unclamped) trim */
6627 /* dropped returns the number of discarded trailing zeros */
6630 /* If clamp is set in the context then the number of zeros trimmed */
6631 /* may be limited if the exponent is high. */
6632 /* All fields are updated as required. This is a utility operation, */
6633 /* so special values are unchanged and no error is possible. */
6634 /* ------------------------------------------------------------------ */
6635 static decNumber * decTrim(decNumber *dn, decContext *set, Flag all,
6636 Flag noclamp, Int *dropped) {
6637 Int d, exp; /* work */
6639 Unit *up; /* -> current Unit */
6642 if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
6645 *dropped=0; /* assume no zeros dropped */
6646 if ((dn->bits & DECSPECIAL) /* fast exit if special .. */
6647 || (*dn->lsu & 0x01)) return dn; /* .. or odd */
6648 if (ISZERO(dn)) { /* .. or 0 */
6649 dn->exponent=0; /* (sign is preserved) */
6653 /* have a finite number which is even */
6655 cut=1; /* digit (1-DECDPUN) in Unit */
6656 up=dn->lsu; /* -> current Unit */
6657 for (d=0; d<dn->digits-1; d++) { /* [don't strip the final digit] */
6658 /* slice by powers */
6660 uInt quot=QUOT10(*up, cut);
6661 if ((*up-quot*powers[cut])!=0) break; /* found non-0 digit */
6663 if (*up%powers[cut]!=0) break; /* found non-0 digit */
6665 /* have a trailing 0 */
6666 if (!all) { /* trimming */
6667 /* [if exp>0 then all trailing 0s are significant for trim] */
6668 if (exp<=0) { /* if digit might be significant */
6669 if (exp==0) break; /* then quit */
6670 exp++; /* next digit might be significant */
6673 cut++; /* next power */
6674 if (cut>DECDPUN) { /* need new Unit */
6679 if (d==0) return dn; /* none to drop */
6681 /* may need to limit drop if clamping */
6682 if (set->clamp && !noclamp) {
6683 Int maxd=set->emax-set->digits+1-dn->exponent;
6684 if (maxd<=0) return dn; /* nothing possible */
6688 /* effect the drop */
6689 decShiftToLeast(dn->lsu, D2U(dn->digits), d);
6690 dn->exponent+=d; /* maintain numerical value */
6691 dn->digits-=d; /* new length */
6692 *dropped=d; /* report the count */
6696 /* ------------------------------------------------------------------ */
6697 /* decReverse -- reverse a Unit array in place */
6699 /* ulo is the start of the array */
6700 /* uhi is the end of the array (highest Unit to include) */
6702 /* The units ulo through uhi are reversed in place (if the number */
6703 /* of units is odd, the middle one is untouched). Note that the */
6704 /* digit(s) in each unit are unaffected. */
6705 /* ------------------------------------------------------------------ */
6706 static void decReverse(Unit *ulo, Unit *uhi) {
6708 for (; ulo<uhi; ulo++, uhi--) {
6716 /* ------------------------------------------------------------------ */
6717 /* decShiftToMost -- shift digits in array towards most significant */
6719 /* uar is the array */
6720 /* digits is the count of digits in use in the array */
6721 /* shift is the number of zeros to pad with (least significant); */
6722 /* it must be zero or positive */
6724 /* returns the new length of the integer in the array, in digits */
6726 /* No overflow is permitted (that is, the uar array must be known to */
6727 /* be large enough to hold the result, after shifting). */
6728 /* ------------------------------------------------------------------ */
6729 static Int decShiftToMost(Unit *uar, Int digits, Int shift) {
6730 Unit *target, *source, *first; /* work */
6731 Int cut; /* odd 0's to add */
6732 uInt next; /* work */
6734 if (shift==0) return digits; /* [fastpath] nothing to do */
6735 if ((digits+shift)<=DECDPUN) { /* [fastpath] single-unit case */
6736 *uar=(Unit)(*uar*powers[shift]);
6737 return digits+shift;
6740 next=0; /* all paths */
6741 source=uar+D2U(digits)-1; /* where msu comes from */
6742 target=source+D2U(shift); /* where upper part of first cut goes */
6743 cut=DECDPUN-MSUDIGITS(shift); /* where to slice */
6744 if (cut==0) { /* unit-boundary case */
6745 for (; source>=uar; source--, target--) *target=*source;
6748 first=uar+D2U(digits+shift)-1; /* where msu of source will end up */
6749 for (; source>=uar; source--, target--) {
6750 /* split the source Unit and accumulate remainder for next */
6752 uInt quot=QUOT10(*source, cut);
6753 uInt rem=*source-quot*powers[cut];
6756 uInt rem=*source%powers[cut];
6757 next+=*source/powers[cut];
6759 if (target<=first) *target=(Unit)next; /* write to target iff valid */
6760 next=rem*powers[DECDPUN-cut]; /* save remainder for next Unit */
6764 /* propagate any partial unit to one below and clear the rest */
6765 for (; target>=uar; target--) {
6769 return digits+shift;
6770 } /* decShiftToMost */
6772 /* ------------------------------------------------------------------ */
6773 /* decShiftToLeast -- shift digits in array towards least significant */
6775 /* uar is the array */
6776 /* units is length of the array, in units */
6777 /* shift is the number of digits to remove from the lsu end; it */
6778 /* must be zero or positive and <= than units*DECDPUN. */
6780 /* returns the new length of the integer in the array, in units */
6782 /* Removed digits are discarded (lost). Units not required to hold */
6783 /* the final result are unchanged. */
6784 /* ------------------------------------------------------------------ */
6785 static Int decShiftToLeast(Unit *uar, Int units, Int shift) {
6786 Unit *target, *up; /* work */
6787 Int cut, count; /* work */
6788 Int quot, rem; /* for division */
6790 if (shift==0) return units; /* [fastpath] nothing to do */
6791 if (shift==units*DECDPUN) { /* [fastpath] little to do */
6792 *uar=0; /* all digits cleared gives zero */
6793 return 1; /* leaves just the one */
6796 target=uar; /* both paths */
6797 cut=MSUDIGITS(shift);
6798 if (cut==DECDPUN) { /* unit-boundary case; easy */
6800 for (; up<uar+units; target++, up++) *target=*up;
6805 up=uar+D2U(shift-cut); /* source; correct to whole Units */
6806 count=units*DECDPUN-shift; /* the maximum new length */
6808 quot=QUOT10(*up, cut);
6810 quot=*up/powers[cut];
6812 for (; ; target++) {
6814 count-=(DECDPUN-cut);
6815 if (count<=0) break;
6819 quot=QUOT10(quot, cut);
6820 rem=*up-quot*powers[cut];
6822 rem=quot%powers[cut];
6823 quot=quot/powers[cut];
6825 *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
6827 if (count<=0) break;
6829 return target-uar+1;
6830 } /* decShiftToLeast */
6833 /* ------------------------------------------------------------------ */
6834 /* decRoundOperand -- round an operand [used for subset only] */
6836 /* dn is the number to round (dn->digits is > set->digits) */
6837 /* set is the relevant context */
6838 /* status is the status accumulator */
6840 /* returns an allocated decNumber with the rounded result. */
6842 /* lostDigits and other status may be set by this. */
6844 /* Since the input is an operand, it must not be modified. */
6845 /* Instead, return an allocated decNumber, rounded as required. */
6846 /* It is the caller's responsibility to free the allocated storage. */
6848 /* If no storage is available then the result cannot be used, so NULL */
6850 /* ------------------------------------------------------------------ */
6851 static decNumber *decRoundOperand(const decNumber *dn, decContext *set,
6853 decNumber *res; /* result structure */
6854 uInt newstatus=0; /* status from round */
6855 Int residue=0; /* rounding accumulator */
6857 /* Allocate storage for the returned decNumber, big enough for the */
6858 /* length specified by the context */
6859 res=(decNumber *)malloc(sizeof(decNumber)
6860 +(D2U(set->digits)-1)*sizeof(Unit));
6862 *status|=DEC_Insufficient_storage;
6865 decCopyFit(res, dn, set, &residue, &newstatus);
6866 decApplyRound(res, set, residue, &newstatus);
6868 /* If that set Inexact then "lost digits" is raised... */
6869 if (newstatus & DEC_Inexact) newstatus|=DEC_Lost_digits;
6872 } /* decRoundOperand */
6875 /* ------------------------------------------------------------------ */
6876 /* decCopyFit -- copy a number, truncating the coefficient if needed */
6878 /* dest is the target decNumber */
6879 /* src is the source decNumber */
6880 /* set is the context [used for length (digits) and rounding mode] */
6881 /* residue is the residue accumulator */
6882 /* status contains the current status to be updated */
6884 /* (dest==src is allowed and will be a no-op if fits) */
6885 /* All fields are updated as required. */
6886 /* ------------------------------------------------------------------ */
6887 static void decCopyFit(decNumber *dest, const decNumber *src,
6888 decContext *set, Int *residue, uInt *status) {
6889 dest->bits=src->bits;
6890 dest->exponent=src->exponent;
6891 decSetCoeff(dest, set, src->lsu, src->digits, residue, status);
6894 /* ------------------------------------------------------------------ */
6895 /* decSetCoeff -- set the coefficient of a number */
6897 /* dn is the number whose coefficient array is to be set. */
6898 /* It must have space for set->digits digits */
6899 /* set is the context [for size] */
6900 /* lsu -> lsu of the source coefficient [may be dn->lsu] */
6901 /* len is digits in the source coefficient [may be dn->digits] */
6902 /* residue is the residue accumulator. This has values as in */
6903 /* decApplyRound, and will be unchanged unless the */
6904 /* target size is less than len. In this case, the */
6905 /* coefficient is truncated and the residue is updated to */
6906 /* reflect the previous residue and the dropped digits. */
6907 /* status is the status accumulator, as usual */
6909 /* The coefficient may already be in the number, or it can be an */
6910 /* external intermediate array. If it is in the number, lsu must == */
6911 /* dn->lsu and len must == dn->digits. */
6913 /* Note that the coefficient length (len) may be < set->digits, and */
6914 /* in this case this merely copies the coefficient (or is a no-op */
6915 /* if dn->lsu==lsu). */
6917 /* Note also that (only internally, from decQuantizeOp and */
6918 /* decSetSubnormal) the value of set->digits may be less than one, */
6919 /* indicating a round to left. This routine handles that case */
6920 /* correctly; caller ensures space. */
6922 /* dn->digits, dn->lsu (and as required), and dn->exponent are */
6923 /* updated as necessary. dn->bits (sign) is unchanged. */
6925 /* DEC_Rounded status is set if any digits are discarded. */
6926 /* DEC_Inexact status is set if any non-zero digits are discarded, or */
6927 /* incoming residue was non-0 (implies rounded) */
6928 /* ------------------------------------------------------------------ */
6929 /* mapping array: maps 0-9 to canonical residues, so that a residue */
6930 /* can be adjusted in the range [-1, +1] and achieve correct rounding */
6931 /* 0 1 2 3 4 5 6 7 8 9 */
6932 static const uByte resmap[10]={0, 3, 3, 3, 3, 5, 7, 7, 7, 7};
6933 static void decSetCoeff(decNumber *dn, decContext *set, const Unit *lsu,
6934 Int len, Int *residue, uInt *status) {
6935 Int discard; /* number of digits to discard */
6936 uInt cut; /* cut point in Unit */
6937 const Unit *up; /* work */
6938 Unit *target; /* .. */
6944 discard=len-set->digits; /* digits to discard */
6945 if (discard<=0) { /* no digits are being discarded */
6946 if (dn->lsu!=lsu) { /* copy needed */
6947 /* copy the coefficient array to the result number; no shift needed */
6948 count=len; /* avoids D2U */
6950 for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
6952 dn->digits=len; /* set the new length */
6954 /* dn->exponent and residue are unchanged, record any inexactitude */
6955 if (*residue!=0) *status|=(DEC_Inexact | DEC_Rounded);
6959 /* some digits must be discarded ... */
6960 dn->exponent+=discard; /* maintain numerical value */
6961 *status|=DEC_Rounded; /* accumulate Rounded status */
6962 if (*residue>1) *residue=1; /* previous residue now to right, so reduce */
6964 if (discard>len) { /* everything, +1, is being discarded */
6965 /* guard digit is 0 */
6966 /* residue is all the number [NB could be all 0s] */
6967 if (*residue<=0) { /* not already positive */
6968 count=len; /* avoids D2U */
6969 for (up=lsu; count>0; up++, count-=DECDPUN) if (*up!=0) { /* found non-0 */
6971 break; /* no need to check any others */
6974 if (*residue!=0) *status|=DEC_Inexact; /* record inexactitude */
6975 *dn->lsu=0; /* coefficient will now be 0 */
6976 dn->digits=1; /* .. */
6978 } /* total discard */
6980 /* partial discard [most common case] */
6981 /* here, at least the first (most significant) discarded digit exists */
6983 /* spin up the number, noting residue during the spin, until get to */
6984 /* the Unit with the first discarded digit. When reach it, extract */
6985 /* it and remember its position */
6987 for (up=lsu;; up++) {
6989 if (count>=discard) break; /* full ones all checked */
6990 if (*up!=0) *residue=1;
6993 /* here up -> Unit with first discarded digit */
6994 cut=discard-(count-DECDPUN)-1;
6995 if (cut==DECDPUN-1) { /* unit-boundary case (fast) */
6996 Unit half=(Unit)powers[DECDPUN]>>1;
6997 /* set residue directly */
6999 if (*up>half) *residue=7;
7000 else *residue+=5; /* add sticky bit */
7003 if (*up!=0) *residue=3; /* [else is 0, leave as sticky bit] */
7005 if (set->digits<=0) { /* special for Quantize/Subnormal :-( */
7006 *dn->lsu=0; /* .. result is 0 */
7007 dn->digits=1; /* .. */
7009 else { /* shift to least */
7010 count=set->digits; /* now digits to end up with */
7011 dn->digits=count; /* set the new length */
7012 up++; /* move to next */
7013 /* on unit boundary, so shift-down copy loop is simple */
7014 for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
7017 } /* unit-boundary case */
7019 else { /* discard digit is in low digit(s), and not top digit */
7020 uInt discard1; /* first discarded digit */
7021 uInt quot, rem; /* for divisions */
7022 if (cut==0) quot=*up; /* is at bottom of unit */
7023 else /* cut>0 */ { /* it's not at bottom of unit */
7025 U_ASSERT(/* cut >= 0 &&*/ cut <= 4);
7026 quot=QUOT10(*up, cut);
7027 rem=*up-quot*powers[cut];
7029 rem=*up%powers[cut];
7030 quot=*up/powers[cut];
7032 if (rem!=0) *residue=1;
7034 /* discard digit is now at bottom of quot */
7036 temp=(quot*6554)>>16; /* fast /10 */
7037 /* Vowels algorithm here not a win (9 instructions) */
7038 discard1=quot-X10(temp);
7044 /* here, discard1 is the guard digit, and residue is everything */
7045 /* else [use mapping array to accumulate residue safely] */
7046 *residue+=resmap[discard1];
7047 cut++; /* update cut */
7048 /* here: up -> Unit of the array with bottom digit */
7049 /* cut is the division point for each Unit */
7050 /* quot holds the uncut high-order digits for the current unit */
7051 if (set->digits<=0) { /* special for Quantize/Subnormal :-( */
7052 *dn->lsu=0; /* .. result is 0 */
7053 dn->digits=1; /* .. */
7055 else { /* shift to least needed */
7056 count=set->digits; /* now digits to end up with */
7057 dn->digits=count; /* set the new length */
7058 /* shift-copy the coefficient array to the result number */
7059 for (target=dn->lsu; ; target++) {
7061 count-=(DECDPUN-cut);
7062 if (count<=0) break;
7066 quot=QUOT10(quot, cut);
7067 rem=*up-quot*powers[cut];
7069 rem=quot%powers[cut];
7070 quot=quot/powers[cut];
7072 *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
7074 if (count<=0) break;
7075 } /* shift-copy loop */
7076 } /* shift to least */
7077 } /* not unit boundary */
7079 if (*residue!=0) *status|=DEC_Inexact; /* record inexactitude */
7083 /* ------------------------------------------------------------------ */
7084 /* decApplyRound -- apply pending rounding to a number */
7086 /* dn is the number, with space for set->digits digits */
7087 /* set is the context [for size and rounding mode] */
7088 /* residue indicates pending rounding, being any accumulated */
7089 /* guard and sticky information. It may be: */
7090 /* 6-9: rounding digit is >5 */
7091 /* 5: rounding digit is exactly half-way */
7092 /* 1-4: rounding digit is <5 and >0 */
7093 /* 0: the coefficient is exact */
7094 /* -1: as 1, but the hidden digits are subtractive, that */
7095 /* is, of the opposite sign to dn. In this case the */
7096 /* coefficient must be non-0. This case occurs when */
7097 /* subtracting a small number (which can be reduced to */
7098 /* a sticky bit); see decAddOp. */
7099 /* status is the status accumulator, as usual */
7101 /* This routine applies rounding while keeping the length of the */
7102 /* coefficient constant. The exponent and status are unchanged */
7105 /* -- the coefficient was increased and is all nines (in which */
7106 /* case Overflow could occur, and is handled directly here so */
7107 /* the caller does not need to re-test for overflow) */
7109 /* -- the coefficient was decreased and becomes all nines (in which */
7110 /* case Underflow could occur, and is also handled directly). */
7112 /* All fields in dn are updated as required. */
7114 /* ------------------------------------------------------------------ */
7115 static void decApplyRound(decNumber *dn, decContext *set, Int residue,
7117 Int bump; /* 1 if coefficient needs to be incremented */
7118 /* -1 if coefficient needs to be decremented */
7120 if (residue==0) return; /* nothing to apply */
7122 bump=0; /* assume a smooth ride */
7124 /* now decide whether, and how, to round, depending on mode */
7125 switch (set->round) {
7126 case DEC_ROUND_05UP: { /* round zero or five up (for reround) */
7127 /* This is the same as DEC_ROUND_DOWN unless there is a */
7128 /* positive residue and the lsd of dn is 0 or 5, in which case */
7129 /* it is bumped; when residue is <0, the number is therefore */
7130 /* bumped down unless the final digit was 1 or 6 (in which */
7131 /* case it is bumped down and then up -- a no-op) */
7132 Int lsd5=*dn->lsu%5; /* get lsd and quintate */
7133 if (residue<0 && lsd5!=1) bump=-1;
7134 else if (residue>0 && lsd5==0) bump=1;
7135 /* [bump==1 could be applied directly; use common path for clarity] */
7138 case DEC_ROUND_DOWN: {
7139 /* no change, except if negative residue */
7140 if (residue<0) bump=-1;
7143 case DEC_ROUND_HALF_DOWN: {
7144 if (residue>5) bump=1;
7147 case DEC_ROUND_HALF_EVEN: {
7148 if (residue>5) bump=1; /* >0.5 goes up */
7149 else if (residue==5) { /* exactly 0.5000... */
7150 /* 0.5 goes up iff [new] lsd is odd */
7151 if (*dn->lsu & 0x01) bump=1;
7155 case DEC_ROUND_HALF_UP: {
7156 if (residue>=5) bump=1;
7159 case DEC_ROUND_UP: {
7160 if (residue>0) bump=1;
7163 case DEC_ROUND_CEILING: {
7164 /* same as _UP for positive numbers, and as _DOWN for negatives */
7165 /* [negative residue cannot occur on 0] */
7166 if (decNumberIsNegative(dn)) {
7167 if (residue<0) bump=-1;
7170 if (residue>0) bump=1;
7174 case DEC_ROUND_FLOOR: {
7175 /* same as _UP for negative numbers, and as _DOWN for positive */
7176 /* [negative residue cannot occur on 0] */
7177 if (!decNumberIsNegative(dn)) {
7178 if (residue<0) bump=-1;
7181 if (residue>0) bump=1;
7185 default: { /* e.g., DEC_ROUND_MAX */
7186 *status|=DEC_Invalid_context;
7187 #if DECTRACE || (DECCHECK && DECVERB)
7188 printf("Unknown rounding mode: %d\n", set->round);
7193 /* now bump the number, up or down, if need be */
7194 if (bump==0) return; /* no action required */
7196 /* Simply use decUnitAddSub unless bumping up and the number is */
7197 /* all nines. In this special case set to 100... explicitly */
7198 /* and adjust the exponent by one (as otherwise could overflow */
7200 /* Similarly handle all-nines result if bumping down. */
7202 Unit *up; /* work */
7203 uInt count=dn->digits; /* digits to be checked */
7204 for (up=dn->lsu; ; up++) {
7205 if (count<=DECDPUN) {
7206 /* this is the last Unit (the msu) */
7207 if (*up!=powers[count]-1) break; /* not still 9s */
7208 /* here if it, too, is all nines */
7209 *up=(Unit)powers[count-1]; /* here 999 -> 100 etc. */
7210 for (up=up-1; up>=dn->lsu; up--) *up=0; /* others all to 0 */
7211 dn->exponent++; /* and bump exponent */
7212 /* [which, very rarely, could cause Overflow...] */
7213 if ((dn->exponent+dn->digits)>set->emax+1) {
7214 decSetOverflow(dn, set, status);
7218 /* a full unit to check, with more to come */
7219 if (*up!=DECDPUNMAX) break; /* not still 9s */
7224 /* here checking for a pre-bump of 1000... (leading 1, all */
7225 /* other digits zero) */
7226 Unit *up, *sup; /* work */
7227 uInt count=dn->digits; /* digits to be checked */
7228 for (up=dn->lsu; ; up++) {
7229 if (count<=DECDPUN) {
7230 /* this is the last Unit (the msu) */
7231 if (*up!=powers[count-1]) break; /* not 100.. */
7232 /* here if have the 1000... case */
7233 sup=up; /* save msu pointer */
7234 *up=(Unit)powers[count]-1; /* here 100 in msu -> 999 */
7235 /* others all to all-nines, too */
7236 for (up=up-1; up>=dn->lsu; up--) *up=(Unit)powers[DECDPUN]-1;
7237 dn->exponent--; /* and bump exponent */
7239 /* iff the number was at the subnormal boundary (exponent=etiny) */
7240 /* then the exponent is now out of range, so it will in fact get */
7241 /* clamped to etiny and the final 9 dropped. */
7242 /* printf(">> emin=%d exp=%d sdig=%d\n", set->emin, */
7243 /* dn->exponent, set->digits); */
7244 if (dn->exponent+1==set->emin-set->digits+1) {
7245 if (count==1 && dn->digits==1) *sup=0; /* here 9 -> 0[.9] */
7247 *sup=(Unit)powers[count-1]-1; /* here 999.. in msu -> 99.. */
7251 *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
7256 /* a full unit to check, with more to come */
7257 if (*up!=0) break; /* not still 0s */
7263 /* Actual bump needed. Do it. */
7264 decUnitAddSub(dn->lsu, D2U(dn->digits), uarrone, 1, 0, dn->lsu, bump);
7265 } /* decApplyRound */
7268 /* ------------------------------------------------------------------ */
7269 /* decFinish -- finish processing a number */
7271 /* dn is the number */
7272 /* set is the context */
7273 /* residue is the rounding accumulator (as in decApplyRound) */
7274 /* status is the accumulator */
7276 /* This finishes off the current number by: */
7277 /* 1. If not extended: */
7278 /* a. Converting a zero result to clean '0' */
7279 /* b. Reducing positive exponents to 0, if would fit in digits */
7280 /* 2. Checking for overflow and subnormals (always) */
7281 /* Note this is just Finalize when no subset arithmetic. */
7282 /* All fields are updated as required. */
7283 /* ------------------------------------------------------------------ */
7284 static void decFinish(decNumber *dn, decContext *set, Int *residue,
7286 if (!set->extended) {
7287 if ISZERO(dn) { /* value is zero */
7288 dn->exponent=0; /* clean exponent .. */
7289 dn->bits=0; /* .. and sign */
7290 return; /* no error possible */
7292 if (dn->exponent>=0) { /* non-negative exponent */
7293 /* >0; reduce to integer if possible */
7294 if (set->digits >= (dn->exponent+dn->digits)) {
7295 dn->digits=decShiftToMost(dn->lsu, dn->digits, dn->exponent);
7301 decFinalize(dn, set, residue, status);
7305 /* ------------------------------------------------------------------ */
7306 /* decFinalize -- final check, clamp, and round of a number */
7308 /* dn is the number */
7309 /* set is the context */
7310 /* residue is the rounding accumulator (as in decApplyRound) */
7311 /* status is the status accumulator */
7313 /* This finishes off the current number by checking for subnormal */
7314 /* results, applying any pending rounding, checking for overflow, */
7315 /* and applying any clamping. */
7316 /* Underflow and overflow conditions are raised as appropriate. */
7317 /* All fields are updated as required. */
7318 /* ------------------------------------------------------------------ */
7319 static void decFinalize(decNumber *dn, decContext *set, Int *residue,
7321 Int shift; /* shift needed if clamping */
7322 Int tinyexp=set->emin-dn->digits+1; /* precalculate subnormal boundary */
7324 /* Must be careful, here, when checking the exponent as the */
7325 /* adjusted exponent could overflow 31 bits [because it may already */
7326 /* be up to twice the expected]. */
7328 /* First test for subnormal. This must be done before any final */
7329 /* round as the result could be rounded to Nmin or 0. */
7330 if (dn->exponent<=tinyexp) { /* prefilter */
7333 /* A very nasty case here is dn == Nmin and residue<0 */
7334 if (dn->exponent<tinyexp) {
7335 /* Go handle subnormals; this will apply round if needed. */
7336 decSetSubnormal(dn, set, residue, status);
7339 /* Equals case: only subnormal if dn=Nmin and negative residue */
7340 uprv_decNumberZero(&nmin);
7342 nmin.exponent=set->emin;
7343 comp=decCompare(dn, &nmin, 1); /* (signless compare) */
7344 if (comp==BADINT) { /* oops */
7345 *status|=DEC_Insufficient_storage; /* abandon... */
7348 if (*residue<0 && comp==0) { /* neg residue and dn==Nmin */
7349 decApplyRound(dn, set, *residue, status); /* might force down */
7350 decSetSubnormal(dn, set, residue, status);
7355 /* now apply any pending round (this could raise overflow). */
7356 if (*residue!=0) decApplyRound(dn, set, *residue, status);
7358 /* Check for overflow [redundant in the 'rare' case] or clamp */
7359 if (dn->exponent<=set->emax-set->digits+1) return; /* neither needed */
7362 /* here when might have an overflow or clamp to do */
7363 if (dn->exponent>set->emax-dn->digits+1) { /* too big */
7364 decSetOverflow(dn, set, status);
7367 /* here when the result is normal but in clamp range */
7368 if (!set->clamp) return;
7370 /* here when need to apply the IEEE exponent clamp (fold-down) */
7371 shift=dn->exponent-(set->emax-set->digits+1);
7373 /* shift coefficient (if non-zero) */
7375 dn->digits=decShiftToMost(dn->lsu, dn->digits, shift);
7377 dn->exponent-=shift; /* adjust the exponent to match */
7378 *status|=DEC_Clamped; /* and record the dirty deed */
7382 /* ------------------------------------------------------------------ */
7383 /* decSetOverflow -- set number to proper overflow value */
7385 /* dn is the number (used for sign [only] and result) */
7386 /* set is the context [used for the rounding mode, etc.] */
7387 /* status contains the current status to be updated */
7389 /* This sets the sign of a number and sets its value to either */
7390 /* Infinity or the maximum finite value, depending on the sign of */
7391 /* dn and the rounding mode, following IEEE 754 rules. */
7392 /* ------------------------------------------------------------------ */
7393 static void decSetOverflow(decNumber *dn, decContext *set, uInt *status) {
7394 Flag needmax=0; /* result is maximum finite value */
7395 uByte sign=dn->bits&DECNEG; /* clean and save sign bit */
7397 if (ISZERO(dn)) { /* zero does not overflow magnitude */
7398 Int emax=set->emax; /* limit value */
7399 if (set->clamp) emax-=set->digits-1; /* lower if clamping */
7400 if (dn->exponent>emax) { /* clamp required */
7402 *status|=DEC_Clamped;
7407 uprv_decNumberZero(dn);
7408 switch (set->round) {
7409 case DEC_ROUND_DOWN: {
7410 needmax=1; /* never Infinity */
7412 case DEC_ROUND_05UP: {
7413 needmax=1; /* never Infinity */
7415 case DEC_ROUND_CEILING: {
7416 if (sign) needmax=1; /* Infinity if non-negative */
7418 case DEC_ROUND_FLOOR: {
7419 if (!sign) needmax=1; /* Infinity if negative */
7421 default: break; /* Infinity in all other cases */
7424 decSetMaxValue(dn, set);
7425 dn->bits=sign; /* set sign */
7427 else dn->bits=sign|DECINF; /* Value is +/-Infinity */
7428 *status|=DEC_Overflow | DEC_Inexact | DEC_Rounded;
7429 } /* decSetOverflow */
7431 /* ------------------------------------------------------------------ */
7432 /* decSetMaxValue -- set number to +Nmax (maximum normal value) */
7434 /* dn is the number to set */
7435 /* set is the context [used for digits and emax] */
7437 /* This sets the number to the maximum positive value. */
7438 /* ------------------------------------------------------------------ */
7439 static void decSetMaxValue(decNumber *dn, decContext *set) {
7440 Unit *up; /* work */
7441 Int count=set->digits; /* nines to add */
7443 /* fill in all nines to set maximum value */
7444 for (up=dn->lsu; ; up++) {
7445 if (count>DECDPUN) *up=DECDPUNMAX; /* unit full o'nines */
7446 else { /* this is the msu */
7447 *up=(Unit)(powers[count]-1);
7450 count-=DECDPUN; /* filled those digits */
7452 dn->bits=0; /* + sign */
7453 dn->exponent=set->emax-set->digits+1;
7454 } /* decSetMaxValue */
7456 /* ------------------------------------------------------------------ */
7457 /* decSetSubnormal -- process value whose exponent is <Emin */
7459 /* dn is the number (used as input as well as output; it may have */
7460 /* an allowed subnormal value, which may need to be rounded) */
7461 /* set is the context [used for the rounding mode] */
7462 /* residue is any pending residue */
7463 /* status contains the current status to be updated */
7465 /* If subset mode, set result to zero and set Underflow flags. */
7467 /* Value may be zero with a low exponent; this does not set Subnormal */
7468 /* but the exponent will be clamped to Etiny. */
7470 /* Otherwise ensure exponent is not out of range, and round as */
7471 /* necessary. Underflow is set if the result is Inexact. */
7472 /* ------------------------------------------------------------------ */
7473 static void decSetSubnormal(decNumber *dn, decContext *set, Int *residue,
7475 decContext workset; /* work */
7476 Int etiny, adjust; /* .. */
7479 /* simple set to zero and 'hard underflow' for subset */
7480 if (!set->extended) {
7481 uprv_decNumberZero(dn);
7482 /* always full overflow */
7483 *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
7488 /* Full arithmetic -- allow subnormals, rounded to minimum exponent */
7489 /* (Etiny) if needed */
7490 etiny=set->emin-(set->digits-1); /* smallest allowed exponent */
7492 if ISZERO(dn) { /* value is zero */
7493 /* residue can never be non-zero here */
7496 printf("++ Subnormal 0 residue %ld\n", (LI)*residue);
7497 *status|=DEC_Invalid_operation;
7500 if (dn->exponent<etiny) { /* clamp required */
7502 *status|=DEC_Clamped;
7507 *status|=DEC_Subnormal; /* have a non-zero subnormal */
7508 adjust=etiny-dn->exponent; /* calculate digits to remove */
7509 if (adjust<=0) { /* not out of range; unrounded */
7510 /* residue can never be non-zero here, except in the Nmin-residue */
7511 /* case (which is a subnormal result), so can take fast-path here */
7512 /* it may already be inexact (from setting the coefficient) */
7513 if (*status&DEC_Inexact) *status|=DEC_Underflow;
7517 /* adjust>0, so need to rescale the result so exponent becomes Etiny */
7518 /* [this code is similar to that in rescale] */
7519 workset=*set; /* clone rounding, etc. */
7520 workset.digits=dn->digits-adjust; /* set requested length */
7521 workset.emin-=adjust; /* and adjust emin to match */
7522 /* [note that the latter can be <1, here, similar to Rescale case] */
7523 decSetCoeff(dn, &workset, dn->lsu, dn->digits, residue, status);
7524 decApplyRound(dn, &workset, *residue, status);
7526 /* Use 754 default rule: Underflow is set iff Inexact */
7527 /* [independent of whether trapped] */
7528 if (*status&DEC_Inexact) *status|=DEC_Underflow;
7530 /* if rounded up a 999s case, exponent will be off by one; adjust */
7531 /* back if so [it will fit, because it was shortened earlier] */
7532 if (dn->exponent>etiny) {
7533 dn->digits=decShiftToMost(dn->lsu, dn->digits, 1);
7534 dn->exponent--; /* (re)adjust the exponent. */
7537 /* if rounded to zero, it is by definition clamped... */
7538 if (ISZERO(dn)) *status|=DEC_Clamped;
7539 } /* decSetSubnormal */
7541 /* ------------------------------------------------------------------ */
7542 /* decCheckMath - check entry conditions for a math function */
7544 /* This checks the context and the operand */
7546 /* rhs is the operand to check */
7547 /* set is the context to check */
7548 /* status is unchanged if both are good */
7550 /* returns non-zero if status is changed, 0 otherwise */
7552 /* Restrictions enforced: */
7554 /* digits, emax, and -emin in the context must be less than */
7555 /* DEC_MAX_MATH (999999), and A must be within these bounds if */
7556 /* non-zero. Invalid_operation is set in the status if a */
7557 /* restriction is violated. */
7558 /* ------------------------------------------------------------------ */
7559 static uInt decCheckMath(const decNumber *rhs, decContext *set,
7561 uInt save=*status; /* record */
7562 if (set->digits>DEC_MAX_MATH
7563 || set->emax>DEC_MAX_MATH
7564 || -set->emin>DEC_MAX_MATH) *status|=DEC_Invalid_context;
7565 else if ((rhs->digits>DEC_MAX_MATH
7566 || rhs->exponent+rhs->digits>DEC_MAX_MATH+1
7567 || rhs->exponent+rhs->digits<2*(1-DEC_MAX_MATH))
7568 && !ISZERO(rhs)) *status|=DEC_Invalid_operation;
7569 return (*status!=save);
7570 } /* decCheckMath */
7572 /* ------------------------------------------------------------------ */
7573 /* decGetInt -- get integer from a number */
7575 /* dn is the number [which will not be altered] */
7577 /* returns one of: */
7578 /* BADINT if there is a non-zero fraction */
7579 /* the converted integer */
7580 /* BIGEVEN if the integer is even and magnitude > 2*10**9 */
7581 /* BIGODD if the integer is odd and magnitude > 2*10**9 */
7583 /* This checks and gets a whole number from the input decNumber. */
7584 /* The sign can be determined from dn by the caller when BIGEVEN or */
7585 /* BIGODD is returned. */
7586 /* ------------------------------------------------------------------ */
7587 static Int decGetInt(const decNumber *dn) {
7588 Int theInt; /* result accumulator */
7589 const Unit *up; /* work */
7590 Int got; /* digits (real or not) processed */
7591 Int ilength=dn->digits+dn->exponent; /* integral length */
7592 Flag neg=decNumberIsNegative(dn); /* 1 if -ve */
7594 /* The number must be an integer that fits in 10 digits */
7595 /* Assert, here, that 10 is enough for any rescale Etiny */
7596 #if DEC_MAX_EMAX > 999999999
7597 #error GetInt may need updating [for Emax]
7599 #if DEC_MIN_EMIN < -999999999
7600 #error GetInt may need updating [for Emin]
7602 if (ISZERO(dn)) return 0; /* zeros are OK, with any exponent */
7604 up=dn->lsu; /* ready for lsu */
7605 theInt=0; /* ready to accumulate */
7606 if (dn->exponent>=0) { /* relatively easy */
7607 /* no fractional part [usual]; allow for positive exponent */
7610 else { /* -ve exponent; some fractional part to check and discard */
7611 Int count=-dn->exponent; /* digits to discard */
7612 /* spin up whole units until reach the Unit with the unit digit */
7613 for (; count>=DECDPUN; up++) {
7614 if (*up!=0) return BADINT; /* non-zero Unit to discard */
7617 if (count==0) got=0; /* [a multiple of DECDPUN] */
7618 else { /* [not multiple of DECDPUN] */
7620 /* slice off fraction digits and check for non-zero */
7622 theInt=QUOT10(*up, count);
7623 rem=*up-theInt*powers[count];
7625 rem=*up%powers[count]; /* slice off discards */
7626 theInt=*up/powers[count];
7628 if (rem!=0) return BADINT; /* non-zero fraction */
7630 got=DECDPUN-count; /* number of digits so far */
7631 up++; /* ready for next */
7634 /* now it's known there's no fractional part */
7636 /* tricky code now, to accumulate up to 9.3 digits */
7637 if (got==0) {theInt=*up; got+=DECDPUN; up++;} /* ensure lsu is there */
7641 /* collect any remaining unit(s) */
7642 for (; got<ilength; up++) {
7643 theInt+=*up*powers[got];
7646 if (ilength==10) { /* need to check for wrap */
7647 if (theInt/(Int)powers[got-DECDPUN]!=(Int)*(up-1)) ilength=11;
7648 /* [that test also disallows the BADINT result case] */
7649 else if (neg && theInt>1999999997) ilength=11;
7650 else if (!neg && theInt>999999999) ilength=11;
7651 if (ilength==11) theInt=save; /* restore correct low bit */
7655 if (ilength>10) { /* too big */
7656 if (theInt&1) return BIGODD; /* bottom bit 1 */
7657 return BIGEVEN; /* bottom bit 0 */
7660 if (neg) theInt=-theInt; /* apply sign */
7664 /* ------------------------------------------------------------------ */
7665 /* decDecap -- decapitate the coefficient of a number */
7667 /* dn is the number to be decapitated */
7668 /* drop is the number of digits to be removed from the left of dn; */
7669 /* this must be <= dn->digits (if equal, the coefficient is */
7672 /* Returns dn; dn->digits will be <= the initial digits less drop */
7673 /* (after removing drop digits there may be leading zero digits */
7674 /* which will also be removed). Only dn->lsu and dn->digits change. */
7675 /* ------------------------------------------------------------------ */
7676 static decNumber *decDecap(decNumber *dn, Int drop) {
7677 Unit *msu; /* -> target cut point */
7679 if (drop>=dn->digits) { /* losing the whole thing */
7681 if (drop>dn->digits)
7682 printf("decDecap called with drop>digits [%ld>%ld]\n",
7683 (LI)drop, (LI)dn->digits);
7689 msu=dn->lsu+D2U(dn->digits-drop)-1; /* -> likely msu */
7690 cut=MSUDIGITS(dn->digits-drop); /* digits to be in use in msu */
7691 if (cut!=DECDPUN) *msu%=powers[cut]; /* clear left digits */
7692 /* that may have left leading zero digits, so do a proper count... */
7693 dn->digits=decGetDigits(dn->lsu, msu-dn->lsu+1);
7697 /* ------------------------------------------------------------------ */
7698 /* decBiStr -- compare string with pairwise options */
7700 /* targ is the string to compare */
7701 /* str1 is one of the strings to compare against (length may be 0) */
7702 /* str2 is the other; it must be the same length as str1 */
7704 /* returns 1 if strings compare equal, (that is, it is the same */
7705 /* length as str1 and str2, and each character of targ is in either */
7706 /* str1 or str2 in the corresponding position), or 0 otherwise */
7708 /* This is used for generic caseless compare, including the awkward */
7709 /* case of the Turkish dotted and dotless Is. Use as (for example): */
7710 /* if (decBiStr(test, "mike", "MIKE")) ... */
7711 /* ------------------------------------------------------------------ */
7712 static Flag decBiStr(const char *targ, const char *str1, const char *str2) {
7713 for (;;targ++, str1++, str2++) {
7714 if (*targ!=*str1 && *targ!=*str2) return 0;
7715 /* *targ has a match in one (or both, if terminator) */
7716 if (*targ=='\0') break;
7721 /* ------------------------------------------------------------------ */
7722 /* decNaNs -- handle NaN operand or operands */
7724 /* res is the result number */
7725 /* lhs is the first operand */
7726 /* rhs is the second operand, or NULL if none */
7727 /* context is used to limit payload length */
7728 /* status contains the current status */
7729 /* returns res in case convenient */
7731 /* Called when one or both operands is a NaN, and propagates the */
7732 /* appropriate result to res. When an sNaN is found, it is changed */
7733 /* to a qNaN and Invalid operation is set. */
7734 /* ------------------------------------------------------------------ */
7735 static decNumber * decNaNs(decNumber *res, const decNumber *lhs,
7736 const decNumber *rhs, decContext *set,
7738 /* This decision tree ends up with LHS being the source pointer, */
7739 /* and status updated if need be */
7740 if (lhs->bits & DECSNAN)
7741 *status|=DEC_Invalid_operation | DEC_sNaN;
7742 else if (rhs==NULL);
7743 else if (rhs->bits & DECSNAN) {
7745 *status|=DEC_Invalid_operation | DEC_sNaN;
7747 else if (lhs->bits & DECNAN);
7750 /* propagate the payload */
7751 if (lhs->digits<=set->digits) uprv_decNumberCopy(res, lhs); /* easy */
7752 else { /* too long */
7755 /* copy safe number of units, then decapitate */
7756 res->bits=lhs->bits; /* need sign etc. */
7757 uresp1=res->lsu+D2U(set->digits);
7758 for (ur=res->lsu, ul=lhs->lsu; ur<uresp1; ur++, ul++) *ur=*ul;
7759 res->digits=D2U(set->digits)*DECDPUN;
7760 /* maybe still too long */
7761 if (res->digits>set->digits) decDecap(res, res->digits-set->digits);
7764 res->bits&=~DECSNAN; /* convert any sNaN to NaN, while */
7765 res->bits|=DECNAN; /* .. preserving sign */
7766 res->exponent=0; /* clean exponent */
7767 /* [coefficient was copied/decapitated] */
7771 /* ------------------------------------------------------------------ */
7772 /* decStatus -- apply non-zero status */
7774 /* dn is the number to set if error */
7775 /* status contains the current status (not yet in context) */
7776 /* set is the context */
7778 /* If the status is an error status, the number is set to a NaN, */
7779 /* unless the error was an overflow, divide-by-zero, or underflow, */
7780 /* in which case the number will have already been set. */
7782 /* The context status is then updated with the new status. Note that */
7783 /* this may raise a signal, so control may never return from this */
7784 /* routine (hence resources must be recovered before it is called). */
7785 /* ------------------------------------------------------------------ */
7786 static void decStatus(decNumber *dn, uInt status, decContext *set) {
7787 if (status & DEC_NaNs) { /* error status -> NaN */
7788 /* if cause was an sNaN, clear and propagate [NaN is already set up] */
7789 if (status & DEC_sNaN) status&=~DEC_sNaN;
7791 uprv_decNumberZero(dn); /* other error: clean throughout */
7792 dn->bits=DECNAN; /* and make a quiet NaN */
7795 uprv_decContextSetStatus(set, status); /* [may not return] */
7799 /* ------------------------------------------------------------------ */
7800 /* decGetDigits -- count digits in a Units array */
7802 /* uar is the Unit array holding the number (this is often an */
7803 /* accumulator of some sort) */
7804 /* len is the length of the array in units [>=1] */
7806 /* returns the number of (significant) digits in the array */
7808 /* All leading zeros are excluded, except the last if the array has */
7809 /* only zero Units. */
7810 /* ------------------------------------------------------------------ */
7811 /* This may be called twice during some operations. */
7812 static Int decGetDigits(Unit *uar, Int len) {
7813 Unit *up=uar+(len-1); /* -> msu */
7814 Int digits=(len-1)*DECDPUN+1; /* possible digits excluding msu */
7816 uInt const *pow; /* work */
7818 /* (at least 1 in final msu) */
7820 if (len<1) printf("decGetDigits called with len<1 [%ld]\n", (LI)len);
7823 for (; up>=uar; up--) {
7824 if (*up==0) { /* unit is all 0s */
7825 if (digits==1) break; /* a zero has one digit */
7826 digits-=DECDPUN; /* adjust for 0 unit */
7828 /* found the first (most significant) non-zero Unit */
7829 #if DECDPUN>1 /* not done yet */
7830 if (*up<10) break; /* is 1-9 */
7832 #if DECDPUN>2 /* not done yet */
7833 if (*up<100) break; /* is 10-99 */
7835 #if DECDPUN>3 /* not done yet */
7836 if (*up<1000) break; /* is 100-999 */
7838 #if DECDPUN>4 /* count the rest ... */
7839 for (pow=&powers[4]; *up>=*pow; pow++) digits++;
7847 } /* decGetDigits */
7849 #if DECTRACE | DECCHECK
7850 /* ------------------------------------------------------------------ */
7851 /* decNumberShow -- display a number [debug aid] */
7852 /* dn is the number to show */
7854 /* Shows: sign, exponent, coefficient (msu first), digits */
7855 /* or: sign, special-value */
7856 /* ------------------------------------------------------------------ */
7857 /* this is public so other modules can use it */
7858 void uprv_decNumberShow(const decNumber *dn) {
7859 const Unit *up; /* work */
7862 char isign='+'; /* main sign */
7866 if (decNumberIsNegative(dn)) isign='-';
7867 printf(" >> %c ", isign);
7868 if (dn->bits&DECSPECIAL) { /* Is a special value */
7869 if (decNumberIsInfinite(dn)) printf("Infinity");
7871 if (dn->bits&DECSNAN) printf("sNaN"); /* signalling NaN */
7874 /* if coefficient and exponent are 0, no more to do */
7875 if (dn->exponent==0 && dn->digits==1 && *dn->lsu==0) {
7878 /* drop through to report other information */
7882 /* now carefully display the coefficient */
7883 up=dn->lsu+D2U(dn->digits)-1; /* msu */
7884 printf("%ld", (LI)*up);
7885 for (up=up-1; up>=dn->lsu; up--) {
7888 for (cut=DECDPUN-1; cut>=0; cut--) {
7891 printf("%ld", (LI)d);
7894 if (dn->exponent!=0) {
7896 if (dn->exponent<0) esign='-';
7897 printf(" E%c%ld", esign, (LI)abs(dn->exponent));
7899 printf(" [%ld]\n", (LI)dn->digits);
7900 } /* decNumberShow */
7903 #if DECTRACE || DECCHECK
7904 /* ------------------------------------------------------------------ */
7905 /* decDumpAr -- display a unit array [debug/check aid] */
7906 /* name is a single-character tag name */
7907 /* ar is the array to display */
7908 /* len is the length of the array in Units */
7909 /* ------------------------------------------------------------------ */
7910 static void decDumpAr(char name, const Unit *ar, Int len) {
7932 printf(" :%c: ", name);
7933 for (i=len-1; i>=0; i--) {
7934 if (i==len-1) printf("%ld ", (LI)ar[i]);
7935 else printf(spec, ar[i]);
7942 /* ------------------------------------------------------------------ */
7943 /* decCheckOperands -- check operand(s) to a routine */
7944 /* res is the result structure (not checked; it will be set to */
7945 /* quiet NaN if error found (and it is not NULL)) */
7946 /* lhs is the first operand (may be DECUNRESU) */
7947 /* rhs is the second (may be DECUNUSED) */
7948 /* set is the context (may be DECUNCONT) */
7949 /* returns 0 if both operands, and the context are clean, or 1 */
7950 /* otherwise (in which case the context will show an error, */
7951 /* unless NULL). Note that res is not cleaned; caller should */
7952 /* handle this so res=NULL case is safe. */
7953 /* The caller is expected to abandon immediately if 1 is returned. */
7954 /* ------------------------------------------------------------------ */
7955 static Flag decCheckOperands(decNumber *res, const decNumber *lhs,
7956 const decNumber *rhs, decContext *set) {
7958 if (set==NULL) { /* oops; hopeless */
7959 #if DECTRACE || DECVERB
7960 printf("Reference to context is NULL.\n");
7964 else if (set!=DECUNCONT
7965 && (set->digits<1 || set->round>=DEC_ROUND_MAX)) {
7967 #if DECTRACE || DECVERB
7968 printf("Bad context [digits=%ld round=%ld].\n",
7969 (LI)set->digits, (LI)set->round);
7976 /* this one not DECVERB as standard tests include NULL */
7977 printf("Reference to result is NULL.\n");
7980 if (!bad && lhs!=DECUNUSED) bad=(decCheckNumber(lhs));
7981 if (!bad && rhs!=DECUNUSED) bad=(decCheckNumber(rhs));
7984 if (set!=DECUNCONT) uprv_decContextSetStatus(set, DEC_Invalid_operation);
7985 if (res!=DECUNRESU && res!=NULL) {
7986 uprv_decNumberZero(res);
7987 res->bits=DECNAN; /* qNaN */
7991 } /* decCheckOperands */
7993 /* ------------------------------------------------------------------ */
7994 /* decCheckNumber -- check a number */
7995 /* dn is the number to check */
7996 /* returns 0 if the number is clean, or 1 otherwise */
7998 /* The number is considered valid if it could be a result from some */
7999 /* operation in some valid context. */
8000 /* ------------------------------------------------------------------ */
8001 static Flag decCheckNumber(const decNumber *dn) {
8002 const Unit *up; /* work */
8003 uInt maxuint; /* .. */
8004 Int ae, d, digits; /* .. */
8005 Int emin, emax; /* .. */
8007 if (dn==NULL) { /* hopeless */
8009 /* this one not DECVERB as standard tests include NULL */
8010 printf("Reference to decNumber is NULL.\n");
8014 /* check special values */
8015 if (dn->bits & DECSPECIAL) {
8016 if (dn->exponent!=0) {
8017 #if DECTRACE || DECVERB
8018 printf("Exponent %ld (not 0) for a special value [%02x].\n",
8019 (LI)dn->exponent, dn->bits);
8023 /* 2003.09.08: NaNs may now have coefficients, so next tests Inf only */
8024 if (decNumberIsInfinite(dn)) {
8025 if (dn->digits!=1) {
8026 #if DECTRACE || DECVERB
8027 printf("Digits %ld (not 1) for an infinity.\n", (LI)dn->digits);
8031 #if DECTRACE || DECVERB
8032 printf("LSU %ld (not 0) for an infinity.\n", (LI)*dn->lsu);
8034 decDumpAr('I', dn->lsu, D2U(dn->digits));
8037 /* 2002.12.26: negative NaNs can now appear through proposed IEEE */
8038 /* concrete formats (decimal64, etc.). */
8042 /* check the coefficient */
8043 if (dn->digits<1 || dn->digits>DECNUMMAXP) {
8044 #if DECTRACE || DECVERB
8045 printf("Digits %ld in number.\n", (LI)dn->digits);
8051 for (up=dn->lsu; d>0; up++) {
8052 if (d>DECDPUN) maxuint=DECDPUNMAX;
8053 else { /* reached the msu */
8054 maxuint=powers[d]-1;
8055 if (dn->digits>1 && *up<powers[d-1]) {
8056 #if DECTRACE || DECVERB
8057 printf("Leading 0 in number.\n");
8058 uprv_decNumberShow(dn);
8063 #if DECTRACE || DECVERB
8064 printf("Bad Unit [%08lx] in %ld-digit number at offset %ld [maxuint %ld].\n",
8065 (LI)*up, (LI)dn->digits, (LI)(up-dn->lsu), (LI)maxuint);
8071 /* check the exponent. Note that input operands can have exponents */
8072 /* which are out of the set->emin/set->emax and set->digits range */
8073 /* (just as they can have more digits than set->digits). */
8074 ae=dn->exponent+dn->digits-1; /* adjusted exponent */
8078 if (ae<emin-(digits-1)) {
8079 #if DECTRACE || DECVERB
8080 printf("Adjusted exponent underflow [%ld].\n", (LI)ae);
8081 uprv_decNumberShow(dn);
8085 #if DECTRACE || DECVERB
8086 printf("Adjusted exponent overflow [%ld].\n", (LI)ae);
8087 uprv_decNumberShow(dn);
8091 return 0; /* it's OK */
8092 } /* decCheckNumber */
8094 /* ------------------------------------------------------------------ */
8095 /* decCheckInexact -- check a normal finite inexact result has digits */
8096 /* dn is the number to check */
8097 /* set is the context (for status and precision) */
8098 /* sets Invalid operation, etc., if some digits are missing */
8099 /* [this check is not made for DECSUBSET compilation or when */
8100 /* subnormal is not set] */
8101 /* ------------------------------------------------------------------ */
8102 static void decCheckInexact(const decNumber *dn, decContext *set) {
8103 #if !DECSUBSET && DECEXTFLAG
8104 if ((set->status & (DEC_Inexact|DEC_Subnormal))==DEC_Inexact
8105 && (set->digits!=dn->digits) && !(dn->bits & DECSPECIAL)) {
8106 #if DECTRACE || DECVERB
8107 printf("Insufficient digits [%ld] on normal Inexact result.\n",
8109 uprv_decNumberShow(dn);
8111 uprv_decContextSetStatus(set, DEC_Invalid_operation);
8114 /* next is a noop for quiet compiler */
8115 if (dn!=NULL && dn->digits==0) set->status|=DEC_Invalid_operation;
8118 } /* decCheckInexact */
8124 /* ------------------------------------------------------------------ */
8125 /* decMalloc -- accountable allocation routine */
8126 /* n is the number of bytes to allocate */
8128 /* Semantics is the same as the stdlib malloc routine, but bytes */
8129 /* allocated are accounted for globally, and corruption fences are */
8130 /* added before and after the 'actual' storage. */
8131 /* ------------------------------------------------------------------ */
8132 /* This routine allocates storage with an extra twelve bytes; 8 are */
8133 /* at the start and hold: */
8134 /* 0-3 the original length requested */
8135 /* 4-7 buffer corruption detection fence (DECFENCE, x4) */
8136 /* The 4 bytes at the end also hold a corruption fence (DECFENCE, x4) */
8137 /* ------------------------------------------------------------------ */
8138 static void *decMalloc(size_t n) {
8139 uInt size=n+12; /* true size */
8140 void *alloc; /* -> allocated storage */
8141 uByte *b, *b0; /* work */
8142 uInt uiwork; /* for macros */
8144 alloc=malloc(size); /* -> allocated storage */
8145 if (alloc==NULL) return NULL; /* out of strorage */
8146 b0=(uByte *)alloc; /* as bytes */
8147 decAllocBytes+=n; /* account for storage */
8148 UBFROMUI(alloc, n); /* save n */
8149 /* printf(" alloc ++ dAB: %ld (%ld)\n", (LI)decAllocBytes, (LI)n); */
8150 for (b=b0+4; b<b0+8; b++) *b=DECFENCE;
8151 for (b=b0+n+8; b<b0+n+12; b++) *b=DECFENCE;
8152 return b0+8; /* -> play area */
8155 /* ------------------------------------------------------------------ */
8156 /* decFree -- accountable free routine */
8157 /* alloc is the storage to free */
8159 /* Semantics is the same as the stdlib malloc routine, except that */
8160 /* the global storage accounting is updated and the fences are */
8161 /* checked to ensure that no routine has written 'out of bounds'. */
8162 /* ------------------------------------------------------------------ */
8163 /* This routine first checks that the fences have not been corrupted. */
8164 /* It then frees the storage using the 'truw' storage address (that */
8165 /* is, offset by 8). */
8166 /* ------------------------------------------------------------------ */
8167 static void decFree(void *alloc) {
8168 uInt n; /* original length */
8169 uByte *b, *b0; /* work */
8170 uInt uiwork; /* for macros */
8172 if (alloc==NULL) return; /* allowed; it's a nop */
8173 b0=(uByte *)alloc; /* as bytes */
8174 b0-=8; /* -> true start of storage */
8175 n=UBTOUI(b0); /* lift length */
8176 for (b=b0+4; b<b0+8; b++) if (*b!=DECFENCE)
8177 printf("=== Corrupt byte [%02x] at offset %d from %ld ===\n", *b,
8179 for (b=b0+n+8; b<b0+n+12; b++) if (*b!=DECFENCE)
8180 printf("=== Corrupt byte [%02x] at offset +%d from %ld, n=%ld ===\n", *b,
8181 b-b0-8, (LI)b0, (LI)n);
8182 free(b0); /* drop the storage */
8183 decAllocBytes-=n; /* account for storage */
8184 /* printf(" free -- dAB: %d (%d)\n", decAllocBytes, -n); */
8186 #define malloc(a) decMalloc(a)
8187 #define free(a) decFree(a)