1 /* Decimal number arithmetic module for the decNumber C Library. 2 Copyright (C) 2005, 2007 Free Software Foundation, Inc. 3 Contributed by IBM Corporation. Author Mike Cowlishaw. 4 5 This file is part of GCC. 6 7 GCC is free software; you can redistribute it and/or modify it under 8 the terms of the GNU General Public License as published by the Free 9 Software Foundation; either version 2, or (at your option) any later 10 version. 11 12 In addition to the permissions in the GNU General Public License, 13 the Free Software Foundation gives you unlimited permission to link 14 the compiled version of this file into combinations with other 15 programs, and to distribute those combinations without any 16 restriction coming from the use of this file. (The General Public 17 License restrictions do apply in other respects; for example, they 18 cover modification of the file, and distribution when not linked 19 into a combine executable.) 20 21 GCC is distributed in the hope that it will be useful, but WITHOUT ANY 22 WARRANTY; without even the implied warranty of MERCHANTABILITY or 23 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 24 for more details. 25 26 You should have received a copy of the GNU General Public License 27 along with GCC; see the file COPYING. If not, write to the Free 28 Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 29 02110-1301, USA. */ 30 31 /* ------------------------------------------------------------------ */ 32 /* Decimal Number arithmetic module */ 33 /* ------------------------------------------------------------------ */ 34 /* This module comprises the routines for General Decimal Arithmetic */ 35 /* as defined in the specification which may be found on the */ 36 /* http://www2.hursley.ibm.com/decimal web pages. It implements both */ 37 /* the full ('extended') arithmetic and the simpler ('subset') */ 38 /* arithmetic. */ 39 /* */ 40 /* Usage notes: */ 41 /* */ 42 /* 1. This code is ANSI C89 except: */ 43 /* */ 44 /* If DECDPUN>4 or DECUSE64=1, the C99 64-bit int64_t and */ 45 /* uint64_t types may be used. To avoid these, set DECUSE64=0 */ 46 /* and DECDPUN<=4 (see documentation). */ 47 /* */ 48 /* 2. The decNumber format which this library uses is optimized for */ 49 /* efficient processing of relatively short numbers; in particular */ 50 /* it allows the use of fixed sized structures and minimizes copy */ 51 /* and move operations. It does, however, support arbitrary */ 52 /* precision (up to 999,999,999 digits) and arbitrary exponent */ 53 /* range (Emax in the range 0 through 999,999,999 and Emin in the */ 54 /* range -999,999,999 through 0). Mathematical functions (for */ 55 /* example decNumberExp) as identified below are restricted more */ 56 /* tightly: digits, emax, and -emin in the context must be <= */ 57 /* DEC_MAX_MATH (999999), and their operand(s) must be within */ 58 /* these bounds. */ 59 /* */ 60 /* 3. Logical functions are further restricted; their operands must */ 61 /* be finite, positive, have an exponent of zero, and all digits */ 62 /* must be either 0 or 1. The result will only contain digits */ 63 /* which are 0 or 1 (and will have exponent=0 and a sign of 0). */ 64 /* */ 65 /* 4. Operands to operator functions are never modified unless they */ 66 /* are also specified to be the result number (which is always */ 67 /* permitted). Other than that case, operands must not overlap. */ 68 /* */ 69 /* 5. Error handling: the type of the error is ORed into the status */ 70 /* flags in the current context (decContext structure). The */ 71 /* SIGFPE signal is then raised if the corresponding trap-enabler */ 72 /* flag in the decContext is set (is 1). */ 73 /* */ 74 /* It is the responsibility of the caller to clear the status */ 75 /* flags as required. */ 76 /* */ 77 /* The result of any routine which returns a number will always */ 78 /* be a valid number (which may be a special value, such as an */ 79 /* Infinity or NaN). */ 80 /* */ 81 /* 6. The decNumber format is not an exchangeable concrete */ 82 /* representation as it comprises fields which may be machine- */ 83 /* dependent (packed or unpacked, or special length, for example). */ 84 /* Canonical conversions to and from strings are provided; other */ 85 /* conversions are available in separate modules. */ 86 /* */ 87 /* 7. Normally, input operands are assumed to be valid. Set DECCHECK */ 88 /* to 1 for extended operand checking (including NULL operands). */ 89 /* Results are undefined if a badly-formed structure (or a NULL */ 90 /* pointer to a structure) is provided, though with DECCHECK */ 91 /* enabled the operator routines are protected against exceptions. */ 92 /* (Except if the result pointer is NULL, which is unrecoverable.) */ 93 /* */ 94 /* However, the routines will never cause exceptions if they are */ 95 /* given well-formed operands, even if the value of the operands */ 96 /* is inappropriate for the operation and DECCHECK is not set. */ 97 /* (Except for SIGFPE, as and where documented.) */ 98 /* */ 99 /* 8. Subset arithmetic is available only if DECSUBSET is set to 1. */ 100 /* ------------------------------------------------------------------ */ 101 /* Implementation notes for maintenance of this module: */ 102 /* */ 103 /* 1. Storage leak protection: Routines which use malloc are not */ 104 /* permitted to use return for fastpath or error exits (i.e., */ 105 /* they follow strict structured programming conventions). */ 106 /* Instead they have a do{}while(0); construct surrounding the */ 107 /* code which is protected -- break may be used to exit this. */ 108 /* Other routines can safely use the return statement inline. */ 109 /* */ 110 /* Storage leak accounting can be enabled using DECALLOC. */ 111 /* */ 112 /* 2. All loops use the for(;;) construct. Any do construct does */ 113 /* not loop; it is for allocation protection as just described. */ 114 /* */ 115 /* 3. Setting status in the context must always be the very last */ 116 /* action in a routine, as non-0 status may raise a trap and hence */ 117 /* the call to set status may not return (if the handler uses long */ 118 /* jump). Therefore all cleanup must be done first. In general, */ 119 /* to achieve this status is accumulated and is only applied just */ 120 /* before return by calling decContextSetStatus (via decStatus). */ 121 /* */ 122 /* Routines which allocate storage cannot, in general, use the */ 123 /* 'top level' routines which could cause a non-returning */ 124 /* transfer of control. The decXxxxOp routines are safe (do not */ 125 /* call decStatus even if traps are set in the context) and should */ 126 /* be used instead (they are also a little faster). */ 127 /* */ 128 /* 4. Exponent checking is minimized by allowing the exponent to */ 129 /* grow outside its limits during calculations, provided that */ 130 /* the decFinalize function is called later. Multiplication and */ 131 /* division, and intermediate calculations in exponentiation, */ 132 /* require more careful checks because of the risk of 31-bit */ 133 /* overflow (the most negative valid exponent is -1999999997, for */ 134 /* a 999999999-digit number with adjusted exponent of -999999999). */ 135 /* */ 136 /* 5. Rounding is deferred until finalization of results, with any */ 137 /* 'off to the right' data being represented as a single digit */ 138 /* residue (in the range -1 through 9). This avoids any double- */ 139 /* rounding when more than one shortening takes place (for */ 140 /* example, when a result is subnormal). */ 141 /* */ 142 /* 6. The digits count is allowed to rise to a multiple of DECDPUN */ 143 /* during many operations, so whole Units are handled and exact */ 144 /* accounting of digits is not needed. The correct digits value */ 145 /* is found by decGetDigits, which accounts for leading zeros. */ 146 /* This must be called before any rounding if the number of digits */ 147 /* is not known exactly. */ 148 /* */ 149 /* 7. The multiply-by-reciprocal 'trick' is used for partitioning */ 150 /* numbers up to four digits, using appropriate constants. This */ 151 /* is not useful for longer numbers because overflow of 32 bits */ 152 /* would lead to 4 multiplies, which is almost as expensive as */ 153 /* a divide (unless a floating-point or 64-bit multiply is */ 154 /* assumed to be available). */ 155 /* */ 156 /* 8. Unusual abbreviations that may be used in the commentary: */ 157 /* lhs -- left hand side (operand, of an operation) */ 158 /* lsd -- least significant digit (of coefficient) */ 159 /* lsu -- least significant Unit (of coefficient) */ 160 /* msd -- most significant digit (of coefficient) */ 161 /* msi -- most significant item (in an array) */ 162 /* msu -- most significant Unit (of coefficient) */ 163 /* rhs -- right hand side (operand, of an operation) */ 164 /* +ve -- positive */ 165 /* -ve -- negative */ 166 /* ** -- raise to the power */ 167 /* ------------------------------------------------------------------ */ 168 169 #include "qemu/osdep.h" 170 #include "qemu/host-utils.h" 171 #include "libdecnumber/dconfig.h" 172 #include "libdecnumber/decNumber.h" 173 #include "libdecnumber/decNumberLocal.h" 174 175 /* Constants */ 176 /* Public lookup table used by the D2U macro */ 177 const uByte d2utable[DECMAXD2U+1]=D2UTABLE; 178 179 #define DECVERB 1 /* set to 1 for verbose DECCHECK */ 180 #define powers DECPOWERS /* old internal name */ 181 182 /* Local constants */ 183 #define DIVIDE 0x80 /* Divide operators */ 184 #define REMAINDER 0x40 /* .. */ 185 #define DIVIDEINT 0x20 /* .. */ 186 #define REMNEAR 0x10 /* .. */ 187 #define COMPARE 0x01 /* Compare operators */ 188 #define COMPMAX 0x02 /* .. */ 189 #define COMPMIN 0x03 /* .. */ 190 #define COMPTOTAL 0x04 /* .. */ 191 #define COMPNAN 0x05 /* .. [NaN processing] */ 192 #define COMPSIG 0x06 /* .. [signaling COMPARE] */ 193 #define COMPMAXMAG 0x07 /* .. */ 194 #define COMPMINMAG 0x08 /* .. */ 195 196 #define DEC_sNaN 0x40000000 /* local status: sNaN signal */ 197 #define BADINT (Int)0x80000000 /* most-negative Int; error indicator */ 198 /* Next two indicate an integer >= 10**6, and its parity (bottom bit) */ 199 #define BIGEVEN (Int)0x80000002 200 #define BIGODD (Int)0x80000003 201 202 static Unit uarrone[1]={1}; /* Unit array of 1, used for incrementing */ 203 204 /* Granularity-dependent code */ 205 #if DECDPUN<=4 206 #define eInt Int /* extended integer */ 207 #define ueInt uInt /* unsigned extended integer */ 208 /* Constant multipliers for divide-by-power-of five using reciprocal */ 209 /* multiply, after removing powers of 2 by shifting, and final shift */ 210 /* of 17 [we only need up to **4] */ 211 static const uInt multies[]={131073, 26215, 5243, 1049, 210}; 212 /* QUOT10 -- macro to return the quotient of unit u divided by 10**n */ 213 #define QUOT10(u, n) ((((uInt)(u)>>(n))*multies[n])>>17) 214 #else 215 /* For DECDPUN>4 non-ANSI-89 64-bit types are needed. */ 216 #if !DECUSE64 217 #error decNumber.c: DECUSE64 must be 1 when DECDPUN>4 218 #endif 219 #define eInt Long /* extended integer */ 220 #define ueInt uLong /* unsigned extended integer */ 221 #endif 222 223 /* Local routines */ 224 static decNumber * decAddOp(decNumber *, const decNumber *, const decNumber *, 225 decContext *, uByte, uInt *); 226 static Flag decBiStr(const char *, const char *, const char *); 227 static uInt decCheckMath(const decNumber *, decContext *, uInt *); 228 static void decApplyRound(decNumber *, decContext *, Int, uInt *); 229 static Int decCompare(const decNumber *lhs, const decNumber *rhs, Flag); 230 static decNumber * decCompareOp(decNumber *, const decNumber *, 231 const decNumber *, decContext *, 232 Flag, uInt *); 233 static void decCopyFit(decNumber *, const decNumber *, decContext *, 234 Int *, uInt *); 235 static decNumber * decDecap(decNumber *, Int); 236 static decNumber * decDivideOp(decNumber *, const decNumber *, 237 const decNumber *, decContext *, Flag, uInt *); 238 static decNumber * decExpOp(decNumber *, const decNumber *, 239 decContext *, uInt *); 240 static void decFinalize(decNumber *, decContext *, Int *, uInt *); 241 static Int decGetDigits(Unit *, Int); 242 static Int decGetInt(const decNumber *); 243 static decNumber * decLnOp(decNumber *, const decNumber *, 244 decContext *, uInt *); 245 static decNumber * decMultiplyOp(decNumber *, const decNumber *, 246 const decNumber *, decContext *, 247 uInt *); 248 static decNumber * decNaNs(decNumber *, const decNumber *, 249 const decNumber *, decContext *, uInt *); 250 static decNumber * decQuantizeOp(decNumber *, const decNumber *, 251 const decNumber *, decContext *, Flag, 252 uInt *); 253 static void decReverse(Unit *, Unit *); 254 static void decSetCoeff(decNumber *, decContext *, const Unit *, 255 Int, Int *, uInt *); 256 static void decSetMaxValue(decNumber *, decContext *); 257 static void decSetOverflow(decNumber *, decContext *, uInt *); 258 static void decSetSubnormal(decNumber *, decContext *, Int *, uInt *); 259 static Int decShiftToLeast(Unit *, Int, Int); 260 static Int decShiftToMost(Unit *, Int, Int); 261 static void decStatus(decNumber *, uInt, decContext *); 262 static void decToString(const decNumber *, char[], Flag); 263 static decNumber * decTrim(decNumber *, decContext *, Flag, Int *); 264 static Int decUnitAddSub(const Unit *, Int, const Unit *, Int, Int, 265 Unit *, Int); 266 static Int decUnitCompare(const Unit *, Int, const Unit *, Int, Int); 267 268 #if !DECSUBSET 269 /* decFinish == decFinalize when no subset arithmetic needed */ 270 #define decFinish(a,b,c,d) decFinalize(a,b,c,d) 271 #else 272 static void decFinish(decNumber *, decContext *, Int *, uInt *); 273 static decNumber * decRoundOperand(const decNumber *, decContext *, uInt *); 274 #endif 275 276 /* Local macros */ 277 /* masked special-values bits */ 278 #define SPECIALARG (rhs->bits & DECSPECIAL) 279 #define SPECIALARGS ((lhs->bits | rhs->bits) & DECSPECIAL) 280 281 /* Diagnostic macros, etc. */ 282 #if DECALLOC 283 /* Handle malloc/free accounting. If enabled, our accountable routines */ 284 /* are used; otherwise the code just goes straight to the system malloc */ 285 /* and free routines. */ 286 #define malloc(a) decMalloc(a) 287 #define free(a) decFree(a) 288 #define DECFENCE 0x5a /* corruption detector */ 289 /* 'Our' malloc and free: */ 290 static void *decMalloc(size_t); 291 static void decFree(void *); 292 uInt decAllocBytes=0; /* count of bytes allocated */ 293 /* Note that DECALLOC code only checks for storage buffer overflow. */ 294 /* To check for memory leaks, the decAllocBytes variable must be */ 295 /* checked to be 0 at appropriate times (e.g., after the test */ 296 /* harness completes a set of tests). This checking may be unreliable */ 297 /* if the testing is done in a multi-thread environment. */ 298 #endif 299 300 #if DECCHECK 301 /* Optional checking routines. Enabling these means that decNumber */ 302 /* and decContext operands to operator routines are checked for */ 303 /* correctness. This roughly doubles the execution time of the */ 304 /* fastest routines (and adds 600+ bytes), so should not normally be */ 305 /* used in 'production'. */ 306 /* decCheckInexact is used to check that inexact results have a full */ 307 /* complement of digits (where appropriate -- this is not the case */ 308 /* for Quantize, for example) */ 309 #define DECUNRESU ((decNumber *)(void *)0xffffffff) 310 #define DECUNUSED ((const decNumber *)(void *)0xffffffff) 311 #define DECUNCONT ((decContext *)(void *)(0xffffffff)) 312 static Flag decCheckOperands(decNumber *, const decNumber *, 313 const decNumber *, decContext *); 314 static Flag decCheckNumber(const decNumber *); 315 static void decCheckInexact(const decNumber *, decContext *); 316 #endif 317 318 #if DECTRACE || DECCHECK 319 /* Optional trace/debugging routines (may or may not be used) */ 320 void decNumberShow(const decNumber *); /* displays the components of a number */ 321 static void decDumpAr(char, const Unit *, Int); 322 #endif 323 324 /* ================================================================== */ 325 /* Conversions */ 326 /* ================================================================== */ 327 328 /* ------------------------------------------------------------------ */ 329 /* from-int32 -- conversion from Int or uInt */ 330 /* */ 331 /* dn is the decNumber to receive the integer */ 332 /* in or uin is the integer to be converted */ 333 /* returns dn */ 334 /* */ 335 /* No error is possible. */ 336 /* ------------------------------------------------------------------ */ 337 decNumber * decNumberFromInt32(decNumber *dn, Int in) { 338 uInt unsig; 339 if (in>=0) unsig=in; 340 else { /* negative (possibly BADINT) */ 341 if (in==BADINT) unsig=(uInt)1073741824*2; /* special case */ 342 else unsig=-in; /* invert */ 343 } 344 /* in is now positive */ 345 decNumberFromUInt32(dn, unsig); 346 if (in<0) dn->bits=DECNEG; /* sign needed */ 347 return dn; 348 } /* decNumberFromInt32 */ 349 350 decNumber * decNumberFromUInt32(decNumber *dn, uInt uin) { 351 Unit *up; /* work pointer */ 352 decNumberZero(dn); /* clean */ 353 if (uin==0) return dn; /* [or decGetDigits bad call] */ 354 for (up=dn->lsu; uin>0; up++) { 355 *up=(Unit)(uin%(DECDPUNMAX+1)); 356 uin=uin/(DECDPUNMAX+1); 357 } 358 dn->digits=decGetDigits(dn->lsu, up-dn->lsu); 359 return dn; 360 } /* decNumberFromUInt32 */ 361 362 /* ------------------------------------------------------------------ */ 363 /* to-int32 -- conversion to Int or uInt */ 364 /* */ 365 /* dn is the decNumber to convert */ 366 /* set is the context for reporting errors */ 367 /* returns the converted decNumber, or 0 if Invalid is set */ 368 /* */ 369 /* Invalid is set if the decNumber does not have exponent==0 or if */ 370 /* it is a NaN, Infinite, or out-of-range. */ 371 /* ------------------------------------------------------------------ */ 372 Int decNumberToInt32(const decNumber *dn, decContext *set) { 373 #if DECCHECK 374 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0; 375 #endif 376 377 /* special or too many digits, or bad exponent */ 378 if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0) ; /* bad */ 379 else { /* is a finite integer with 10 or fewer digits */ 380 Int d; /* work */ 381 const Unit *up; /* .. */ 382 uInt hi=0, lo; /* .. */ 383 up=dn->lsu; /* -> lsu */ 384 lo=*up; /* get 1 to 9 digits */ 385 #if DECDPUN>1 /* split to higher */ 386 hi=lo/10; 387 lo=lo%10; 388 #endif 389 up++; 390 /* collect remaining Units, if any, into hi */ 391 for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1]; 392 /* now low has the lsd, hi the remainder */ 393 if (hi>214748364 || (hi==214748364 && lo>7)) { /* out of range? */ 394 /* most-negative is a reprieve */ 395 if (dn->bits&DECNEG && hi==214748364 && lo==8) return 0x80000000; 396 /* bad -- drop through */ 397 } 398 else { /* in-range always */ 399 Int i=X10(hi)+lo; 400 if (dn->bits&DECNEG) return -i; 401 return i; 402 } 403 } /* integer */ 404 decContextSetStatus(set, DEC_Invalid_operation); /* [may not return] */ 405 return 0; 406 } /* decNumberToInt32 */ 407 408 uInt decNumberToUInt32(const decNumber *dn, decContext *set) { 409 #if DECCHECK 410 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0; 411 #endif 412 /* special or too many digits, or bad exponent, or negative (<0) */ 413 if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0 414 || (dn->bits&DECNEG && !ISZERO(dn))); /* bad */ 415 else { /* is a finite integer with 10 or fewer digits */ 416 Int d; /* work */ 417 const Unit *up; /* .. */ 418 uInt hi=0, lo; /* .. */ 419 up=dn->lsu; /* -> lsu */ 420 lo=*up; /* get 1 to 9 digits */ 421 #if DECDPUN>1 /* split to higher */ 422 hi=lo/10; 423 lo=lo%10; 424 #endif 425 up++; 426 /* collect remaining Units, if any, into hi */ 427 for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1]; 428 429 /* now low has the lsd, hi the remainder */ 430 if (hi>429496729 || (hi==429496729 && lo>5)) ; /* no reprieve possible */ 431 else return X10(hi)+lo; 432 } /* integer */ 433 decContextSetStatus(set, DEC_Invalid_operation); /* [may not return] */ 434 return 0; 435 } /* decNumberToUInt32 */ 436 437 decNumber *decNumberFromInt64(decNumber *dn, int64_t in) 438 { 439 uint64_t unsig = in; 440 if (in < 0) { 441 unsig = -unsig; 442 } 443 444 decNumberFromUInt64(dn, unsig); 445 if (in < 0) { 446 dn->bits = DECNEG; /* sign needed */ 447 } 448 return dn; 449 } /* decNumberFromInt64 */ 450 451 decNumber *decNumberFromUInt64(decNumber *dn, uint64_t uin) 452 { 453 Unit *up; /* work pointer */ 454 decNumberZero(dn); /* clean */ 455 if (uin == 0) { 456 return dn; /* [or decGetDigits bad call] */ 457 } 458 for (up = dn->lsu; uin > 0; up++) { 459 *up = (Unit)(uin % (DECDPUNMAX + 1)); 460 uin = uin / (DECDPUNMAX + 1); 461 } 462 dn->digits = decGetDigits(dn->lsu, up-dn->lsu); 463 return dn; 464 } /* decNumberFromUInt64 */ 465 466 decNumber *decNumberFromInt128(decNumber *dn, uint64_t lo, int64_t hi) 467 { 468 uint64_t unsig_hi = hi; 469 if (hi < 0) { 470 if (lo == 0) { 471 unsig_hi = -unsig_hi; 472 } else { 473 unsig_hi = ~unsig_hi; 474 lo = -lo; 475 } 476 } 477 478 decNumberFromUInt128(dn, lo, unsig_hi); 479 if (hi < 0) { 480 dn->bits = DECNEG; /* sign needed */ 481 } 482 return dn; 483 } /* decNumberFromInt128 */ 484 485 decNumber *decNumberFromUInt128(decNumber *dn, uint64_t lo, uint64_t hi) 486 { 487 uint64_t rem; 488 Unit *up; /* work pointer */ 489 decNumberZero(dn); /* clean */ 490 if (lo == 0 && hi == 0) { 491 return dn; /* [or decGetDigits bad call] */ 492 } 493 for (up = dn->lsu; hi > 0 || lo > 0; up++) { 494 rem = divu128(&lo, &hi, DECDPUNMAX + 1); 495 *up = (Unit)rem; 496 } 497 dn->digits = decGetDigits(dn->lsu, up - dn->lsu); 498 return dn; 499 } /* decNumberFromUInt128 */ 500 501 /* ------------------------------------------------------------------ */ 502 /* to-int64 -- conversion to int64 */ 503 /* */ 504 /* dn is the decNumber to convert. dn is assumed to have been */ 505 /* rounded to a floating point integer value. */ 506 /* set is the context for reporting errors */ 507 /* returns the converted decNumber, or 0 if Invalid is set */ 508 /* */ 509 /* Invalid is set if the decNumber is a NaN, Infinite or is out of */ 510 /* range for a signed 64 bit integer. */ 511 /* ------------------------------------------------------------------ */ 512 513 int64_t decNumberIntegralToInt64(const decNumber *dn, decContext *set) 514 { 515 if (decNumberIsSpecial(dn) || (dn->exponent < 0) || 516 (dn->digits + dn->exponent > 19)) { 517 goto Invalid; 518 } else { 519 int64_t d; /* work */ 520 const Unit *up; /* .. */ 521 uint64_t hi = 0; 522 up = dn->lsu; /* -> lsu */ 523 524 for (d = 1; d <= dn->digits; up++, d += DECDPUN) { 525 uint64_t prev = hi; 526 hi += *up * powers[d-1]; 527 if ((hi < prev) || (hi > INT64_MAX)) { 528 goto Invalid; 529 } 530 } 531 532 uint64_t prev = hi; 533 hi *= (uint64_t)powers[dn->exponent]; 534 if ((hi < prev) || (hi > INT64_MAX)) { 535 goto Invalid; 536 } 537 return (decNumberIsNegative(dn)) ? -((int64_t)hi) : (int64_t)hi; 538 } 539 540 Invalid: 541 decContextSetStatus(set, DEC_Invalid_operation); 542 return 0; 543 } /* decNumberIntegralToInt64 */ 544 545 546 /* ------------------------------------------------------------------ */ 547 /* to-scientific-string -- conversion to numeric string */ 548 /* to-engineering-string -- conversion to numeric string */ 549 /* */ 550 /* decNumberToString(dn, string); */ 551 /* decNumberToEngString(dn, string); */ 552 /* */ 553 /* dn is the decNumber to convert */ 554 /* string is the string where the result will be laid out */ 555 /* */ 556 /* string must be at least dn->digits+14 characters long */ 557 /* */ 558 /* No error is possible, and no status can be set. */ 559 /* ------------------------------------------------------------------ */ 560 char * decNumberToString(const decNumber *dn, char *string){ 561 decToString(dn, string, 0); 562 return string; 563 } /* DecNumberToString */ 564 565 char * decNumberToEngString(const decNumber *dn, char *string){ 566 decToString(dn, string, 1); 567 return string; 568 } /* DecNumberToEngString */ 569 570 /* ------------------------------------------------------------------ */ 571 /* to-number -- conversion from numeric string */ 572 /* */ 573 /* decNumberFromString -- convert string to decNumber */ 574 /* dn -- the number structure to fill */ 575 /* chars[] -- the string to convert ('\0' terminated) */ 576 /* set -- the context used for processing any error, */ 577 /* determining the maximum precision available */ 578 /* (set.digits), determining the maximum and minimum */ 579 /* exponent (set.emax and set.emin), determining if */ 580 /* extended values are allowed, and checking the */ 581 /* rounding mode if overflow occurs or rounding is */ 582 /* needed. */ 583 /* */ 584 /* The length of the coefficient and the size of the exponent are */ 585 /* checked by this routine, so the correct error (Underflow or */ 586 /* Overflow) can be reported or rounding applied, as necessary. */ 587 /* */ 588 /* If bad syntax is detected, the result will be a quiet NaN. */ 589 /* ------------------------------------------------------------------ */ 590 decNumber * decNumberFromString(decNumber *dn, const char chars[], 591 decContext *set) { 592 Int exponent=0; /* working exponent [assume 0] */ 593 uByte bits=0; /* working flags [assume +ve] */ 594 Unit *res; /* where result will be built */ 595 Unit resbuff[SD2U(DECBUFFER+9)];/* local buffer in case need temporary */ 596 /* [+9 allows for ln() constants] */ 597 Unit *allocres=NULL; /* -> allocated result, iff allocated */ 598 Int d=0; /* count of digits found in decimal part */ 599 const char *dotchar=NULL; /* where dot was found */ 600 const char *cfirst=chars; /* -> first character of decimal part */ 601 const char *last=NULL; /* -> last digit of decimal part */ 602 const char *c; /* work */ 603 Unit *up; /* .. */ 604 #if DECDPUN>1 605 Int cut, out; /* .. */ 606 #endif 607 Int residue; /* rounding residue */ 608 uInt status=0; /* error code */ 609 610 #if DECCHECK 611 if (decCheckOperands(DECUNRESU, DECUNUSED, DECUNUSED, set)) 612 return decNumberZero(dn); 613 #endif 614 615 do { /* status & malloc protection */ 616 for (c=chars;; c++) { /* -> input character */ 617 if (*c>='0' && *c<='9') { /* test for Arabic digit */ 618 last=c; 619 d++; /* count of real digits */ 620 continue; /* still in decimal part */ 621 } 622 if (*c=='.' && dotchar==NULL) { /* first '.' */ 623 dotchar=c; /* record offset into decimal part */ 624 if (c==cfirst) cfirst++; /* first digit must follow */ 625 continue;} 626 if (c==chars) { /* first in string... */ 627 if (*c=='-') { /* valid - sign */ 628 cfirst++; 629 bits=DECNEG; 630 continue;} 631 if (*c=='+') { /* valid + sign */ 632 cfirst++; 633 continue;} 634 } 635 /* *c is not a digit, or a valid +, -, or '.' */ 636 break; 637 } /* c */ 638 639 if (last==NULL) { /* no digits yet */ 640 status=DEC_Conversion_syntax;/* assume the worst */ 641 if (*c=='\0') break; /* and no more to come... */ 642 #if DECSUBSET 643 /* if subset then infinities and NaNs are not allowed */ 644 if (!set->extended) break; /* hopeless */ 645 #endif 646 /* Infinities and NaNs are possible, here */ 647 if (dotchar!=NULL) break; /* .. unless had a dot */ 648 decNumberZero(dn); /* be optimistic */ 649 if (decBiStr(c, "infinity", "INFINITY") 650 || decBiStr(c, "inf", "INF")) { 651 dn->bits=bits | DECINF; 652 status=0; /* is OK */ 653 break; /* all done */ 654 } 655 /* a NaN expected */ 656 /* 2003.09.10 NaNs are now permitted to have a sign */ 657 dn->bits=bits | DECNAN; /* assume simple NaN */ 658 if (*c=='s' || *c=='S') { /* looks like an sNaN */ 659 c++; 660 dn->bits=bits | DECSNAN; 661 } 662 if (*c!='n' && *c!='N') break; /* check caseless "NaN" */ 663 c++; 664 if (*c!='a' && *c!='A') break; /* .. */ 665 c++; 666 if (*c!='n' && *c!='N') break; /* .. */ 667 c++; 668 /* now either nothing, or nnnn payload, expected */ 669 /* -> start of integer and skip leading 0s [including plain 0] */ 670 for (cfirst=c; *cfirst=='0';) cfirst++; 671 if (*cfirst=='\0') { /* "NaN" or "sNaN", maybe with all 0s */ 672 status=0; /* it's good */ 673 break; /* .. */ 674 } 675 /* something other than 0s; setup last and d as usual [no dots] */ 676 for (c=cfirst;; c++, d++) { 677 if (*c<'0' || *c>'9') break; /* test for Arabic digit */ 678 last=c; 679 } 680 if (*c!='\0') break; /* not all digits */ 681 if (d>set->digits-1) { 682 /* [NB: payload in a decNumber can be full length unless */ 683 /* clamped, in which case can only be digits-1] */ 684 if (set->clamp) break; 685 if (d>set->digits) break; 686 } /* too many digits? */ 687 /* good; drop through to convert the integer to coefficient */ 688 status=0; /* syntax is OK */ 689 bits=dn->bits; /* for copy-back */ 690 } /* last==NULL */ 691 692 else if (*c!='\0') { /* more to process... */ 693 /* had some digits; exponent is only valid sequence now */ 694 Flag nege; /* 1=negative exponent */ 695 const char *firstexp; /* -> first significant exponent digit */ 696 status=DEC_Conversion_syntax;/* assume the worst */ 697 if (*c!='e' && *c!='E') break; 698 /* Found 'e' or 'E' -- now process explicit exponent */ 699 /* 1998.07.11: sign no longer required */ 700 nege=0; 701 c++; /* to (possible) sign */ 702 if (*c=='-') {nege=1; c++;} 703 else if (*c=='+') c++; 704 if (*c=='\0') break; 705 706 for (; *c=='0' && *(c+1)!='\0';) c++; /* strip insignificant zeros */ 707 firstexp=c; /* save exponent digit place */ 708 for (; ;c++) { 709 if (*c<'0' || *c>'9') break; /* not a digit */ 710 exponent=X10(exponent)+(Int)*c-(Int)'0'; 711 } /* c */ 712 /* if not now on a '\0', *c must not be a digit */ 713 if (*c!='\0') break; 714 715 /* (this next test must be after the syntax checks) */ 716 /* if it was too long the exponent may have wrapped, so check */ 717 /* carefully and set it to a certain overflow if wrap possible */ 718 if (c>=firstexp+9+1) { 719 if (c>firstexp+9+1 || *firstexp>'1') exponent=DECNUMMAXE*2; 720 /* [up to 1999999999 is OK, for example 1E-1000000998] */ 721 } 722 if (nege) exponent=-exponent; /* was negative */ 723 status=0; /* is OK */ 724 } /* stuff after digits */ 725 726 /* Here when whole string has been inspected; syntax is good */ 727 /* cfirst->first digit (never dot), last->last digit (ditto) */ 728 729 /* strip leading zeros/dot [leave final 0 if all 0's] */ 730 if (*cfirst=='0') { /* [cfirst has stepped over .] */ 731 for (c=cfirst; c<last; c++, cfirst++) { 732 if (*c=='.') continue; /* ignore dots */ 733 if (*c!='0') break; /* non-zero found */ 734 d--; /* 0 stripped */ 735 } /* c */ 736 #if DECSUBSET 737 /* make a rapid exit for easy zeros if !extended */ 738 if (*cfirst=='0' && !set->extended) { 739 decNumberZero(dn); /* clean result */ 740 break; /* [could be return] */ 741 } 742 #endif 743 } /* at least one leading 0 */ 744 745 /* Handle decimal point... */ 746 if (dotchar!=NULL && dotchar<last) /* non-trailing '.' found? */ 747 exponent-=(last-dotchar); /* adjust exponent */ 748 /* [we can now ignore the .] */ 749 750 /* OK, the digits string is good. Assemble in the decNumber, or in */ 751 /* a temporary units array if rounding is needed */ 752 if (d<=set->digits) res=dn->lsu; /* fits into supplied decNumber */ 753 else { /* rounding needed */ 754 Int needbytes=D2U(d)*sizeof(Unit);/* bytes needed */ 755 res=resbuff; /* assume use local buffer */ 756 if (needbytes>(Int)sizeof(resbuff)) { /* too big for local */ 757 allocres=(Unit *)malloc(needbytes); 758 if (allocres==NULL) {status|=DEC_Insufficient_storage; break;} 759 res=allocres; 760 } 761 } 762 /* res now -> number lsu, buffer, or allocated storage for Unit array */ 763 764 /* Place the coefficient into the selected Unit array */ 765 /* [this is often 70% of the cost of this function when DECDPUN>1] */ 766 #if DECDPUN>1 767 out=0; /* accumulator */ 768 up=res+D2U(d)-1; /* -> msu */ 769 cut=d-(up-res)*DECDPUN; /* digits in top unit */ 770 for (c=cfirst;; c++) { /* along the digits */ 771 if (*c=='.') continue; /* ignore '.' [don't decrement cut] */ 772 out=X10(out)+(Int)*c-(Int)'0'; 773 if (c==last) break; /* done [never get to trailing '.'] */ 774 cut--; 775 if (cut>0) continue; /* more for this unit */ 776 *up=(Unit)out; /* write unit */ 777 up--; /* prepare for unit below.. */ 778 cut=DECDPUN; /* .. */ 779 out=0; /* .. */ 780 } /* c */ 781 *up=(Unit)out; /* write lsu */ 782 783 #else 784 /* DECDPUN==1 */ 785 up=res; /* -> lsu */ 786 for (c=last; c>=cfirst; c--) { /* over each character, from least */ 787 if (*c=='.') continue; /* ignore . [don't step up] */ 788 *up=(Unit)((Int)*c-(Int)'0'); 789 up++; 790 } /* c */ 791 #endif 792 793 dn->bits=bits; 794 dn->exponent=exponent; 795 dn->digits=d; 796 797 /* if not in number (too long) shorten into the number */ 798 if (d>set->digits) { 799 residue=0; 800 decSetCoeff(dn, set, res, d, &residue, &status); 801 /* always check for overflow or subnormal and round as needed */ 802 decFinalize(dn, set, &residue, &status); 803 } 804 else { /* no rounding, but may still have overflow or subnormal */ 805 /* [these tests are just for performance; finalize repeats them] */ 806 if ((dn->exponent-1<set->emin-dn->digits) 807 || (dn->exponent-1>set->emax-set->digits)) { 808 residue=0; 809 decFinalize(dn, set, &residue, &status); 810 } 811 } 812 /* decNumberShow(dn); */ 813 } while(0); /* [for break] */ 814 815 if (allocres!=NULL) free(allocres); /* drop any storage used */ 816 if (status!=0) decStatus(dn, status, set); 817 return dn; 818 } /* decNumberFromString */ 819 820 /* ================================================================== */ 821 /* Operators */ 822 /* ================================================================== */ 823 824 /* ------------------------------------------------------------------ */ 825 /* decNumberAbs -- absolute value operator */ 826 /* */ 827 /* This computes C = abs(A) */ 828 /* */ 829 /* res is C, the result. C may be A */ 830 /* rhs is A */ 831 /* set is the context */ 832 /* */ 833 /* See also decNumberCopyAbs for a quiet bitwise version of this. */ 834 /* C must have space for set->digits digits. */ 835 /* ------------------------------------------------------------------ */ 836 /* This has the same effect as decNumberPlus unless A is negative, */ 837 /* in which case it has the same effect as decNumberMinus. */ 838 /* ------------------------------------------------------------------ */ 839 decNumber * decNumberAbs(decNumber *res, const decNumber *rhs, 840 decContext *set) { 841 decNumber dzero; /* for 0 */ 842 uInt status=0; /* accumulator */ 843 844 #if DECCHECK 845 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; 846 #endif 847 848 decNumberZero(&dzero); /* set 0 */ 849 dzero.exponent=rhs->exponent; /* [no coefficient expansion] */ 850 decAddOp(res, &dzero, rhs, set, (uByte)(rhs->bits & DECNEG), &status); 851 if (status!=0) decStatus(res, status, set); 852 #if DECCHECK 853 decCheckInexact(res, set); 854 #endif 855 return res; 856 } /* decNumberAbs */ 857 858 /* ------------------------------------------------------------------ */ 859 /* decNumberAdd -- add two Numbers */ 860 /* */ 861 /* This computes C = A + B */ 862 /* */ 863 /* res is C, the result. C may be A and/or B (e.g., X=X+X) */ 864 /* lhs is A */ 865 /* rhs is B */ 866 /* set is the context */ 867 /* */ 868 /* C must have space for set->digits digits. */ 869 /* ------------------------------------------------------------------ */ 870 /* This just calls the routine shared with Subtract */ 871 decNumber * decNumberAdd(decNumber *res, const decNumber *lhs, 872 const decNumber *rhs, decContext *set) { 873 uInt status=0; /* accumulator */ 874 decAddOp(res, lhs, rhs, set, 0, &status); 875 if (status!=0) decStatus(res, status, set); 876 #if DECCHECK 877 decCheckInexact(res, set); 878 #endif 879 return res; 880 } /* decNumberAdd */ 881 882 /* ------------------------------------------------------------------ */ 883 /* decNumberAnd -- AND two Numbers, digitwise */ 884 /* */ 885 /* This computes C = A & B */ 886 /* */ 887 /* res is C, the result. C may be A and/or B (e.g., X=X&X) */ 888 /* lhs is A */ 889 /* rhs is B */ 890 /* set is the context (used for result length and error report) */ 891 /* */ 892 /* C must have space for set->digits digits. */ 893 /* */ 894 /* Logical function restrictions apply (see above); a NaN is */ 895 /* returned with Invalid_operation if a restriction is violated. */ 896 /* ------------------------------------------------------------------ */ 897 decNumber * decNumberAnd(decNumber *res, const decNumber *lhs, 898 const decNumber *rhs, decContext *set) { 899 const Unit *ua, *ub; /* -> operands */ 900 const Unit *msua, *msub; /* -> operand msus */ 901 Unit *uc, *msuc; /* -> result and its msu */ 902 Int msudigs; /* digits in res msu */ 903 #if DECCHECK 904 if (decCheckOperands(res, lhs, rhs, set)) return res; 905 #endif 906 907 if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs) 908 || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) { 909 decStatus(res, DEC_Invalid_operation, set); 910 return res; 911 } 912 913 /* operands are valid */ 914 ua=lhs->lsu; /* bottom-up */ 915 ub=rhs->lsu; /* .. */ 916 uc=res->lsu; /* .. */ 917 msua=ua+D2U(lhs->digits)-1; /* -> msu of lhs */ 918 msub=ub+D2U(rhs->digits)-1; /* -> msu of rhs */ 919 msuc=uc+D2U(set->digits)-1; /* -> msu of result */ 920 msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */ 921 for (; uc<=msuc; ua++, ub++, uc++) { /* Unit loop */ 922 Unit a, b; /* extract units */ 923 if (ua>msua) a=0; 924 else a=*ua; 925 if (ub>msub) b=0; 926 else b=*ub; 927 *uc=0; /* can now write back */ 928 if (a|b) { /* maybe 1 bits to examine */ 929 Int i, j; 930 *uc=0; /* can now write back */ 931 /* This loop could be unrolled and/or use BIN2BCD tables */ 932 for (i=0; i<DECDPUN; i++) { 933 if (a&b&1) *uc=*uc+(Unit)powers[i]; /* effect AND */ 934 j=a%10; 935 a=a/10; 936 j|=b%10; 937 b=b/10; 938 if (j>1) { 939 decStatus(res, DEC_Invalid_operation, set); 940 return res; 941 } 942 if (uc==msuc && i==msudigs-1) break; /* just did final digit */ 943 } /* each digit */ 944 } /* both OK */ 945 } /* each unit */ 946 /* [here uc-1 is the msu of the result] */ 947 res->digits=decGetDigits(res->lsu, uc-res->lsu); 948 res->exponent=0; /* integer */ 949 res->bits=0; /* sign=0 */ 950 return res; /* [no status to set] */ 951 } /* decNumberAnd */ 952 953 /* ------------------------------------------------------------------ */ 954 /* decNumberCompare -- compare two Numbers */ 955 /* */ 956 /* This computes C = A ? B */ 957 /* */ 958 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */ 959 /* lhs is A */ 960 /* rhs is B */ 961 /* set is the context */ 962 /* */ 963 /* C must have space for one digit (or NaN). */ 964 /* ------------------------------------------------------------------ */ 965 decNumber * decNumberCompare(decNumber *res, const decNumber *lhs, 966 const decNumber *rhs, decContext *set) { 967 uInt status=0; /* accumulator */ 968 decCompareOp(res, lhs, rhs, set, COMPARE, &status); 969 if (status!=0) decStatus(res, status, set); 970 return res; 971 } /* decNumberCompare */ 972 973 /* ------------------------------------------------------------------ */ 974 /* decNumberCompareSignal -- compare, signalling on all NaNs */ 975 /* */ 976 /* This computes C = A ? B */ 977 /* */ 978 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */ 979 /* lhs is A */ 980 /* rhs is B */ 981 /* set is the context */ 982 /* */ 983 /* C must have space for one digit (or NaN). */ 984 /* ------------------------------------------------------------------ */ 985 decNumber * decNumberCompareSignal(decNumber *res, const decNumber *lhs, 986 const decNumber *rhs, decContext *set) { 987 uInt status=0; /* accumulator */ 988 decCompareOp(res, lhs, rhs, set, COMPSIG, &status); 989 if (status!=0) decStatus(res, status, set); 990 return res; 991 } /* decNumberCompareSignal */ 992 993 /* ------------------------------------------------------------------ */ 994 /* decNumberCompareTotal -- compare two Numbers, using total ordering */ 995 /* */ 996 /* This computes C = A ? B, under total ordering */ 997 /* */ 998 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */ 999 /* lhs is A */ 1000 /* rhs is B */ 1001 /* set is the context */ 1002 /* */ 1003 /* C must have space for one digit; the result will always be one of */ 1004 /* -1, 0, or 1. */ 1005 /* ------------------------------------------------------------------ */ 1006 decNumber * decNumberCompareTotal(decNumber *res, const decNumber *lhs, 1007 const decNumber *rhs, decContext *set) { 1008 uInt status=0; /* accumulator */ 1009 decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status); 1010 if (status!=0) decStatus(res, status, set); 1011 return res; 1012 } /* decNumberCompareTotal */ 1013 1014 /* ------------------------------------------------------------------ */ 1015 /* decNumberCompareTotalMag -- compare, total ordering of magnitudes */ 1016 /* */ 1017 /* This computes C = |A| ? |B|, under total ordering */ 1018 /* */ 1019 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */ 1020 /* lhs is A */ 1021 /* rhs is B */ 1022 /* set is the context */ 1023 /* */ 1024 /* C must have space for one digit; the result will always be one of */ 1025 /* -1, 0, or 1. */ 1026 /* ------------------------------------------------------------------ */ 1027 decNumber * decNumberCompareTotalMag(decNumber *res, const decNumber *lhs, 1028 const decNumber *rhs, decContext *set) { 1029 uInt status=0; /* accumulator */ 1030 uInt needbytes; /* for space calculations */ 1031 decNumber bufa[D2N(DECBUFFER+1)];/* +1 in case DECBUFFER=0 */ 1032 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */ 1033 decNumber bufb[D2N(DECBUFFER+1)]; 1034 decNumber *allocbufb=NULL; /* -> allocated bufb, iff allocated */ 1035 decNumber *a, *b; /* temporary pointers */ 1036 1037 #if DECCHECK 1038 if (decCheckOperands(res, lhs, rhs, set)) return res; 1039 #endif 1040 1041 do { /* protect allocated storage */ 1042 /* if either is negative, take a copy and absolute */ 1043 if (decNumberIsNegative(lhs)) { /* lhs<0 */ 1044 a=bufa; 1045 needbytes=sizeof(decNumber)+(D2U(lhs->digits)-1)*sizeof(Unit); 1046 if (needbytes>sizeof(bufa)) { /* need malloc space */ 1047 allocbufa=(decNumber *)malloc(needbytes); 1048 if (allocbufa==NULL) { /* hopeless -- abandon */ 1049 status|=DEC_Insufficient_storage; 1050 break;} 1051 a=allocbufa; /* use the allocated space */ 1052 } 1053 decNumberCopy(a, lhs); /* copy content */ 1054 a->bits&=~DECNEG; /* .. and clear the sign */ 1055 lhs=a; /* use copy from here on */ 1056 } 1057 if (decNumberIsNegative(rhs)) { /* rhs<0 */ 1058 b=bufb; 1059 needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit); 1060 if (needbytes>sizeof(bufb)) { /* need malloc space */ 1061 allocbufb=(decNumber *)malloc(needbytes); 1062 if (allocbufb==NULL) { /* hopeless -- abandon */ 1063 status|=DEC_Insufficient_storage; 1064 break;} 1065 b=allocbufb; /* use the allocated space */ 1066 } 1067 decNumberCopy(b, rhs); /* copy content */ 1068 b->bits&=~DECNEG; /* .. and clear the sign */ 1069 rhs=b; /* use copy from here on */ 1070 } 1071 decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status); 1072 } while(0); /* end protected */ 1073 1074 if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */ 1075 if (allocbufb!=NULL) free(allocbufb); /* .. */ 1076 if (status!=0) decStatus(res, status, set); 1077 return res; 1078 } /* decNumberCompareTotalMag */ 1079 1080 /* ------------------------------------------------------------------ */ 1081 /* decNumberDivide -- divide one number by another */ 1082 /* */ 1083 /* This computes C = A / B */ 1084 /* */ 1085 /* res is C, the result. C may be A and/or B (e.g., X=X/X) */ 1086 /* lhs is A */ 1087 /* rhs is B */ 1088 /* set is the context */ 1089 /* */ 1090 /* C must have space for set->digits digits. */ 1091 /* ------------------------------------------------------------------ */ 1092 decNumber * decNumberDivide(decNumber *res, const decNumber *lhs, 1093 const decNumber *rhs, decContext *set) { 1094 uInt status=0; /* accumulator */ 1095 decDivideOp(res, lhs, rhs, set, DIVIDE, &status); 1096 if (status!=0) decStatus(res, status, set); 1097 #if DECCHECK 1098 decCheckInexact(res, set); 1099 #endif 1100 return res; 1101 } /* decNumberDivide */ 1102 1103 /* ------------------------------------------------------------------ */ 1104 /* decNumberDivideInteger -- divide and return integer quotient */ 1105 /* */ 1106 /* This computes C = A # B, where # is the integer divide operator */ 1107 /* */ 1108 /* res is C, the result. C may be A and/or B (e.g., X=X#X) */ 1109 /* lhs is A */ 1110 /* rhs is B */ 1111 /* set is the context */ 1112 /* */ 1113 /* C must have space for set->digits digits. */ 1114 /* ------------------------------------------------------------------ */ 1115 decNumber * decNumberDivideInteger(decNumber *res, const decNumber *lhs, 1116 const decNumber *rhs, decContext *set) { 1117 uInt status=0; /* accumulator */ 1118 decDivideOp(res, lhs, rhs, set, DIVIDEINT, &status); 1119 if (status!=0) decStatus(res, status, set); 1120 return res; 1121 } /* decNumberDivideInteger */ 1122 1123 /* ------------------------------------------------------------------ */ 1124 /* decNumberExp -- exponentiation */ 1125 /* */ 1126 /* This computes C = exp(A) */ 1127 /* */ 1128 /* res is C, the result. C may be A */ 1129 /* rhs is A */ 1130 /* set is the context; note that rounding mode has no effect */ 1131 /* */ 1132 /* C must have space for set->digits digits. */ 1133 /* */ 1134 /* Mathematical function restrictions apply (see above); a NaN is */ 1135 /* returned with Invalid_operation if a restriction is violated. */ 1136 /* */ 1137 /* Finite results will always be full precision and Inexact, except */ 1138 /* when A is a zero or -Infinity (giving 1 or 0 respectively). */ 1139 /* */ 1140 /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */ 1141 /* almost always be correctly rounded, but may be up to 1 ulp in */ 1142 /* error in rare cases. */ 1143 /* ------------------------------------------------------------------ */ 1144 /* This is a wrapper for decExpOp which can handle the slightly wider */ 1145 /* (double) range needed by Ln (which has to be able to calculate */ 1146 /* exp(-a) where a can be the tiniest number (Ntiny). */ 1147 /* ------------------------------------------------------------------ */ 1148 decNumber * decNumberExp(decNumber *res, const decNumber *rhs, 1149 decContext *set) { 1150 uInt status=0; /* accumulator */ 1151 #if DECSUBSET 1152 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */ 1153 #endif 1154 1155 #if DECCHECK 1156 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; 1157 #endif 1158 1159 /* Check restrictions; these restrictions ensure that if h=8 (see */ 1160 /* decExpOp) then the result will either overflow or underflow to 0. */ 1161 /* Other math functions restrict the input range, too, for inverses. */ 1162 /* If not violated then carry out the operation. */ 1163 if (!decCheckMath(rhs, set, &status)) do { /* protect allocation */ 1164 #if DECSUBSET 1165 if (!set->extended) { 1166 /* reduce operand and set lostDigits status, as needed */ 1167 if (rhs->digits>set->digits) { 1168 allocrhs=decRoundOperand(rhs, set, &status); 1169 if (allocrhs==NULL) break; 1170 rhs=allocrhs; 1171 } 1172 } 1173 #endif 1174 decExpOp(res, rhs, set, &status); 1175 } while(0); /* end protected */ 1176 1177 #if DECSUBSET 1178 if (allocrhs !=NULL) free(allocrhs); /* drop any storage used */ 1179 #endif 1180 /* apply significant status */ 1181 if (status!=0) decStatus(res, status, set); 1182 #if DECCHECK 1183 decCheckInexact(res, set); 1184 #endif 1185 return res; 1186 } /* decNumberExp */ 1187 1188 /* ------------------------------------------------------------------ */ 1189 /* decNumberFMA -- fused multiply add */ 1190 /* */ 1191 /* This computes D = (A * B) + C with only one rounding */ 1192 /* */ 1193 /* res is D, the result. D may be A or B or C (e.g., X=FMA(X,X,X)) */ 1194 /* lhs is A */ 1195 /* rhs is B */ 1196 /* fhs is C [far hand side] */ 1197 /* set is the context */ 1198 /* */ 1199 /* Mathematical function restrictions apply (see above); a NaN is */ 1200 /* returned with Invalid_operation if a restriction is violated. */ 1201 /* */ 1202 /* C must have space for set->digits digits. */ 1203 /* ------------------------------------------------------------------ */ 1204 decNumber * decNumberFMA(decNumber *res, const decNumber *lhs, 1205 const decNumber *rhs, const decNumber *fhs, 1206 decContext *set) { 1207 uInt status=0; /* accumulator */ 1208 decContext dcmul; /* context for the multiplication */ 1209 uInt needbytes; /* for space calculations */ 1210 decNumber bufa[D2N(DECBUFFER*2+1)]; 1211 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */ 1212 decNumber *acc; /* accumulator pointer */ 1213 decNumber dzero; /* work */ 1214 1215 #if DECCHECK 1216 if (decCheckOperands(res, lhs, rhs, set)) return res; 1217 if (decCheckOperands(res, fhs, DECUNUSED, set)) return res; 1218 #endif 1219 1220 do { /* protect allocated storage */ 1221 #if DECSUBSET 1222 if (!set->extended) { /* [undefined if subset] */ 1223 status|=DEC_Invalid_operation; 1224 break;} 1225 #endif 1226 /* Check math restrictions [these ensure no overflow or underflow] */ 1227 if ((!decNumberIsSpecial(lhs) && decCheckMath(lhs, set, &status)) 1228 || (!decNumberIsSpecial(rhs) && decCheckMath(rhs, set, &status)) 1229 || (!decNumberIsSpecial(fhs) && decCheckMath(fhs, set, &status))) break; 1230 /* set up context for multiply */ 1231 dcmul=*set; 1232 dcmul.digits=lhs->digits+rhs->digits; /* just enough */ 1233 /* [The above may be an over-estimate for subset arithmetic, but that's OK] */ 1234 dcmul.emax=DEC_MAX_EMAX; /* effectively unbounded .. */ 1235 dcmul.emin=DEC_MIN_EMIN; /* [thanks to Math restrictions] */ 1236 /* set up decNumber space to receive the result of the multiply */ 1237 acc=bufa; /* may fit */ 1238 needbytes=sizeof(decNumber)+(D2U(dcmul.digits)-1)*sizeof(Unit); 1239 if (needbytes>sizeof(bufa)) { /* need malloc space */ 1240 allocbufa=(decNumber *)malloc(needbytes); 1241 if (allocbufa==NULL) { /* hopeless -- abandon */ 1242 status|=DEC_Insufficient_storage; 1243 break;} 1244 acc=allocbufa; /* use the allocated space */ 1245 } 1246 /* multiply with extended range and necessary precision */ 1247 /*printf("emin=%ld\n", dcmul.emin); */ 1248 decMultiplyOp(acc, lhs, rhs, &dcmul, &status); 1249 /* Only Invalid operation (from sNaN or Inf * 0) is possible in */ 1250 /* status; if either is seen than ignore fhs (in case it is */ 1251 /* another sNaN) and set acc to NaN unless we had an sNaN */ 1252 /* [decMultiplyOp leaves that to caller] */ 1253 /* Note sNaN has to go through addOp to shorten payload if */ 1254 /* necessary */ 1255 if ((status&DEC_Invalid_operation)!=0) { 1256 if (!(status&DEC_sNaN)) { /* but be true invalid */ 1257 decNumberZero(res); /* acc not yet set */ 1258 res->bits=DECNAN; 1259 break; 1260 } 1261 decNumberZero(&dzero); /* make 0 (any non-NaN would do) */ 1262 fhs=&dzero; /* use that */ 1263 } 1264 #if DECCHECK 1265 else { /* multiply was OK */ 1266 if (status!=0) printf("Status=%08lx after FMA multiply\n", status); 1267 } 1268 #endif 1269 /* add the third operand and result -> res, and all is done */ 1270 decAddOp(res, acc, fhs, set, 0, &status); 1271 } while(0); /* end protected */ 1272 1273 if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */ 1274 if (status!=0) decStatus(res, status, set); 1275 #if DECCHECK 1276 decCheckInexact(res, set); 1277 #endif 1278 return res; 1279 } /* decNumberFMA */ 1280 1281 /* ------------------------------------------------------------------ */ 1282 /* decNumberInvert -- invert a Number, digitwise */ 1283 /* */ 1284 /* This computes C = ~A */ 1285 /* */ 1286 /* res is C, the result. C may be A (e.g., X=~X) */ 1287 /* rhs is A */ 1288 /* set is the context (used for result length and error report) */ 1289 /* */ 1290 /* C must have space for set->digits digits. */ 1291 /* */ 1292 /* Logical function restrictions apply (see above); a NaN is */ 1293 /* returned with Invalid_operation if a restriction is violated. */ 1294 /* ------------------------------------------------------------------ */ 1295 decNumber * decNumberInvert(decNumber *res, const decNumber *rhs, 1296 decContext *set) { 1297 const Unit *ua, *msua; /* -> operand and its msu */ 1298 Unit *uc, *msuc; /* -> result and its msu */ 1299 Int msudigs; /* digits in res msu */ 1300 #if DECCHECK 1301 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; 1302 #endif 1303 1304 if (rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) { 1305 decStatus(res, DEC_Invalid_operation, set); 1306 return res; 1307 } 1308 /* operand is valid */ 1309 ua=rhs->lsu; /* bottom-up */ 1310 uc=res->lsu; /* .. */ 1311 msua=ua+D2U(rhs->digits)-1; /* -> msu of rhs */ 1312 msuc=uc+D2U(set->digits)-1; /* -> msu of result */ 1313 msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */ 1314 for (; uc<=msuc; ua++, uc++) { /* Unit loop */ 1315 Unit a; /* extract unit */ 1316 Int i, j; /* work */ 1317 if (ua>msua) a=0; 1318 else a=*ua; 1319 *uc=0; /* can now write back */ 1320 /* always need to examine all bits in rhs */ 1321 /* This loop could be unrolled and/or use BIN2BCD tables */ 1322 for (i=0; i<DECDPUN; i++) { 1323 if ((~a)&1) *uc=*uc+(Unit)powers[i]; /* effect INVERT */ 1324 j=a%10; 1325 a=a/10; 1326 if (j>1) { 1327 decStatus(res, DEC_Invalid_operation, set); 1328 return res; 1329 } 1330 if (uc==msuc && i==msudigs-1) break; /* just did final digit */ 1331 } /* each digit */ 1332 } /* each unit */ 1333 /* [here uc-1 is the msu of the result] */ 1334 res->digits=decGetDigits(res->lsu, uc-res->lsu); 1335 res->exponent=0; /* integer */ 1336 res->bits=0; /* sign=0 */ 1337 return res; /* [no status to set] */ 1338 } /* decNumberInvert */ 1339 1340 /* ------------------------------------------------------------------ */ 1341 /* decNumberLn -- natural logarithm */ 1342 /* */ 1343 /* This computes C = ln(A) */ 1344 /* */ 1345 /* res is C, the result. C may be A */ 1346 /* rhs is A */ 1347 /* set is the context; note that rounding mode has no effect */ 1348 /* */ 1349 /* C must have space for set->digits digits. */ 1350 /* */ 1351 /* Notable cases: */ 1352 /* A<0 -> Invalid */ 1353 /* A=0 -> -Infinity (Exact) */ 1354 /* A=+Infinity -> +Infinity (Exact) */ 1355 /* A=1 exactly -> 0 (Exact) */ 1356 /* */ 1357 /* Mathematical function restrictions apply (see above); a NaN is */ 1358 /* returned with Invalid_operation if a restriction is violated. */ 1359 /* */ 1360 /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */ 1361 /* almost always be correctly rounded, but may be up to 1 ulp in */ 1362 /* error in rare cases. */ 1363 /* ------------------------------------------------------------------ */ 1364 /* This is a wrapper for decLnOp which can handle the slightly wider */ 1365 /* (+11) range needed by Ln, Log10, etc. (which may have to be able */ 1366 /* to calculate at p+e+2). */ 1367 /* ------------------------------------------------------------------ */ 1368 decNumber * decNumberLn(decNumber *res, const decNumber *rhs, 1369 decContext *set) { 1370 uInt status=0; /* accumulator */ 1371 #if DECSUBSET 1372 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */ 1373 #endif 1374 1375 #if DECCHECK 1376 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; 1377 #endif 1378 1379 /* Check restrictions; this is a math function; if not violated */ 1380 /* then carry out the operation. */ 1381 if (!decCheckMath(rhs, set, &status)) do { /* protect allocation */ 1382 #if DECSUBSET 1383 if (!set->extended) { 1384 /* reduce operand and set lostDigits status, as needed */ 1385 if (rhs->digits>set->digits) { 1386 allocrhs=decRoundOperand(rhs, set, &status); 1387 if (allocrhs==NULL) break; 1388 rhs=allocrhs; 1389 } 1390 /* special check in subset for rhs=0 */ 1391 if (ISZERO(rhs)) { /* +/- zeros -> error */ 1392 status|=DEC_Invalid_operation; 1393 break;} 1394 } /* extended=0 */ 1395 #endif 1396 decLnOp(res, rhs, set, &status); 1397 } while(0); /* end protected */ 1398 1399 #if DECSUBSET 1400 if (allocrhs !=NULL) free(allocrhs); /* drop any storage used */ 1401 #endif 1402 /* apply significant status */ 1403 if (status!=0) decStatus(res, status, set); 1404 #if DECCHECK 1405 decCheckInexact(res, set); 1406 #endif 1407 return res; 1408 } /* decNumberLn */ 1409 1410 /* ------------------------------------------------------------------ */ 1411 /* decNumberLogB - get adjusted exponent, by 754r rules */ 1412 /* */ 1413 /* This computes C = adjustedexponent(A) */ 1414 /* */ 1415 /* res is C, the result. C may be A */ 1416 /* rhs is A */ 1417 /* set is the context, used only for digits and status */ 1418 /* */ 1419 /* C must have space for 10 digits (A might have 10**9 digits and */ 1420 /* an exponent of +999999999, or one digit and an exponent of */ 1421 /* -1999999999). */ 1422 /* */ 1423 /* This returns the adjusted exponent of A after (in theory) padding */ 1424 /* with zeros on the right to set->digits digits while keeping the */ 1425 /* same value. The exponent is not limited by emin/emax. */ 1426 /* */ 1427 /* Notable cases: */ 1428 /* A<0 -> Use |A| */ 1429 /* A=0 -> -Infinity (Division by zero) */ 1430 /* A=Infinite -> +Infinity (Exact) */ 1431 /* A=1 exactly -> 0 (Exact) */ 1432 /* NaNs are propagated as usual */ 1433 /* ------------------------------------------------------------------ */ 1434 decNumber * decNumberLogB(decNumber *res, const decNumber *rhs, 1435 decContext *set) { 1436 uInt status=0; /* accumulator */ 1437 1438 #if DECCHECK 1439 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; 1440 #endif 1441 1442 /* NaNs as usual; Infinities return +Infinity; 0->oops */ 1443 if (decNumberIsNaN(rhs)) decNaNs(res, rhs, NULL, set, &status); 1444 else if (decNumberIsInfinite(rhs)) decNumberCopyAbs(res, rhs); 1445 else if (decNumberIsZero(rhs)) { 1446 decNumberZero(res); /* prepare for Infinity */ 1447 res->bits=DECNEG|DECINF; /* -Infinity */ 1448 status|=DEC_Division_by_zero; /* as per 754r */ 1449 } 1450 else { /* finite non-zero */ 1451 Int ae=rhs->exponent+rhs->digits-1; /* adjusted exponent */ 1452 decNumberFromInt32(res, ae); /* lay it out */ 1453 } 1454 1455 if (status!=0) decStatus(res, status, set); 1456 return res; 1457 } /* decNumberLogB */ 1458 1459 /* ------------------------------------------------------------------ */ 1460 /* decNumberLog10 -- logarithm in base 10 */ 1461 /* */ 1462 /* This computes C = log10(A) */ 1463 /* */ 1464 /* res is C, the result. C may be A */ 1465 /* rhs is A */ 1466 /* set is the context; note that rounding mode has no effect */ 1467 /* */ 1468 /* C must have space for set->digits digits. */ 1469 /* */ 1470 /* Notable cases: */ 1471 /* A<0 -> Invalid */ 1472 /* A=0 -> -Infinity (Exact) */ 1473 /* A=+Infinity -> +Infinity (Exact) */ 1474 /* A=10**n (if n is an integer) -> n (Exact) */ 1475 /* */ 1476 /* Mathematical function restrictions apply (see above); a NaN is */ 1477 /* returned with Invalid_operation if a restriction is violated. */ 1478 /* */ 1479 /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */ 1480 /* almost always be correctly rounded, but may be up to 1 ulp in */ 1481 /* error in rare cases. */ 1482 /* ------------------------------------------------------------------ */ 1483 /* This calculates ln(A)/ln(10) using appropriate precision. For */ 1484 /* ln(A) this is the max(p, rhs->digits + t) + 3, where p is the */ 1485 /* requested digits and t is the number of digits in the exponent */ 1486 /* (maximum 6). For ln(10) it is p + 3; this is often handled by the */ 1487 /* fastpath in decLnOp. The final division is done to the requested */ 1488 /* precision. */ 1489 /* ------------------------------------------------------------------ */ 1490 decNumber * decNumberLog10(decNumber *res, const decNumber *rhs, 1491 decContext *set) { 1492 uInt status=0, ignore=0; /* status accumulators */ 1493 uInt needbytes; /* for space calculations */ 1494 Int p; /* working precision */ 1495 Int t; /* digits in exponent of A */ 1496 1497 /* buffers for a and b working decimals */ 1498 /* (adjustment calculator, same size) */ 1499 decNumber bufa[D2N(DECBUFFER+2)]; 1500 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */ 1501 decNumber *a=bufa; /* temporary a */ 1502 decNumber bufb[D2N(DECBUFFER+2)]; 1503 decNumber *allocbufb=NULL; /* -> allocated bufb, iff allocated */ 1504 decNumber *b=bufb; /* temporary b */ 1505 decNumber bufw[D2N(10)]; /* working 2-10 digit number */ 1506 decNumber *w=bufw; /* .. */ 1507 #if DECSUBSET 1508 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */ 1509 #endif 1510 1511 decContext aset; /* working context */ 1512 1513 #if DECCHECK 1514 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; 1515 #endif 1516 1517 /* Check restrictions; this is a math function; if not violated */ 1518 /* then carry out the operation. */ 1519 if (!decCheckMath(rhs, set, &status)) do { /* protect malloc */ 1520 #if DECSUBSET 1521 if (!set->extended) { 1522 /* reduce operand and set lostDigits status, as needed */ 1523 if (rhs->digits>set->digits) { 1524 allocrhs=decRoundOperand(rhs, set, &status); 1525 if (allocrhs==NULL) break; 1526 rhs=allocrhs; 1527 } 1528 /* special check in subset for rhs=0 */ 1529 if (ISZERO(rhs)) { /* +/- zeros -> error */ 1530 status|=DEC_Invalid_operation; 1531 break;} 1532 } /* extended=0 */ 1533 #endif 1534 1535 decContextDefault(&aset, DEC_INIT_DECIMAL64); /* clean context */ 1536 1537 /* handle exact powers of 10; only check if +ve finite */ 1538 if (!(rhs->bits&(DECNEG|DECSPECIAL)) && !ISZERO(rhs)) { 1539 Int residue=0; /* (no residue) */ 1540 uInt copystat=0; /* clean status */ 1541 1542 /* round to a single digit... */ 1543 aset.digits=1; 1544 decCopyFit(w, rhs, &aset, &residue, ©stat); /* copy & shorten */ 1545 /* if exact and the digit is 1, rhs is a power of 10 */ 1546 if (!(copystat&DEC_Inexact) && w->lsu[0]==1) { 1547 /* the exponent, conveniently, is the power of 10; making */ 1548 /* this the result needs a little care as it might not fit, */ 1549 /* so first convert it into the working number, and then move */ 1550 /* to res */ 1551 decNumberFromInt32(w, w->exponent); 1552 residue=0; 1553 decCopyFit(res, w, set, &residue, &status); /* copy & round */ 1554 decFinish(res, set, &residue, &status); /* cleanup/set flags */ 1555 break; 1556 } /* not a power of 10 */ 1557 } /* not a candidate for exact */ 1558 1559 /* simplify the information-content calculation to use 'total */ 1560 /* number of digits in a, including exponent' as compared to the */ 1561 /* requested digits, as increasing this will only rarely cost an */ 1562 /* iteration in ln(a) anyway */ 1563 t=6; /* it can never be >6 */ 1564 1565 /* allocate space when needed... */ 1566 p=(rhs->digits+t>set->digits?rhs->digits+t:set->digits)+3; 1567 needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit); 1568 if (needbytes>sizeof(bufa)) { /* need malloc space */ 1569 allocbufa=(decNumber *)malloc(needbytes); 1570 if (allocbufa==NULL) { /* hopeless -- abandon */ 1571 status|=DEC_Insufficient_storage; 1572 break;} 1573 a=allocbufa; /* use the allocated space */ 1574 } 1575 aset.digits=p; /* as calculated */ 1576 aset.emax=DEC_MAX_MATH; /* usual bounds */ 1577 aset.emin=-DEC_MAX_MATH; /* .. */ 1578 aset.clamp=0; /* and no concrete format */ 1579 decLnOp(a, rhs, &aset, &status); /* a=ln(rhs) */ 1580 1581 /* skip the division if the result so far is infinite, NaN, or */ 1582 /* zero, or there was an error; note NaN from sNaN needs copy */ 1583 if (status&DEC_NaNs && !(status&DEC_sNaN)) break; 1584 if (a->bits&DECSPECIAL || ISZERO(a)) { 1585 decNumberCopy(res, a); /* [will fit] */ 1586 break;} 1587 1588 /* for ln(10) an extra 3 digits of precision are needed */ 1589 p=set->digits+3; 1590 needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit); 1591 if (needbytes>sizeof(bufb)) { /* need malloc space */ 1592 allocbufb=(decNumber *)malloc(needbytes); 1593 if (allocbufb==NULL) { /* hopeless -- abandon */ 1594 status|=DEC_Insufficient_storage; 1595 break;} 1596 b=allocbufb; /* use the allocated space */ 1597 } 1598 decNumberZero(w); /* set up 10... */ 1599 #if DECDPUN==1 1600 w->lsu[1]=1; w->lsu[0]=0; /* .. */ 1601 #else 1602 w->lsu[0]=10; /* .. */ 1603 #endif 1604 w->digits=2; /* .. */ 1605 1606 aset.digits=p; 1607 decLnOp(b, w, &aset, &ignore); /* b=ln(10) */ 1608 1609 aset.digits=set->digits; /* for final divide */ 1610 decDivideOp(res, a, b, &aset, DIVIDE, &status); /* into result */ 1611 } while(0); /* [for break] */ 1612 1613 if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */ 1614 if (allocbufb!=NULL) free(allocbufb); /* .. */ 1615 #if DECSUBSET 1616 if (allocrhs !=NULL) free(allocrhs); /* .. */ 1617 #endif 1618 /* apply significant status */ 1619 if (status!=0) decStatus(res, status, set); 1620 #if DECCHECK 1621 decCheckInexact(res, set); 1622 #endif 1623 return res; 1624 } /* decNumberLog10 */ 1625 1626 /* ------------------------------------------------------------------ */ 1627 /* decNumberMax -- compare two Numbers and return the maximum */ 1628 /* */ 1629 /* This computes C = A ? B, returning the maximum by 754R rules */ 1630 /* */ 1631 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */ 1632 /* lhs is A */ 1633 /* rhs is B */ 1634 /* set is the context */ 1635 /* */ 1636 /* C must have space for set->digits digits. */ 1637 /* ------------------------------------------------------------------ */ 1638 decNumber * decNumberMax(decNumber *res, const decNumber *lhs, 1639 const decNumber *rhs, decContext *set) { 1640 uInt status=0; /* accumulator */ 1641 decCompareOp(res, lhs, rhs, set, COMPMAX, &status); 1642 if (status!=0) decStatus(res, status, set); 1643 #if DECCHECK 1644 decCheckInexact(res, set); 1645 #endif 1646 return res; 1647 } /* decNumberMax */ 1648 1649 /* ------------------------------------------------------------------ */ 1650 /* decNumberMaxMag -- compare and return the maximum by magnitude */ 1651 /* */ 1652 /* This computes C = A ? B, returning the maximum by 754R rules */ 1653 /* */ 1654 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */ 1655 /* lhs is A */ 1656 /* rhs is B */ 1657 /* set is the context */ 1658 /* */ 1659 /* C must have space for set->digits digits. */ 1660 /* ------------------------------------------------------------------ */ 1661 decNumber * decNumberMaxMag(decNumber *res, const decNumber *lhs, 1662 const decNumber *rhs, decContext *set) { 1663 uInt status=0; /* accumulator */ 1664 decCompareOp(res, lhs, rhs, set, COMPMAXMAG, &status); 1665 if (status!=0) decStatus(res, status, set); 1666 #if DECCHECK 1667 decCheckInexact(res, set); 1668 #endif 1669 return res; 1670 } /* decNumberMaxMag */ 1671 1672 /* ------------------------------------------------------------------ */ 1673 /* decNumberMin -- compare two Numbers and return the minimum */ 1674 /* */ 1675 /* This computes C = A ? B, returning the minimum by 754R rules */ 1676 /* */ 1677 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */ 1678 /* lhs is A */ 1679 /* rhs is B */ 1680 /* set is the context */ 1681 /* */ 1682 /* C must have space for set->digits digits. */ 1683 /* ------------------------------------------------------------------ */ 1684 decNumber * decNumberMin(decNumber *res, const decNumber *lhs, 1685 const decNumber *rhs, decContext *set) { 1686 uInt status=0; /* accumulator */ 1687 decCompareOp(res, lhs, rhs, set, COMPMIN, &status); 1688 if (status!=0) decStatus(res, status, set); 1689 #if DECCHECK 1690 decCheckInexact(res, set); 1691 #endif 1692 return res; 1693 } /* decNumberMin */ 1694 1695 /* ------------------------------------------------------------------ */ 1696 /* decNumberMinMag -- compare and return the minimum by magnitude */ 1697 /* */ 1698 /* This computes C = A ? B, returning the minimum by 754R rules */ 1699 /* */ 1700 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */ 1701 /* lhs is A */ 1702 /* rhs is B */ 1703 /* set is the context */ 1704 /* */ 1705 /* C must have space for set->digits digits. */ 1706 /* ------------------------------------------------------------------ */ 1707 decNumber * decNumberMinMag(decNumber *res, const decNumber *lhs, 1708 const decNumber *rhs, decContext *set) { 1709 uInt status=0; /* accumulator */ 1710 decCompareOp(res, lhs, rhs, set, COMPMINMAG, &status); 1711 if (status!=0) decStatus(res, status, set); 1712 #if DECCHECK 1713 decCheckInexact(res, set); 1714 #endif 1715 return res; 1716 } /* decNumberMinMag */ 1717 1718 /* ------------------------------------------------------------------ */ 1719 /* decNumberMinus -- prefix minus operator */ 1720 /* */ 1721 /* This computes C = 0 - A */ 1722 /* */ 1723 /* res is C, the result. C may be A */ 1724 /* rhs is A */ 1725 /* set is the context */ 1726 /* */ 1727 /* See also decNumberCopyNegate for a quiet bitwise version of this. */ 1728 /* C must have space for set->digits digits. */ 1729 /* ------------------------------------------------------------------ */ 1730 /* Simply use AddOp for the subtract, which will do the necessary. */ 1731 /* ------------------------------------------------------------------ */ 1732 decNumber * decNumberMinus(decNumber *res, const decNumber *rhs, 1733 decContext *set) { 1734 decNumber dzero; 1735 uInt status=0; /* accumulator */ 1736 1737 #if DECCHECK 1738 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; 1739 #endif 1740 1741 decNumberZero(&dzero); /* make 0 */ 1742 dzero.exponent=rhs->exponent; /* [no coefficient expansion] */ 1743 decAddOp(res, &dzero, rhs, set, DECNEG, &status); 1744 if (status!=0) decStatus(res, status, set); 1745 #if DECCHECK 1746 decCheckInexact(res, set); 1747 #endif 1748 return res; 1749 } /* decNumberMinus */ 1750 1751 /* ------------------------------------------------------------------ */ 1752 /* decNumberNextMinus -- next towards -Infinity */ 1753 /* */ 1754 /* This computes C = A - infinitesimal, rounded towards -Infinity */ 1755 /* */ 1756 /* res is C, the result. C may be A */ 1757 /* rhs is A */ 1758 /* set is the context */ 1759 /* */ 1760 /* This is a generalization of 754r NextDown. */ 1761 /* ------------------------------------------------------------------ */ 1762 decNumber * decNumberNextMinus(decNumber *res, const decNumber *rhs, 1763 decContext *set) { 1764 decNumber dtiny; /* constant */ 1765 decContext workset=*set; /* work */ 1766 uInt status=0; /* accumulator */ 1767 #if DECCHECK 1768 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; 1769 #endif 1770 1771 /* +Infinity is the special case */ 1772 if ((rhs->bits&(DECINF|DECNEG))==DECINF) { 1773 decSetMaxValue(res, set); /* is +ve */ 1774 /* there is no status to set */ 1775 return res; 1776 } 1777 decNumberZero(&dtiny); /* start with 0 */ 1778 dtiny.lsu[0]=1; /* make number that is .. */ 1779 dtiny.exponent=DEC_MIN_EMIN-1; /* .. smaller than tiniest */ 1780 workset.round=DEC_ROUND_FLOOR; 1781 decAddOp(res, rhs, &dtiny, &workset, DECNEG, &status); 1782 status&=DEC_Invalid_operation|DEC_sNaN; /* only sNaN Invalid please */ 1783 if (status!=0) decStatus(res, status, set); 1784 return res; 1785 } /* decNumberNextMinus */ 1786 1787 /* ------------------------------------------------------------------ */ 1788 /* decNumberNextPlus -- next towards +Infinity */ 1789 /* */ 1790 /* This computes C = A + infinitesimal, rounded towards +Infinity */ 1791 /* */ 1792 /* res is C, the result. C may be A */ 1793 /* rhs is A */ 1794 /* set is the context */ 1795 /* */ 1796 /* This is a generalization of 754r NextUp. */ 1797 /* ------------------------------------------------------------------ */ 1798 decNumber * decNumberNextPlus(decNumber *res, const decNumber *rhs, 1799 decContext *set) { 1800 decNumber dtiny; /* constant */ 1801 decContext workset=*set; /* work */ 1802 uInt status=0; /* accumulator */ 1803 #if DECCHECK 1804 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; 1805 #endif 1806 1807 /* -Infinity is the special case */ 1808 if ((rhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) { 1809 decSetMaxValue(res, set); 1810 res->bits=DECNEG; /* negative */ 1811 /* there is no status to set */ 1812 return res; 1813 } 1814 decNumberZero(&dtiny); /* start with 0 */ 1815 dtiny.lsu[0]=1; /* make number that is .. */ 1816 dtiny.exponent=DEC_MIN_EMIN-1; /* .. smaller than tiniest */ 1817 workset.round=DEC_ROUND_CEILING; 1818 decAddOp(res, rhs, &dtiny, &workset, 0, &status); 1819 status&=DEC_Invalid_operation|DEC_sNaN; /* only sNaN Invalid please */ 1820 if (status!=0) decStatus(res, status, set); 1821 return res; 1822 } /* decNumberNextPlus */ 1823 1824 /* ------------------------------------------------------------------ */ 1825 /* decNumberNextToward -- next towards rhs */ 1826 /* */ 1827 /* This computes C = A +/- infinitesimal, rounded towards */ 1828 /* +/-Infinity in the direction of B, as per 754r nextafter rules */ 1829 /* */ 1830 /* res is C, the result. C may be A or B. */ 1831 /* lhs is A */ 1832 /* rhs is B */ 1833 /* set is the context */ 1834 /* */ 1835 /* This is a generalization of 754r NextAfter. */ 1836 /* ------------------------------------------------------------------ */ 1837 decNumber * decNumberNextToward(decNumber *res, const decNumber *lhs, 1838 const decNumber *rhs, decContext *set) { 1839 decNumber dtiny; /* constant */ 1840 decContext workset=*set; /* work */ 1841 Int result; /* .. */ 1842 uInt status=0; /* accumulator */ 1843 #if DECCHECK 1844 if (decCheckOperands(res, lhs, rhs, set)) return res; 1845 #endif 1846 1847 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) { 1848 decNaNs(res, lhs, rhs, set, &status); 1849 } 1850 else { /* Is numeric, so no chance of sNaN Invalid, etc. */ 1851 result=decCompare(lhs, rhs, 0); /* sign matters */ 1852 if (result==BADINT) status|=DEC_Insufficient_storage; /* rare */ 1853 else { /* valid compare */ 1854 if (result==0) decNumberCopySign(res, lhs, rhs); /* easy */ 1855 else { /* differ: need NextPlus or NextMinus */ 1856 uByte sub; /* add or subtract */ 1857 if (result<0) { /* lhs<rhs, do nextplus */ 1858 /* -Infinity is the special case */ 1859 if ((lhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) { 1860 decSetMaxValue(res, set); 1861 res->bits=DECNEG; /* negative */ 1862 return res; /* there is no status to set */ 1863 } 1864 workset.round=DEC_ROUND_CEILING; 1865 sub=0; /* add, please */ 1866 } /* plus */ 1867 else { /* lhs>rhs, do nextminus */ 1868 /* +Infinity is the special case */ 1869 if ((lhs->bits&(DECINF|DECNEG))==DECINF) { 1870 decSetMaxValue(res, set); 1871 return res; /* there is no status to set */ 1872 } 1873 workset.round=DEC_ROUND_FLOOR; 1874 sub=DECNEG; /* subtract, please */ 1875 } /* minus */ 1876 decNumberZero(&dtiny); /* start with 0 */ 1877 dtiny.lsu[0]=1; /* make number that is .. */ 1878 dtiny.exponent=DEC_MIN_EMIN-1; /* .. smaller than tiniest */ 1879 decAddOp(res, lhs, &dtiny, &workset, sub, &status); /* + or - */ 1880 /* turn off exceptions if the result is a normal number */ 1881 /* (including Nmin), otherwise let all status through */ 1882 if (decNumberIsNormal(res, set)) status=0; 1883 } /* unequal */ 1884 } /* compare OK */ 1885 } /* numeric */ 1886 if (status!=0) decStatus(res, status, set); 1887 return res; 1888 } /* decNumberNextToward */ 1889 1890 /* ------------------------------------------------------------------ */ 1891 /* decNumberOr -- OR two Numbers, digitwise */ 1892 /* */ 1893 /* This computes C = A | B */ 1894 /* */ 1895 /* res is C, the result. C may be A and/or B (e.g., X=X|X) */ 1896 /* lhs is A */ 1897 /* rhs is B */ 1898 /* set is the context (used for result length and error report) */ 1899 /* */ 1900 /* C must have space for set->digits digits. */ 1901 /* */ 1902 /* Logical function restrictions apply (see above); a NaN is */ 1903 /* returned with Invalid_operation if a restriction is violated. */ 1904 /* ------------------------------------------------------------------ */ 1905 decNumber * decNumberOr(decNumber *res, const decNumber *lhs, 1906 const decNumber *rhs, decContext *set) { 1907 const Unit *ua, *ub; /* -> operands */ 1908 const Unit *msua, *msub; /* -> operand msus */ 1909 Unit *uc, *msuc; /* -> result and its msu */ 1910 Int msudigs; /* digits in res msu */ 1911 #if DECCHECK 1912 if (decCheckOperands(res, lhs, rhs, set)) return res; 1913 #endif 1914 1915 if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs) 1916 || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) { 1917 decStatus(res, DEC_Invalid_operation, set); 1918 return res; 1919 } 1920 /* operands are valid */ 1921 ua=lhs->lsu; /* bottom-up */ 1922 ub=rhs->lsu; /* .. */ 1923 uc=res->lsu; /* .. */ 1924 msua=ua+D2U(lhs->digits)-1; /* -> msu of lhs */ 1925 msub=ub+D2U(rhs->digits)-1; /* -> msu of rhs */ 1926 msuc=uc+D2U(set->digits)-1; /* -> msu of result */ 1927 msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */ 1928 for (; uc<=msuc; ua++, ub++, uc++) { /* Unit loop */ 1929 Unit a, b; /* extract units */ 1930 if (ua>msua) a=0; 1931 else a=*ua; 1932 if (ub>msub) b=0; 1933 else b=*ub; 1934 *uc=0; /* can now write back */ 1935 if (a|b) { /* maybe 1 bits to examine */ 1936 Int i, j; 1937 /* This loop could be unrolled and/or use BIN2BCD tables */ 1938 for (i=0; i<DECDPUN; i++) { 1939 if ((a|b)&1) *uc=*uc+(Unit)powers[i]; /* effect OR */ 1940 j=a%10; 1941 a=a/10; 1942 j|=b%10; 1943 b=b/10; 1944 if (j>1) { 1945 decStatus(res, DEC_Invalid_operation, set); 1946 return res; 1947 } 1948 if (uc==msuc && i==msudigs-1) break; /* just did final digit */ 1949 } /* each digit */ 1950 } /* non-zero */ 1951 } /* each unit */ 1952 /* [here uc-1 is the msu of the result] */ 1953 res->digits=decGetDigits(res->lsu, uc-res->lsu); 1954 res->exponent=0; /* integer */ 1955 res->bits=0; /* sign=0 */ 1956 return res; /* [no status to set] */ 1957 } /* decNumberOr */ 1958 1959 /* ------------------------------------------------------------------ */ 1960 /* decNumberPlus -- prefix plus operator */ 1961 /* */ 1962 /* This computes C = 0 + A */ 1963 /* */ 1964 /* res is C, the result. C may be A */ 1965 /* rhs is A */ 1966 /* set is the context */ 1967 /* */ 1968 /* See also decNumberCopy for a quiet bitwise version of this. */ 1969 /* C must have space for set->digits digits. */ 1970 /* ------------------------------------------------------------------ */ 1971 /* This simply uses AddOp; Add will take fast path after preparing A. */ 1972 /* Performance is a concern here, as this routine is often used to */ 1973 /* check operands and apply rounding and overflow/underflow testing. */ 1974 /* ------------------------------------------------------------------ */ 1975 decNumber * decNumberPlus(decNumber *res, const decNumber *rhs, 1976 decContext *set) { 1977 decNumber dzero; 1978 uInt status=0; /* accumulator */ 1979 #if DECCHECK 1980 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; 1981 #endif 1982 1983 decNumberZero(&dzero); /* make 0 */ 1984 dzero.exponent=rhs->exponent; /* [no coefficient expansion] */ 1985 decAddOp(res, &dzero, rhs, set, 0, &status); 1986 if (status!=0) decStatus(res, status, set); 1987 #if DECCHECK 1988 decCheckInexact(res, set); 1989 #endif 1990 return res; 1991 } /* decNumberPlus */ 1992 1993 /* ------------------------------------------------------------------ */ 1994 /* decNumberMultiply -- multiply two Numbers */ 1995 /* */ 1996 /* This computes C = A x B */ 1997 /* */ 1998 /* res is C, the result. C may be A and/or B (e.g., X=X+X) */ 1999 /* lhs is A */ 2000 /* rhs is B */ 2001 /* set is the context */ 2002 /* */ 2003 /* C must have space for set->digits digits. */ 2004 /* ------------------------------------------------------------------ */ 2005 decNumber * decNumberMultiply(decNumber *res, const decNumber *lhs, 2006 const decNumber *rhs, decContext *set) { 2007 uInt status=0; /* accumulator */ 2008 decMultiplyOp(res, lhs, rhs, set, &status); 2009 if (status!=0) decStatus(res, status, set); 2010 #if DECCHECK 2011 decCheckInexact(res, set); 2012 #endif 2013 return res; 2014 } /* decNumberMultiply */ 2015 2016 /* ------------------------------------------------------------------ */ 2017 /* decNumberPower -- raise a number to a power */ 2018 /* */ 2019 /* This computes C = A ** B */ 2020 /* */ 2021 /* res is C, the result. C may be A and/or B (e.g., X=X**X) */ 2022 /* lhs is A */ 2023 /* rhs is B */ 2024 /* set is the context */ 2025 /* */ 2026 /* C must have space for set->digits digits. */ 2027 /* */ 2028 /* Mathematical function restrictions apply (see above); a NaN is */ 2029 /* returned with Invalid_operation if a restriction is violated. */ 2030 /* */ 2031 /* However, if 1999999997<=B<=999999999 and B is an integer then the */ 2032 /* restrictions on A and the context are relaxed to the usual bounds, */ 2033 /* for compatibility with the earlier (integer power only) version */ 2034 /* of this function. */ 2035 /* */ 2036 /* When B is an integer, the result may be exact, even if rounded. */ 2037 /* */ 2038 /* The final result is rounded according to the context; it will */ 2039 /* almost always be correctly rounded, but may be up to 1 ulp in */ 2040 /* error in rare cases. */ 2041 /* ------------------------------------------------------------------ */ 2042 decNumber * decNumberPower(decNumber *res, const decNumber *lhs, 2043 const decNumber *rhs, decContext *set) { 2044 #if DECSUBSET 2045 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */ 2046 decNumber *allocrhs=NULL; /* .., rhs */ 2047 #endif 2048 decNumber *allocdac=NULL; /* -> allocated acc buffer, iff used */ 2049 decNumber *allocinv=NULL; /* -> allocated 1/x buffer, iff used */ 2050 Int reqdigits=set->digits; /* requested DIGITS */ 2051 Int n; /* rhs in binary */ 2052 Flag rhsint=0; /* 1 if rhs is an integer */ 2053 Flag useint=0; /* 1 if can use integer calculation */ 2054 Flag isoddint=0; /* 1 if rhs is an integer and odd */ 2055 Int i; /* work */ 2056 #if DECSUBSET 2057 Int dropped; /* .. */ 2058 #endif 2059 uInt needbytes; /* buffer size needed */ 2060 Flag seenbit; /* seen a bit while powering */ 2061 Int residue=0; /* rounding residue */ 2062 uInt status=0; /* accumulators */ 2063 uByte bits=0; /* result sign if errors */ 2064 decContext aset; /* working context */ 2065 decNumber dnOne; /* work value 1... */ 2066 /* local accumulator buffer [a decNumber, with digits+elength+1 digits] */ 2067 decNumber dacbuff[D2N(DECBUFFER+9)]; 2068 decNumber *dac=dacbuff; /* -> result accumulator */ 2069 /* same again for possible 1/lhs calculation */ 2070 decNumber invbuff[D2N(DECBUFFER+9)]; 2071 2072 #if DECCHECK 2073 if (decCheckOperands(res, lhs, rhs, set)) return res; 2074 #endif 2075 2076 do { /* protect allocated storage */ 2077 #if DECSUBSET 2078 if (!set->extended) { /* reduce operands and set status, as needed */ 2079 if (lhs->digits>reqdigits) { 2080 alloclhs=decRoundOperand(lhs, set, &status); 2081 if (alloclhs==NULL) break; 2082 lhs=alloclhs; 2083 } 2084 if (rhs->digits>reqdigits) { 2085 allocrhs=decRoundOperand(rhs, set, &status); 2086 if (allocrhs==NULL) break; 2087 rhs=allocrhs; 2088 } 2089 } 2090 #endif 2091 /* [following code does not require input rounding] */ 2092 2093 /* handle NaNs and rhs Infinity (lhs infinity is harder) */ 2094 if (SPECIALARGS) { 2095 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) { /* NaNs */ 2096 decNaNs(res, lhs, rhs, set, &status); 2097 break;} 2098 if (decNumberIsInfinite(rhs)) { /* rhs Infinity */ 2099 Flag rhsneg=rhs->bits&DECNEG; /* save rhs sign */ 2100 if (decNumberIsNegative(lhs) /* lhs<0 */ 2101 && !decNumberIsZero(lhs)) /* .. */ 2102 status|=DEC_Invalid_operation; 2103 else { /* lhs >=0 */ 2104 decNumberZero(&dnOne); /* set up 1 */ 2105 dnOne.lsu[0]=1; 2106 decNumberCompare(dac, lhs, &dnOne, set); /* lhs ? 1 */ 2107 decNumberZero(res); /* prepare for 0/1/Infinity */ 2108 if (decNumberIsNegative(dac)) { /* lhs<1 */ 2109 if (rhsneg) res->bits|=DECINF; /* +Infinity [else is +0] */ 2110 } 2111 else if (dac->lsu[0]==0) { /* lhs=1 */ 2112 /* 1**Infinity is inexact, so return fully-padded 1.0000 */ 2113 Int shift=set->digits-1; 2114 *res->lsu=1; /* was 0, make int 1 */ 2115 res->digits=decShiftToMost(res->lsu, 1, shift); 2116 res->exponent=-shift; /* make 1.0000... */ 2117 status|=DEC_Inexact|DEC_Rounded; /* deemed inexact */ 2118 } 2119 else { /* lhs>1 */ 2120 if (!rhsneg) res->bits|=DECINF; /* +Infinity [else is +0] */ 2121 } 2122 } /* lhs>=0 */ 2123 break;} 2124 /* [lhs infinity drops through] */ 2125 } /* specials */ 2126 2127 /* Original rhs may be an integer that fits and is in range */ 2128 n=decGetInt(rhs); 2129 if (n!=BADINT) { /* it is an integer */ 2130 rhsint=1; /* record the fact for 1**n */ 2131 isoddint=(Flag)n&1; /* [works even if big] */ 2132 if (n!=BIGEVEN && n!=BIGODD) /* can use integer path? */ 2133 useint=1; /* looks good */ 2134 } 2135 2136 if (decNumberIsNegative(lhs) /* -x .. */ 2137 && isoddint) bits=DECNEG; /* .. to an odd power */ 2138 2139 /* handle LHS infinity */ 2140 if (decNumberIsInfinite(lhs)) { /* [NaNs already handled] */ 2141 uByte rbits=rhs->bits; /* save */ 2142 decNumberZero(res); /* prepare */ 2143 if (n==0) *res->lsu=1; /* [-]Inf**0 => 1 */ 2144 else { 2145 /* -Inf**nonint -> error */ 2146 if (!rhsint && decNumberIsNegative(lhs)) { 2147 status|=DEC_Invalid_operation; /* -Inf**nonint is error */ 2148 break;} 2149 if (!(rbits & DECNEG)) bits|=DECINF; /* was not a **-n */ 2150 /* [otherwise will be 0 or -0] */ 2151 res->bits=bits; 2152 } 2153 break;} 2154 2155 /* similarly handle LHS zero */ 2156 if (decNumberIsZero(lhs)) { 2157 if (n==0) { /* 0**0 => Error */ 2158 #if DECSUBSET 2159 if (!set->extended) { /* [unless subset] */ 2160 decNumberZero(res); 2161 *res->lsu=1; /* return 1 */ 2162 break;} 2163 #endif 2164 status|=DEC_Invalid_operation; 2165 } 2166 else { /* 0**x */ 2167 uByte rbits=rhs->bits; /* save */ 2168 if (rbits & DECNEG) { /* was a 0**(-n) */ 2169 #if DECSUBSET 2170 if (!set->extended) { /* [bad if subset] */ 2171 status|=DEC_Invalid_operation; 2172 break;} 2173 #endif 2174 bits|=DECINF; 2175 } 2176 decNumberZero(res); /* prepare */ 2177 /* [otherwise will be 0 or -0] */ 2178 res->bits=bits; 2179 } 2180 break;} 2181 2182 /* here both lhs and rhs are finite; rhs==0 is handled in the */ 2183 /* integer path. Next handle the non-integer cases */ 2184 if (!useint) { /* non-integral rhs */ 2185 /* any -ve lhs is bad, as is either operand or context out of */ 2186 /* bounds */ 2187 if (decNumberIsNegative(lhs)) { 2188 status|=DEC_Invalid_operation; 2189 break;} 2190 if (decCheckMath(lhs, set, &status) 2191 || decCheckMath(rhs, set, &status)) break; /* variable status */ 2192 2193 decContextDefault(&aset, DEC_INIT_DECIMAL64); /* clean context */ 2194 aset.emax=DEC_MAX_MATH; /* usual bounds */ 2195 aset.emin=-DEC_MAX_MATH; /* .. */ 2196 aset.clamp=0; /* and no concrete format */ 2197 2198 /* calculate the result using exp(ln(lhs)*rhs), which can */ 2199 /* all be done into the accumulator, dac. The precision needed */ 2200 /* is enough to contain the full information in the lhs (which */ 2201 /* is the total digits, including exponent), or the requested */ 2202 /* precision, if larger, + 4; 6 is used for the exponent */ 2203 /* maximum length, and this is also used when it is shorter */ 2204 /* than the requested digits as it greatly reduces the >0.5 ulp */ 2205 /* cases at little cost (because Ln doubles digits each */ 2206 /* iteration so a few extra digits rarely causes an extra */ 2207 /* iteration) */ 2208 aset.digits=MAXI(lhs->digits, set->digits)+6+4; 2209 } /* non-integer rhs */ 2210 2211 else { /* rhs is in-range integer */ 2212 if (n==0) { /* x**0 = 1 */ 2213 /* (0**0 was handled above) */ 2214 decNumberZero(res); /* result=1 */ 2215 *res->lsu=1; /* .. */ 2216 break;} 2217 /* rhs is a non-zero integer */ 2218 if (n<0) n=-n; /* use abs(n) */ 2219 2220 aset=*set; /* clone the context */ 2221 aset.round=DEC_ROUND_HALF_EVEN; /* internally use balanced */ 2222 /* calculate the working DIGITS */ 2223 aset.digits=reqdigits+(rhs->digits+rhs->exponent)+2; 2224 #if DECSUBSET 2225 if (!set->extended) aset.digits--; /* use classic precision */ 2226 #endif 2227 /* it's an error if this is more than can be handled */ 2228 if (aset.digits>DECNUMMAXP) {status|=DEC_Invalid_operation; break;} 2229 } /* integer path */ 2230 2231 /* aset.digits is the count of digits for the accumulator needed */ 2232 /* if accumulator is too long for local storage, then allocate */ 2233 needbytes=sizeof(decNumber)+(D2U(aset.digits)-1)*sizeof(Unit); 2234 /* [needbytes also used below if 1/lhs needed] */ 2235 if (needbytes>sizeof(dacbuff)) { 2236 allocdac=(decNumber *)malloc(needbytes); 2237 if (allocdac==NULL) { /* hopeless -- abandon */ 2238 status|=DEC_Insufficient_storage; 2239 break;} 2240 dac=allocdac; /* use the allocated space */ 2241 } 2242 /* here, aset is set up and accumulator is ready for use */ 2243 2244 if (!useint) { /* non-integral rhs */ 2245 /* x ** y; special-case x=1 here as it will otherwise always */ 2246 /* reduce to integer 1; decLnOp has a fastpath which detects */ 2247 /* the case of x=1 */ 2248 decLnOp(dac, lhs, &aset, &status); /* dac=ln(lhs) */ 2249 /* [no error possible, as lhs 0 already handled] */ 2250 if (ISZERO(dac)) { /* x==1, 1.0, etc. */ 2251 /* need to return fully-padded 1.0000 etc., but rhsint->1 */ 2252 *dac->lsu=1; /* was 0, make int 1 */ 2253 if (!rhsint) { /* add padding */ 2254 Int shift=set->digits-1; 2255 dac->digits=decShiftToMost(dac->lsu, 1, shift); 2256 dac->exponent=-shift; /* make 1.0000... */ 2257 status|=DEC_Inexact|DEC_Rounded; /* deemed inexact */ 2258 } 2259 } 2260 else { 2261 decMultiplyOp(dac, dac, rhs, &aset, &status); /* dac=dac*rhs */ 2262 decExpOp(dac, dac, &aset, &status); /* dac=exp(dac) */ 2263 } 2264 /* and drop through for final rounding */ 2265 } /* non-integer rhs */ 2266 2267 else { /* carry on with integer */ 2268 decNumberZero(dac); /* acc=1 */ 2269 *dac->lsu=1; /* .. */ 2270 2271 /* if a negative power the constant 1 is needed, and if not subset */ 2272 /* invert the lhs now rather than inverting the result later */ 2273 if (decNumberIsNegative(rhs)) { /* was a **-n [hence digits>0] */ 2274 decNumber *inv=invbuff; /* assume use fixed buffer */ 2275 decNumberCopy(&dnOne, dac); /* dnOne=1; [needed now or later] */ 2276 #if DECSUBSET 2277 if (set->extended) { /* need to calculate 1/lhs */ 2278 #endif 2279 /* divide lhs into 1, putting result in dac [dac=1/dac] */ 2280 decDivideOp(dac, &dnOne, lhs, &aset, DIVIDE, &status); 2281 /* now locate or allocate space for the inverted lhs */ 2282 if (needbytes>sizeof(invbuff)) { 2283 allocinv=(decNumber *)malloc(needbytes); 2284 if (allocinv==NULL) { /* hopeless -- abandon */ 2285 status|=DEC_Insufficient_storage; 2286 break;} 2287 inv=allocinv; /* use the allocated space */ 2288 } 2289 /* [inv now points to big-enough buffer or allocated storage] */ 2290 decNumberCopy(inv, dac); /* copy the 1/lhs */ 2291 decNumberCopy(dac, &dnOne); /* restore acc=1 */ 2292 lhs=inv; /* .. and go forward with new lhs */ 2293 #if DECSUBSET 2294 } 2295 #endif 2296 } 2297 2298 /* Raise-to-the-power loop... */ 2299 seenbit=0; /* set once a 1-bit is encountered */ 2300 for (i=1;;i++){ /* for each bit [top bit ignored] */ 2301 /* abandon if had overflow or terminal underflow */ 2302 if (status & (DEC_Overflow|DEC_Underflow)) { /* interesting? */ 2303 if (status&DEC_Overflow || ISZERO(dac)) break; 2304 } 2305 /* [the following two lines revealed an optimizer bug in a C++ */ 2306 /* compiler, with symptom: 5**3 -> 25, when n=n+n was used] */ 2307 n=n<<1; /* move next bit to testable position */ 2308 if (n<0) { /* top bit is set */ 2309 seenbit=1; /* OK, significant bit seen */ 2310 decMultiplyOp(dac, dac, lhs, &aset, &status); /* dac=dac*x */ 2311 } 2312 if (i==31) break; /* that was the last bit */ 2313 if (!seenbit) continue; /* no need to square 1 */ 2314 decMultiplyOp(dac, dac, dac, &aset, &status); /* dac=dac*dac [square] */ 2315 } /*i*/ /* 32 bits */ 2316 2317 /* complete internal overflow or underflow processing */ 2318 if (status & (DEC_Overflow|DEC_Underflow)) { 2319 #if DECSUBSET 2320 /* If subset, and power was negative, reverse the kind of -erflow */ 2321 /* [1/x not yet done] */ 2322 if (!set->extended && decNumberIsNegative(rhs)) { 2323 if (status & DEC_Overflow) 2324 status^=DEC_Overflow | DEC_Underflow | DEC_Subnormal; 2325 else { /* trickier -- Underflow may or may not be set */ 2326 status&=~(DEC_Underflow | DEC_Subnormal); /* [one or both] */ 2327 status|=DEC_Overflow; 2328 } 2329 } 2330 #endif 2331 dac->bits=(dac->bits & ~DECNEG) | bits; /* force correct sign */ 2332 /* round subnormals [to set.digits rather than aset.digits] */ 2333 /* or set overflow result similarly as required */ 2334 decFinalize(dac, set, &residue, &status); 2335 decNumberCopy(res, dac); /* copy to result (is now OK length) */ 2336 break; 2337 } 2338 2339 #if DECSUBSET 2340 if (!set->extended && /* subset math */ 2341 decNumberIsNegative(rhs)) { /* was a **-n [hence digits>0] */ 2342 /* so divide result into 1 [dac=1/dac] */ 2343 decDivideOp(dac, &dnOne, dac, &aset, DIVIDE, &status); 2344 } 2345 #endif 2346 } /* rhs integer path */ 2347 2348 /* reduce result to the requested length and copy to result */ 2349 decCopyFit(res, dac, set, &residue, &status); 2350 decFinish(res, set, &residue, &status); /* final cleanup */ 2351 #if DECSUBSET 2352 if (!set->extended) decTrim(res, set, 0, &dropped); /* trailing zeros */ 2353 #endif 2354 } while(0); /* end protected */ 2355 2356 if (allocdac!=NULL) free(allocdac); /* drop any storage used */ 2357 if (allocinv!=NULL) free(allocinv); /* .. */ 2358 #if DECSUBSET 2359 if (alloclhs!=NULL) free(alloclhs); /* .. */ 2360 if (allocrhs!=NULL) free(allocrhs); /* .. */ 2361 #endif 2362 if (status!=0) decStatus(res, status, set); 2363 #if DECCHECK 2364 decCheckInexact(res, set); 2365 #endif 2366 return res; 2367 } /* decNumberPower */ 2368 2369 /* ------------------------------------------------------------------ */ 2370 /* decNumberQuantize -- force exponent to requested value */ 2371 /* */ 2372 /* This computes C = op(A, B), where op adjusts the coefficient */ 2373 /* of C (by rounding or shifting) such that the exponent (-scale) */ 2374 /* of C has exponent of B. The numerical value of C will equal A, */ 2375 /* except for the effects of any rounding that occurred. */ 2376 /* */ 2377 /* res is C, the result. C may be A or B */ 2378 /* lhs is A, the number to adjust */ 2379 /* rhs is B, the number with exponent to match */ 2380 /* set is the context */ 2381 /* */ 2382 /* C must have space for set->digits digits. */ 2383 /* */ 2384 /* Unless there is an error or the result is infinite, the exponent */ 2385 /* after the operation is guaranteed to be equal to that of B. */ 2386 /* ------------------------------------------------------------------ */ 2387 decNumber * decNumberQuantize(decNumber *res, const decNumber *lhs, 2388 const decNumber *rhs, decContext *set) { 2389 uInt status=0; /* accumulator */ 2390 decQuantizeOp(res, lhs, rhs, set, 1, &status); 2391 if (status!=0) decStatus(res, status, set); 2392 return res; 2393 } /* decNumberQuantize */ 2394 2395 /* ------------------------------------------------------------------ */ 2396 /* decNumberReduce -- remove trailing zeros */ 2397 /* */ 2398 /* This computes C = 0 + A, and normalizes the result */ 2399 /* */ 2400 /* res is C, the result. C may be A */ 2401 /* rhs is A */ 2402 /* set is the context */ 2403 /* */ 2404 /* C must have space for set->digits digits. */ 2405 /* ------------------------------------------------------------------ */ 2406 /* Previously known as Normalize */ 2407 decNumber * decNumberNormalize(decNumber *res, const decNumber *rhs, 2408 decContext *set) { 2409 return decNumberReduce(res, rhs, set); 2410 } /* decNumberNormalize */ 2411 2412 decNumber * decNumberReduce(decNumber *res, const decNumber *rhs, 2413 decContext *set) { 2414 #if DECSUBSET 2415 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */ 2416 #endif 2417 uInt status=0; /* as usual */ 2418 Int residue=0; /* as usual */ 2419 Int dropped; /* work */ 2420 2421 #if DECCHECK 2422 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; 2423 #endif 2424 2425 do { /* protect allocated storage */ 2426 #if DECSUBSET 2427 if (!set->extended) { 2428 /* reduce operand and set lostDigits status, as needed */ 2429 if (rhs->digits>set->digits) { 2430 allocrhs=decRoundOperand(rhs, set, &status); 2431 if (allocrhs==NULL) break; 2432 rhs=allocrhs; 2433 } 2434 } 2435 #endif 2436 /* [following code does not require input rounding] */ 2437 2438 /* Infinities copy through; NaNs need usual treatment */ 2439 if (decNumberIsNaN(rhs)) { 2440 decNaNs(res, rhs, NULL, set, &status); 2441 break; 2442 } 2443 2444 /* reduce result to the requested length and copy to result */ 2445 decCopyFit(res, rhs, set, &residue, &status); /* copy & round */ 2446 decFinish(res, set, &residue, &status); /* cleanup/set flags */ 2447 decTrim(res, set, 1, &dropped); /* normalize in place */ 2448 } while(0); /* end protected */ 2449 2450 #if DECSUBSET 2451 if (allocrhs !=NULL) free(allocrhs); /* .. */ 2452 #endif 2453 if (status!=0) decStatus(res, status, set);/* then report status */ 2454 return res; 2455 } /* decNumberReduce */ 2456 2457 /* ------------------------------------------------------------------ */ 2458 /* decNumberRescale -- force exponent to requested value */ 2459 /* */ 2460 /* This computes C = op(A, B), where op adjusts the coefficient */ 2461 /* of C (by rounding or shifting) such that the exponent (-scale) */ 2462 /* of C has the value B. The numerical value of C will equal A, */ 2463 /* except for the effects of any rounding that occurred. */ 2464 /* */ 2465 /* res is C, the result. C may be A or B */ 2466 /* lhs is A, the number to adjust */ 2467 /* rhs is B, the requested exponent */ 2468 /* set is the context */ 2469 /* */ 2470 /* C must have space for set->digits digits. */ 2471 /* */ 2472 /* Unless there is an error or the result is infinite, the exponent */ 2473 /* after the operation is guaranteed to be equal to B. */ 2474 /* ------------------------------------------------------------------ */ 2475 decNumber * decNumberRescale(decNumber *res, const decNumber *lhs, 2476 const decNumber *rhs, decContext *set) { 2477 uInt status=0; /* accumulator */ 2478 decQuantizeOp(res, lhs, rhs, set, 0, &status); 2479 if (status!=0) decStatus(res, status, set); 2480 return res; 2481 } /* decNumberRescale */ 2482 2483 /* ------------------------------------------------------------------ */ 2484 /* decNumberRemainder -- divide and return remainder */ 2485 /* */ 2486 /* This computes C = A % B */ 2487 /* */ 2488 /* res is C, the result. C may be A and/or B (e.g., X=X%X) */ 2489 /* lhs is A */ 2490 /* rhs is B */ 2491 /* set is the context */ 2492 /* */ 2493 /* C must have space for set->digits digits. */ 2494 /* ------------------------------------------------------------------ */ 2495 decNumber * decNumberRemainder(decNumber *res, const decNumber *lhs, 2496 const decNumber *rhs, decContext *set) { 2497 uInt status=0; /* accumulator */ 2498 decDivideOp(res, lhs, rhs, set, REMAINDER, &status); 2499 if (status!=0) decStatus(res, status, set); 2500 #if DECCHECK 2501 decCheckInexact(res, set); 2502 #endif 2503 return res; 2504 } /* decNumberRemainder */ 2505 2506 /* ------------------------------------------------------------------ */ 2507 /* decNumberRemainderNear -- divide and return remainder from nearest */ 2508 /* */ 2509 /* This computes C = A % B, where % is the IEEE remainder operator */ 2510 /* */ 2511 /* res is C, the result. C may be A and/or B (e.g., X=X%X) */ 2512 /* lhs is A */ 2513 /* rhs is B */ 2514 /* set is the context */ 2515 /* */ 2516 /* C must have space for set->digits digits. */ 2517 /* ------------------------------------------------------------------ */ 2518 decNumber * decNumberRemainderNear(decNumber *res, const decNumber *lhs, 2519 const decNumber *rhs, decContext *set) { 2520 uInt status=0; /* accumulator */ 2521 decDivideOp(res, lhs, rhs, set, REMNEAR, &status); 2522 if (status!=0) decStatus(res, status, set); 2523 #if DECCHECK 2524 decCheckInexact(res, set); 2525 #endif 2526 return res; 2527 } /* decNumberRemainderNear */ 2528 2529 /* ------------------------------------------------------------------ */ 2530 /* decNumberRotate -- rotate the coefficient of a Number left/right */ 2531 /* */ 2532 /* This computes C = A rot B (in base ten and rotating set->digits */ 2533 /* digits). */ 2534 /* */ 2535 /* res is C, the result. C may be A and/or B (e.g., X=XrotX) */ 2536 /* lhs is A */ 2537 /* rhs is B, the number of digits to rotate (-ve to right) */ 2538 /* set is the context */ 2539 /* */ 2540 /* The digits of the coefficient of A are rotated to the left (if B */ 2541 /* is positive) or to the right (if B is negative) without adjusting */ 2542 /* the exponent or the sign of A. If lhs->digits is less than */ 2543 /* set->digits the coefficient is padded with zeros on the left */ 2544 /* before the rotate. Any leading zeros in the result are removed */ 2545 /* as usual. */ 2546 /* */ 2547 /* B must be an integer (q=0) and in the range -set->digits through */ 2548 /* +set->digits. */ 2549 /* C must have space for set->digits digits. */ 2550 /* NaNs are propagated as usual. Infinities are unaffected (but */ 2551 /* B must be valid). No status is set unless B is invalid or an */ 2552 /* operand is an sNaN. */ 2553 /* ------------------------------------------------------------------ */ 2554 decNumber * decNumberRotate(decNumber *res, const decNumber *lhs, 2555 const decNumber *rhs, decContext *set) { 2556 uInt status=0; /* accumulator */ 2557 Int rotate; /* rhs as an Int */ 2558 2559 #if DECCHECK 2560 if (decCheckOperands(res, lhs, rhs, set)) return res; 2561 #endif 2562 2563 /* NaNs propagate as normal */ 2564 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) 2565 decNaNs(res, lhs, rhs, set, &status); 2566 /* rhs must be an integer */ 2567 else if (decNumberIsInfinite(rhs) || rhs->exponent!=0) 2568 status=DEC_Invalid_operation; 2569 else { /* both numeric, rhs is an integer */ 2570 rotate=decGetInt(rhs); /* [cannot fail] */ 2571 if (rotate==BADINT /* something bad .. */ 2572 || rotate==BIGODD || rotate==BIGEVEN /* .. very big .. */ 2573 || abs(rotate)>set->digits) /* .. or out of range */ 2574 status=DEC_Invalid_operation; 2575 else { /* rhs is OK */ 2576 decNumberCopy(res, lhs); 2577 /* convert -ve rotate to equivalent positive rotation */ 2578 if (rotate<0) rotate=set->digits+rotate; 2579 if (rotate!=0 && rotate!=set->digits /* zero or full rotation */ 2580 && !decNumberIsInfinite(res)) { /* lhs was infinite */ 2581 /* left-rotate to do; 0 < rotate < set->digits */ 2582 uInt units, shift; /* work */ 2583 uInt msudigits; /* digits in result msu */ 2584 Unit *msu=res->lsu+D2U(res->digits)-1; /* current msu */ 2585 Unit *msumax=res->lsu+D2U(set->digits)-1; /* rotation msu */ 2586 for (msu++; msu<=msumax; msu++) *msu=0; /* ensure high units=0 */ 2587 res->digits=set->digits; /* now full-length */ 2588 msudigits=MSUDIGITS(res->digits); /* actual digits in msu */ 2589 2590 /* rotation here is done in-place, in three steps */ 2591 /* 1. shift all to least up to one unit to unit-align final */ 2592 /* lsd [any digits shifted out are rotated to the left, */ 2593 /* abutted to the original msd (which may require split)] */ 2594 /* */ 2595 /* [if there are no whole units left to rotate, the */ 2596 /* rotation is now complete] */ 2597 /* */ 2598 /* 2. shift to least, from below the split point only, so that */ 2599 /* the final msd is in the right place in its Unit [any */ 2600 /* digits shifted out will fit exactly in the current msu, */ 2601 /* left aligned, no split required] */ 2602 /* */ 2603 /* 3. rotate all the units by reversing left part, right */ 2604 /* part, and then whole */ 2605 /* */ 2606 /* example: rotate right 8 digits (2 units + 2), DECDPUN=3. */ 2607 /* */ 2608 /* start: 00a bcd efg hij klm npq */ 2609 /* */ 2610 /* 1a 000 0ab cde fgh|ijk lmn [pq saved] */ 2611 /* 1b 00p qab cde fgh|ijk lmn */ 2612 /* */ 2613 /* 2a 00p qab cde fgh|00i jkl [mn saved] */ 2614 /* 2b mnp qab cde fgh|00i jkl */ 2615 /* */ 2616 /* 3a fgh cde qab mnp|00i jkl */ 2617 /* 3b fgh cde qab mnp|jkl 00i */ 2618 /* 3c 00i jkl mnp qab cde fgh */ 2619 2620 /* Step 1: amount to shift is the partial right-rotate count */ 2621 rotate=set->digits-rotate; /* make it right-rotate */ 2622 units=rotate/DECDPUN; /* whole units to rotate */ 2623 shift=rotate%DECDPUN; /* left-over digits count */ 2624 if (shift>0) { /* not an exact number of units */ 2625 uInt save=res->lsu[0]%powers[shift]; /* save low digit(s) */ 2626 decShiftToLeast(res->lsu, D2U(res->digits), shift); 2627 if (shift>msudigits) { /* msumax-1 needs >0 digits */ 2628 uInt rem=save%powers[shift-msudigits];/* split save */ 2629 *msumax=(Unit)(save/powers[shift-msudigits]); /* and insert */ 2630 *(msumax-1)=*(msumax-1) 2631 +(Unit)(rem*powers[DECDPUN-(shift-msudigits)]); /* .. */ 2632 } 2633 else { /* all fits in msumax */ 2634 *msumax=*msumax+(Unit)(save*powers[msudigits-shift]); /* [maybe *1] */ 2635 } 2636 } /* digits shift needed */ 2637 2638 /* If whole units to rotate... */ 2639 if (units>0) { /* some to do */ 2640 /* Step 2: the units to touch are the whole ones in rotate, */ 2641 /* if any, and the shift is DECDPUN-msudigits (which may be */ 2642 /* 0, again) */ 2643 shift=DECDPUN-msudigits; 2644 if (shift>0) { /* not an exact number of units */ 2645 uInt save=res->lsu[0]%powers[shift]; /* save low digit(s) */ 2646 decShiftToLeast(res->lsu, units, shift); 2647 *msumax=*msumax+(Unit)(save*powers[msudigits]); 2648 } /* partial shift needed */ 2649 2650 /* Step 3: rotate the units array using triple reverse */ 2651 /* (reversing is easy and fast) */ 2652 decReverse(res->lsu+units, msumax); /* left part */ 2653 decReverse(res->lsu, res->lsu+units-1); /* right part */ 2654 decReverse(res->lsu, msumax); /* whole */ 2655 } /* whole units to rotate */ 2656 /* the rotation may have left an undetermined number of zeros */ 2657 /* on the left, so true length needs to be calculated */ 2658 res->digits=decGetDigits(res->lsu, msumax-res->lsu+1); 2659 } /* rotate needed */ 2660 } /* rhs OK */ 2661 } /* numerics */ 2662 if (status!=0) decStatus(res, status, set); 2663 return res; 2664 } /* decNumberRotate */ 2665 2666 /* ------------------------------------------------------------------ */ 2667 /* decNumberSameQuantum -- test for equal exponents */ 2668 /* */ 2669 /* res is the result number, which will contain either 0 or 1 */ 2670 /* lhs is a number to test */ 2671 /* rhs is the second (usually a pattern) */ 2672 /* */ 2673 /* No errors are possible and no context is needed. */ 2674 /* ------------------------------------------------------------------ */ 2675 decNumber * decNumberSameQuantum(decNumber *res, const decNumber *lhs, 2676 const decNumber *rhs) { 2677 Unit ret=0; /* return value */ 2678 2679 #if DECCHECK 2680 if (decCheckOperands(res, lhs, rhs, DECUNCONT)) return res; 2681 #endif 2682 2683 if (SPECIALARGS) { 2684 if (decNumberIsNaN(lhs) && decNumberIsNaN(rhs)) ret=1; 2685 else if (decNumberIsInfinite(lhs) && decNumberIsInfinite(rhs)) ret=1; 2686 /* [anything else with a special gives 0] */ 2687 } 2688 else if (lhs->exponent==rhs->exponent) ret=1; 2689 2690 decNumberZero(res); /* OK to overwrite an operand now */ 2691 *res->lsu=ret; 2692 return res; 2693 } /* decNumberSameQuantum */ 2694 2695 /* ------------------------------------------------------------------ */ 2696 /* decNumberScaleB -- multiply by a power of 10 */ 2697 /* */ 2698 /* This computes C = A x 10**B where B is an integer (q=0) with */ 2699 /* maximum magnitude 2*(emax+digits) */ 2700 /* */ 2701 /* res is C, the result. C may be A or B */ 2702 /* lhs is A, the number to adjust */ 2703 /* rhs is B, the requested power of ten to use */ 2704 /* set is the context */ 2705 /* */ 2706 /* C must have space for set->digits digits. */ 2707 /* */ 2708 /* The result may underflow or overflow. */ 2709 /* ------------------------------------------------------------------ */ 2710 decNumber * decNumberScaleB(decNumber *res, const decNumber *lhs, 2711 const decNumber *rhs, decContext *set) { 2712 Int reqexp; /* requested exponent change [B] */ 2713 uInt status=0; /* accumulator */ 2714 Int residue; /* work */ 2715 2716 #if DECCHECK 2717 if (decCheckOperands(res, lhs, rhs, set)) return res; 2718 #endif 2719 2720 /* Handle special values except lhs infinite */ 2721 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) 2722 decNaNs(res, lhs, rhs, set, &status); 2723 /* rhs must be an integer */ 2724 else if (decNumberIsInfinite(rhs) || rhs->exponent!=0) 2725 status=DEC_Invalid_operation; 2726 else { 2727 /* lhs is a number; rhs is a finite with q==0 */ 2728 reqexp=decGetInt(rhs); /* [cannot fail] */ 2729 if (reqexp==BADINT /* something bad .. */ 2730 || reqexp==BIGODD || reqexp==BIGEVEN /* .. very big .. */ 2731 || abs(reqexp)>(2*(set->digits+set->emax))) /* .. or out of range */ 2732 status=DEC_Invalid_operation; 2733 else { /* rhs is OK */ 2734 decNumberCopy(res, lhs); /* all done if infinite lhs */ 2735 if (!decNumberIsInfinite(res)) { /* prepare to scale */ 2736 res->exponent+=reqexp; /* adjust the exponent */ 2737 residue=0; 2738 decFinalize(res, set, &residue, &status); /* .. and check */ 2739 } /* finite LHS */ 2740 } /* rhs OK */ 2741 } /* rhs finite */ 2742 if (status!=0) decStatus(res, status, set); 2743 return res; 2744 } /* decNumberScaleB */ 2745 2746 /* ------------------------------------------------------------------ */ 2747 /* decNumberShift -- shift the coefficient of a Number left or right */ 2748 /* */ 2749 /* This computes C = A << B or C = A >> -B (in base ten). */ 2750 /* */ 2751 /* res is C, the result. C may be A and/or B (e.g., X=X<<X) */ 2752 /* lhs is A */ 2753 /* rhs is B, the number of digits to shift (-ve to right) */ 2754 /* set is the context */ 2755 /* */ 2756 /* The digits of the coefficient of A are shifted to the left (if B */ 2757 /* is positive) or to the right (if B is negative) without adjusting */ 2758 /* the exponent or the sign of A. */ 2759 /* */ 2760 /* B must be an integer (q=0) and in the range -set->digits through */ 2761 /* +set->digits. */ 2762 /* C must have space for set->digits digits. */ 2763 /* NaNs are propagated as usual. Infinities are unaffected (but */ 2764 /* B must be valid). No status is set unless B is invalid or an */ 2765 /* operand is an sNaN. */ 2766 /* ------------------------------------------------------------------ */ 2767 decNumber * decNumberShift(decNumber *res, const decNumber *lhs, 2768 const decNumber *rhs, decContext *set) { 2769 uInt status=0; /* accumulator */ 2770 Int shift; /* rhs as an Int */ 2771 2772 #if DECCHECK 2773 if (decCheckOperands(res, lhs, rhs, set)) return res; 2774 #endif 2775 2776 /* NaNs propagate as normal */ 2777 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) 2778 decNaNs(res, lhs, rhs, set, &status); 2779 /* rhs must be an integer */ 2780 else if (decNumberIsInfinite(rhs) || rhs->exponent!=0) 2781 status=DEC_Invalid_operation; 2782 else { /* both numeric, rhs is an integer */ 2783 shift=decGetInt(rhs); /* [cannot fail] */ 2784 if (shift==BADINT /* something bad .. */ 2785 || shift==BIGODD || shift==BIGEVEN /* .. very big .. */ 2786 || abs(shift)>set->digits) /* .. or out of range */ 2787 status=DEC_Invalid_operation; 2788 else { /* rhs is OK */ 2789 decNumberCopy(res, lhs); 2790 if (shift!=0 && !decNumberIsInfinite(res)) { /* something to do */ 2791 if (shift>0) { /* to left */ 2792 if (shift==set->digits) { /* removing all */ 2793 *res->lsu=0; /* so place 0 */ 2794 res->digits=1; /* .. */ 2795 } 2796 else { /* */ 2797 /* first remove leading digits if necessary */ 2798 if (res->digits+shift>set->digits) { 2799 decDecap(res, res->digits+shift-set->digits); 2800 /* that updated res->digits; may have gone to 1 (for a */ 2801 /* single digit or for zero */ 2802 } 2803 if (res->digits>1 || *res->lsu) /* if non-zero.. */ 2804 res->digits=decShiftToMost(res->lsu, res->digits, shift); 2805 } /* partial left */ 2806 } /* left */ 2807 else { /* to right */ 2808 if (-shift>=res->digits) { /* discarding all */ 2809 *res->lsu=0; /* so place 0 */ 2810 res->digits=1; /* .. */ 2811 } 2812 else { 2813 decShiftToLeast(res->lsu, D2U(res->digits), -shift); 2814 res->digits-=(-shift); 2815 } 2816 } /* to right */ 2817 } /* non-0 non-Inf shift */ 2818 } /* rhs OK */ 2819 } /* numerics */ 2820 if (status!=0) decStatus(res, status, set); 2821 return res; 2822 } /* decNumberShift */ 2823 2824 /* ------------------------------------------------------------------ */ 2825 /* decNumberSquareRoot -- square root operator */ 2826 /* */ 2827 /* This computes C = squareroot(A) */ 2828 /* */ 2829 /* res is C, the result. C may be A */ 2830 /* rhs is A */ 2831 /* set is the context; note that rounding mode has no effect */ 2832 /* */ 2833 /* C must have space for set->digits digits. */ 2834 /* ------------------------------------------------------------------ */ 2835 /* This uses the following varying-precision algorithm in: */ 2836 /* */ 2837 /* Properly Rounded Variable Precision Square Root, T. E. Hull and */ 2838 /* A. Abrham, ACM Transactions on Mathematical Software, Vol 11 #3, */ 2839 /* pp229-237, ACM, September 1985. */ 2840 /* */ 2841 /* The square-root is calculated using Newton's method, after which */ 2842 /* a check is made to ensure the result is correctly rounded. */ 2843 /* */ 2844 /* % [Reformatted original Numerical Turing source code follows.] */ 2845 /* function sqrt(x : real) : real */ 2846 /* % sqrt(x) returns the properly rounded approximation to the square */ 2847 /* % root of x, in the precision of the calling environment, or it */ 2848 /* % fails if x < 0. */ 2849 /* % t e hull and a abrham, august, 1984 */ 2850 /* if x <= 0 then */ 2851 /* if x < 0 then */ 2852 /* assert false */ 2853 /* else */ 2854 /* result 0 */ 2855 /* end if */ 2856 /* end if */ 2857 /* var f := setexp(x, 0) % fraction part of x [0.1 <= x < 1] */ 2858 /* var e := getexp(x) % exponent part of x */ 2859 /* var approx : real */ 2860 /* if e mod 2 = 0 then */ 2861 /* approx := .259 + .819 * f % approx to root of f */ 2862 /* else */ 2863 /* f := f/l0 % adjustments */ 2864 /* e := e + 1 % for odd */ 2865 /* approx := .0819 + 2.59 * f % exponent */ 2866 /* end if */ 2867 /* */ 2868 /* var p:= 3 */ 2869 /* const maxp := currentprecision + 2 */ 2870 /* loop */ 2871 /* p := min(2*p - 2, maxp) % p = 4,6,10, . . . , maxp */ 2872 /* precision p */ 2873 /* approx := .5 * (approx + f/approx) */ 2874 /* exit when p = maxp */ 2875 /* end loop */ 2876 /* */ 2877 /* % approx is now within 1 ulp of the properly rounded square root */ 2878 /* % of f; to ensure proper rounding, compare squares of (approx - */ 2879 /* % l/2 ulp) and (approx + l/2 ulp) with f. */ 2880 /* p := currentprecision */ 2881 /* begin */ 2882 /* precision p + 2 */ 2883 /* const approxsubhalf := approx - setexp(.5, -p) */ 2884 /* if mulru(approxsubhalf, approxsubhalf) > f then */ 2885 /* approx := approx - setexp(.l, -p + 1) */ 2886 /* else */ 2887 /* const approxaddhalf := approx + setexp(.5, -p) */ 2888 /* if mulrd(approxaddhalf, approxaddhalf) < f then */ 2889 /* approx := approx + setexp(.l, -p + 1) */ 2890 /* end if */ 2891 /* end if */ 2892 /* end */ 2893 /* result setexp(approx, e div 2) % fix exponent */ 2894 /* end sqrt */ 2895 /* ------------------------------------------------------------------ */ 2896 decNumber * decNumberSquareRoot(decNumber *res, const decNumber *rhs, 2897 decContext *set) { 2898 decContext workset, approxset; /* work contexts */ 2899 decNumber dzero; /* used for constant zero */ 2900 Int maxp; /* largest working precision */ 2901 Int workp; /* working precision */ 2902 Int residue=0; /* rounding residue */ 2903 uInt status=0, ignore=0; /* status accumulators */ 2904 uInt rstatus; /* .. */ 2905 Int exp; /* working exponent */ 2906 Int ideal; /* ideal (preferred) exponent */ 2907 Int needbytes; /* work */ 2908 Int dropped; /* .. */ 2909 2910 #if DECSUBSET 2911 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */ 2912 #endif 2913 /* buffer for f [needs +1 in case DECBUFFER 0] */ 2914 decNumber buff[D2N(DECBUFFER+1)]; 2915 /* buffer for a [needs +2 to match likely maxp] */ 2916 decNumber bufa[D2N(DECBUFFER+2)]; 2917 /* buffer for temporary, b [must be same size as a] */ 2918 decNumber bufb[D2N(DECBUFFER+2)]; 2919 decNumber *allocbuff=NULL; /* -> allocated buff, iff allocated */ 2920 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */ 2921 decNumber *allocbufb=NULL; /* -> allocated bufb, iff allocated */ 2922 decNumber *f=buff; /* reduced fraction */ 2923 decNumber *a=bufa; /* approximation to result */ 2924 decNumber *b=bufb; /* intermediate result */ 2925 /* buffer for temporary variable, up to 3 digits */ 2926 decNumber buft[D2N(3)]; 2927 decNumber *t=buft; /* up-to-3-digit constant or work */ 2928 2929 #if DECCHECK 2930 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; 2931 #endif 2932 2933 do { /* protect allocated storage */ 2934 #if DECSUBSET 2935 if (!set->extended) { 2936 /* reduce operand and set lostDigits status, as needed */ 2937 if (rhs->digits>set->digits) { 2938 allocrhs=decRoundOperand(rhs, set, &status); 2939 if (allocrhs==NULL) break; 2940 /* [Note: 'f' allocation below could reuse this buffer if */ 2941 /* used, but as this is rare they are kept separate for clarity.] */ 2942 rhs=allocrhs; 2943 } 2944 } 2945 #endif 2946 /* [following code does not require input rounding] */ 2947 2948 /* handle infinities and NaNs */ 2949 if (SPECIALARG) { 2950 if (decNumberIsInfinite(rhs)) { /* an infinity */ 2951 if (decNumberIsNegative(rhs)) status|=DEC_Invalid_operation; 2952 else decNumberCopy(res, rhs); /* +Infinity */ 2953 } 2954 else decNaNs(res, rhs, NULL, set, &status); /* a NaN */ 2955 break; 2956 } 2957 2958 /* calculate the ideal (preferred) exponent [floor(exp/2)] */ 2959 /* [We would like to write: ideal=rhs->exponent>>1, but this */ 2960 /* generates a compiler warning. Generated code is the same.] */ 2961 ideal=(rhs->exponent&~1)/2; /* target */ 2962 2963 /* handle zeros */ 2964 if (ISZERO(rhs)) { 2965 decNumberCopy(res, rhs); /* could be 0 or -0 */ 2966 res->exponent=ideal; /* use the ideal [safe] */ 2967 /* use decFinish to clamp any out-of-range exponent, etc. */ 2968 decFinish(res, set, &residue, &status); 2969 break; 2970 } 2971 2972 /* any other -x is an oops */ 2973 if (decNumberIsNegative(rhs)) { 2974 status|=DEC_Invalid_operation; 2975 break; 2976 } 2977 2978 /* space is needed for three working variables */ 2979 /* f -- the same precision as the RHS, reduced to 0.01->0.99... */ 2980 /* a -- Hull's approximation -- precision, when assigned, is */ 2981 /* currentprecision+1 or the input argument precision, */ 2982 /* whichever is larger (+2 for use as temporary) */ 2983 /* b -- intermediate temporary result (same size as a) */ 2984 /* if any is too long for local storage, then allocate */ 2985 workp=MAXI(set->digits+1, rhs->digits); /* actual rounding precision */ 2986 maxp=workp+2; /* largest working precision */ 2987 2988 needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit); 2989 if (needbytes>(Int)sizeof(buff)) { 2990 allocbuff=(decNumber *)malloc(needbytes); 2991 if (allocbuff==NULL) { /* hopeless -- abandon */ 2992 status|=DEC_Insufficient_storage; 2993 break;} 2994 f=allocbuff; /* use the allocated space */ 2995 } 2996 /* a and b both need to be able to hold a maxp-length number */ 2997 needbytes=sizeof(decNumber)+(D2U(maxp)-1)*sizeof(Unit); 2998 if (needbytes>(Int)sizeof(bufa)) { /* [same applies to b] */ 2999 allocbufa=(decNumber *)malloc(needbytes); 3000 allocbufb=(decNumber *)malloc(needbytes); 3001 if (allocbufa==NULL || allocbufb==NULL) { /* hopeless */ 3002 status|=DEC_Insufficient_storage; 3003 break;} 3004 a=allocbufa; /* use the allocated spaces */ 3005 b=allocbufb; /* .. */ 3006 } 3007 3008 /* copy rhs -> f, save exponent, and reduce so 0.1 <= f < 1 */ 3009 decNumberCopy(f, rhs); 3010 exp=f->exponent+f->digits; /* adjusted to Hull rules */ 3011 f->exponent=-(f->digits); /* to range */ 3012 3013 /* set up working context */ 3014 decContextDefault(&workset, DEC_INIT_DECIMAL64); 3015 3016 /* [Until further notice, no error is possible and status bits */ 3017 /* (Rounded, etc.) should be ignored, not accumulated.] */ 3018 3019 /* Calculate initial approximation, and allow for odd exponent */ 3020 workset.digits=workp; /* p for initial calculation */ 3021 t->bits=0; t->digits=3; 3022 a->bits=0; a->digits=3; 3023 if ((exp & 1)==0) { /* even exponent */ 3024 /* Set t=0.259, a=0.819 */ 3025 t->exponent=-3; 3026 a->exponent=-3; 3027 #if DECDPUN>=3 3028 t->lsu[0]=259; 3029 a->lsu[0]=819; 3030 #elif DECDPUN==2 3031 t->lsu[0]=59; t->lsu[1]=2; 3032 a->lsu[0]=19; a->lsu[1]=8; 3033 #else 3034 t->lsu[0]=9; t->lsu[1]=5; t->lsu[2]=2; 3035 a->lsu[0]=9; a->lsu[1]=1; a->lsu[2]=8; 3036 #endif 3037 } 3038 else { /* odd exponent */ 3039 /* Set t=0.0819, a=2.59 */ 3040 f->exponent--; /* f=f/10 */ 3041 exp++; /* e=e+1 */ 3042 t->exponent=-4; 3043 a->exponent=-2; 3044 #if DECDPUN>=3 3045 t->lsu[0]=819; 3046 a->lsu[0]=259; 3047 #elif DECDPUN==2 3048 t->lsu[0]=19; t->lsu[1]=8; 3049 a->lsu[0]=59; a->lsu[1]=2; 3050 #else 3051 t->lsu[0]=9; t->lsu[1]=1; t->lsu[2]=8; 3052 a->lsu[0]=9; a->lsu[1]=5; a->lsu[2]=2; 3053 #endif 3054 } 3055 decMultiplyOp(a, a, f, &workset, &ignore); /* a=a*f */ 3056 decAddOp(a, a, t, &workset, 0, &ignore); /* ..+t */ 3057 /* [a is now the initial approximation for sqrt(f), calculated with */ 3058 /* currentprecision, which is also a's precision.] */ 3059 3060 /* the main calculation loop */ 3061 decNumberZero(&dzero); /* make 0 */ 3062 decNumberZero(t); /* set t = 0.5 */ 3063 t->lsu[0]=5; /* .. */ 3064 t->exponent=-1; /* .. */ 3065 workset.digits=3; /* initial p */ 3066 for (;;) { 3067 /* set p to min(2*p - 2, maxp) [hence 3; or: 4, 6, 10, ... , maxp] */ 3068 workset.digits=workset.digits*2-2; 3069 if (workset.digits>maxp) workset.digits=maxp; 3070 /* a = 0.5 * (a + f/a) */ 3071 /* [calculated at p then rounded to currentprecision] */ 3072 decDivideOp(b, f, a, &workset, DIVIDE, &ignore); /* b=f/a */ 3073 decAddOp(b, b, a, &workset, 0, &ignore); /* b=b+a */ 3074 decMultiplyOp(a, b, t, &workset, &ignore); /* a=b*0.5 */ 3075 if (a->digits==maxp) break; /* have required digits */ 3076 } /* loop */ 3077 3078 /* Here, 0.1 <= a < 1 [Hull], and a has maxp digits */ 3079 /* now reduce to length, etc.; this needs to be done with a */ 3080 /* having the correct exponent so as to handle subnormals */ 3081 /* correctly */ 3082 approxset=*set; /* get emin, emax, etc. */ 3083 approxset.round=DEC_ROUND_HALF_EVEN; 3084 a->exponent+=exp/2; /* set correct exponent */ 3085 3086 rstatus=0; /* clear status */ 3087 residue=0; /* .. and accumulator */ 3088 decCopyFit(a, a, &approxset, &residue, &rstatus); /* reduce (if needed) */ 3089 decFinish(a, &approxset, &residue, &rstatus); /* clean and finalize */ 3090 3091 /* Overflow was possible if the input exponent was out-of-range, */ 3092 /* in which case quit */ 3093 if (rstatus&DEC_Overflow) { 3094 status=rstatus; /* use the status as-is */ 3095 decNumberCopy(res, a); /* copy to result */ 3096 break; 3097 } 3098 3099 /* Preserve status except Inexact/Rounded */ 3100 status|=(rstatus & ~(DEC_Rounded|DEC_Inexact)); 3101 3102 /* Carry out the Hull correction */ 3103 a->exponent-=exp/2; /* back to 0.1->1 */ 3104 3105 /* a is now at final precision and within 1 ulp of the properly */ 3106 /* rounded square root of f; to ensure proper rounding, compare */ 3107 /* squares of (a - l/2 ulp) and (a + l/2 ulp) with f. */ 3108 /* Here workset.digits=maxp and t=0.5, and a->digits determines */ 3109 /* the ulp */ 3110 workset.digits--; /* maxp-1 is OK now */ 3111 t->exponent=-a->digits-1; /* make 0.5 ulp */ 3112 decAddOp(b, a, t, &workset, DECNEG, &ignore); /* b = a - 0.5 ulp */ 3113 workset.round=DEC_ROUND_UP; 3114 decMultiplyOp(b, b, b, &workset, &ignore); /* b = mulru(b, b) */ 3115 decCompareOp(b, f, b, &workset, COMPARE, &ignore); /* b ? f, reversed */ 3116 if (decNumberIsNegative(b)) { /* f < b [i.e., b > f] */ 3117 /* this is the more common adjustment, though both are rare */ 3118 t->exponent++; /* make 1.0 ulp */ 3119 t->lsu[0]=1; /* .. */ 3120 decAddOp(a, a, t, &workset, DECNEG, &ignore); /* a = a - 1 ulp */ 3121 /* assign to approx [round to length] */ 3122 approxset.emin-=exp/2; /* adjust to match a */ 3123 approxset.emax-=exp/2; 3124 decAddOp(a, &dzero, a, &approxset, 0, &ignore); 3125 } 3126 else { 3127 decAddOp(b, a, t, &workset, 0, &ignore); /* b = a + 0.5 ulp */ 3128 workset.round=DEC_ROUND_DOWN; 3129 decMultiplyOp(b, b, b, &workset, &ignore); /* b = mulrd(b, b) */ 3130 decCompareOp(b, b, f, &workset, COMPARE, &ignore); /* b ? f */ 3131 if (decNumberIsNegative(b)) { /* b < f */ 3132 t->exponent++; /* make 1.0 ulp */ 3133 t->lsu[0]=1; /* .. */ 3134 decAddOp(a, a, t, &workset, 0, &ignore); /* a = a + 1 ulp */ 3135 /* assign to approx [round to length] */ 3136 approxset.emin-=exp/2; /* adjust to match a */ 3137 approxset.emax-=exp/2; 3138 decAddOp(a, &dzero, a, &approxset, 0, &ignore); 3139 } 3140 } 3141 /* [no errors are possible in the above, and rounding/inexact during */ 3142 /* estimation are irrelevant, so status was not accumulated] */ 3143 3144 /* Here, 0.1 <= a < 1 (still), so adjust back */ 3145 a->exponent+=exp/2; /* set correct exponent */ 3146 3147 /* count droppable zeros [after any subnormal rounding] by */ 3148 /* trimming a copy */ 3149 decNumberCopy(b, a); 3150 decTrim(b, set, 1, &dropped); /* [drops trailing zeros] */ 3151 3152 /* Set Inexact and Rounded. The answer can only be exact if */ 3153 /* it is short enough so that squaring it could fit in workp digits, */ 3154 /* and it cannot have trailing zeros due to clamping, so these are */ 3155 /* the only (relatively rare) conditions a careful check is needed */ 3156 if (b->digits*2-1 > workp && !set->clamp) { /* cannot fit */ 3157 status|=DEC_Inexact|DEC_Rounded; 3158 } 3159 else { /* could be exact/unrounded */ 3160 uInt mstatus=0; /* local status */ 3161 decMultiplyOp(b, b, b, &workset, &mstatus); /* try the multiply */ 3162 if (mstatus&DEC_Overflow) { /* result just won't fit */ 3163 status|=DEC_Inexact|DEC_Rounded; 3164 } 3165 else { /* plausible */ 3166 decCompareOp(t, b, rhs, &workset, COMPARE, &mstatus); /* b ? rhs */ 3167 if (!ISZERO(t)) status|=DEC_Inexact|DEC_Rounded; /* not equal */ 3168 else { /* is Exact */ 3169 /* here, dropped is the count of trailing zeros in 'a' */ 3170 /* use closest exponent to ideal... */ 3171 Int todrop=ideal-a->exponent; /* most that can be dropped */ 3172 if (todrop<0) status|=DEC_Rounded; /* ideally would add 0s */ 3173 else { /* unrounded */ 3174 if (dropped<todrop) { /* clamp to those available */ 3175 todrop=dropped; 3176 status|=DEC_Clamped; 3177 } 3178 if (todrop>0) { /* have some to drop */ 3179 decShiftToLeast(a->lsu, D2U(a->digits), todrop); 3180 a->exponent+=todrop; /* maintain numerical value */ 3181 a->digits-=todrop; /* new length */ 3182 } 3183 } 3184 } 3185 } 3186 } 3187 3188 /* double-check Underflow, as perhaps the result could not have */ 3189 /* been subnormal (initial argument too big), or it is now Exact */ 3190 if (status&DEC_Underflow) { 3191 Int ae=rhs->exponent+rhs->digits-1; /* adjusted exponent */ 3192 /* check if truly subnormal */ 3193 #if DECEXTFLAG /* DEC_Subnormal too */ 3194 if (ae>=set->emin*2) status&=~(DEC_Subnormal|DEC_Underflow); 3195 #else 3196 if (ae>=set->emin*2) status&=~DEC_Underflow; 3197 #endif 3198 /* check if truly inexact */ 3199 if (!(status&DEC_Inexact)) status&=~DEC_Underflow; 3200 } 3201 3202 decNumberCopy(res, a); /* a is now the result */ 3203 } while(0); /* end protected */ 3204 3205 if (allocbuff!=NULL) free(allocbuff); /* drop any storage used */ 3206 if (allocbufa!=NULL) free(allocbufa); /* .. */ 3207 if (allocbufb!=NULL) free(allocbufb); /* .. */ 3208 #if DECSUBSET 3209 if (allocrhs !=NULL) free(allocrhs); /* .. */ 3210 #endif 3211 if (status!=0) decStatus(res, status, set);/* then report status */ 3212 #if DECCHECK 3213 decCheckInexact(res, set); 3214 #endif 3215 return res; 3216 } /* decNumberSquareRoot */ 3217 3218 /* ------------------------------------------------------------------ */ 3219 /* decNumberSubtract -- subtract two Numbers */ 3220 /* */ 3221 /* This computes C = A - B */ 3222 /* */ 3223 /* res is C, the result. C may be A and/or B (e.g., X=X-X) */ 3224 /* lhs is A */ 3225 /* rhs is B */ 3226 /* set is the context */ 3227 /* */ 3228 /* C must have space for set->digits digits. */ 3229 /* ------------------------------------------------------------------ */ 3230 decNumber * decNumberSubtract(decNumber *res, const decNumber *lhs, 3231 const decNumber *rhs, decContext *set) { 3232 uInt status=0; /* accumulator */ 3233 3234 decAddOp(res, lhs, rhs, set, DECNEG, &status); 3235 if (status!=0) decStatus(res, status, set); 3236 #if DECCHECK 3237 decCheckInexact(res, set); 3238 #endif 3239 return res; 3240 } /* decNumberSubtract */ 3241 3242 /* ------------------------------------------------------------------ */ 3243 /* decNumberToIntegralExact -- round-to-integral-value with InExact */ 3244 /* decNumberToIntegralValue -- round-to-integral-value */ 3245 /* */ 3246 /* res is the result */ 3247 /* rhs is input number */ 3248 /* set is the context */ 3249 /* */ 3250 /* res must have space for any value of rhs. */ 3251 /* */ 3252 /* This implements the IEEE special operators and therefore treats */ 3253 /* special values as valid. For finite numbers it returns */ 3254 /* rescale(rhs, 0) if rhs->exponent is <0. */ 3255 /* Otherwise the result is rhs (so no error is possible, except for */ 3256 /* sNaN). */ 3257 /* */ 3258 /* The context is used for rounding mode and status after sNaN, but */ 3259 /* the digits setting is ignored. The Exact version will signal */ 3260 /* Inexact if the result differs numerically from rhs; the other */ 3261 /* never signals Inexact. */ 3262 /* ------------------------------------------------------------------ */ 3263 decNumber * decNumberToIntegralExact(decNumber *res, const decNumber *rhs, 3264 decContext *set) { 3265 decNumber dn; 3266 decContext workset; /* working context */ 3267 uInt status=0; /* accumulator */ 3268 3269 #if DECCHECK 3270 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; 3271 #endif 3272 3273 /* handle infinities and NaNs */ 3274 if (SPECIALARG) { 3275 if (decNumberIsInfinite(rhs)) decNumberCopy(res, rhs); /* an Infinity */ 3276 else decNaNs(res, rhs, NULL, set, &status); /* a NaN */ 3277 } 3278 else { /* finite */ 3279 /* have a finite number; no error possible (res must be big enough) */ 3280 if (rhs->exponent>=0) return decNumberCopy(res, rhs); 3281 /* that was easy, but if negative exponent there is work to do... */ 3282 workset=*set; /* clone rounding, etc. */ 3283 workset.digits=rhs->digits; /* no length rounding */ 3284 workset.traps=0; /* no traps */ 3285 decNumberZero(&dn); /* make a number with exponent 0 */ 3286 decNumberQuantize(res, rhs, &dn, &workset); 3287 status|=workset.status; 3288 } 3289 if (status!=0) decStatus(res, status, set); 3290 return res; 3291 } /* decNumberToIntegralExact */ 3292 3293 decNumber * decNumberToIntegralValue(decNumber *res, const decNumber *rhs, 3294 decContext *set) { 3295 decContext workset=*set; /* working context */ 3296 workset.traps=0; /* no traps */ 3297 decNumberToIntegralExact(res, rhs, &workset); 3298 /* this never affects set, except for sNaNs; NaN will have been set */ 3299 /* or propagated already, so no need to call decStatus */ 3300 set->status|=workset.status&DEC_Invalid_operation; 3301 return res; 3302 } /* decNumberToIntegralValue */ 3303 3304 /* ------------------------------------------------------------------ */ 3305 /* decNumberXor -- XOR two Numbers, digitwise */ 3306 /* */ 3307 /* This computes C = A ^ B */ 3308 /* */ 3309 /* res is C, the result. C may be A and/or B (e.g., X=X^X) */ 3310 /* lhs is A */ 3311 /* rhs is B */ 3312 /* set is the context (used for result length and error report) */ 3313 /* */ 3314 /* C must have space for set->digits digits. */ 3315 /* */ 3316 /* Logical function restrictions apply (see above); a NaN is */ 3317 /* returned with Invalid_operation if a restriction is violated. */ 3318 /* ------------------------------------------------------------------ */ 3319 decNumber * decNumberXor(decNumber *res, const decNumber *lhs, 3320 const decNumber *rhs, decContext *set) { 3321 const Unit *ua, *ub; /* -> operands */ 3322 const Unit *msua, *msub; /* -> operand msus */ 3323 Unit *uc, *msuc; /* -> result and its msu */ 3324 Int msudigs; /* digits in res msu */ 3325 #if DECCHECK 3326 if (decCheckOperands(res, lhs, rhs, set)) return res; 3327 #endif 3328 3329 if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs) 3330 || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) { 3331 decStatus(res, DEC_Invalid_operation, set); 3332 return res; 3333 } 3334 /* operands are valid */ 3335 ua=lhs->lsu; /* bottom-up */ 3336 ub=rhs->lsu; /* .. */ 3337 uc=res->lsu; /* .. */ 3338 msua=ua+D2U(lhs->digits)-1; /* -> msu of lhs */ 3339 msub=ub+D2U(rhs->digits)-1; /* -> msu of rhs */ 3340 msuc=uc+D2U(set->digits)-1; /* -> msu of result */ 3341 msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */ 3342 for (; uc<=msuc; ua++, ub++, uc++) { /* Unit loop */ 3343 Unit a, b; /* extract units */ 3344 if (ua>msua) a=0; 3345 else a=*ua; 3346 if (ub>msub) b=0; 3347 else b=*ub; 3348 *uc=0; /* can now write back */ 3349 if (a|b) { /* maybe 1 bits to examine */ 3350 Int i, j; 3351 /* This loop could be unrolled and/or use BIN2BCD tables */ 3352 for (i=0; i<DECDPUN; i++) { 3353 if ((a^b)&1) *uc=*uc+(Unit)powers[i]; /* effect XOR */ 3354 j=a%10; 3355 a=a/10; 3356 j|=b%10; 3357 b=b/10; 3358 if (j>1) { 3359 decStatus(res, DEC_Invalid_operation, set); 3360 return res; 3361 } 3362 if (uc==msuc && i==msudigs-1) break; /* just did final digit */ 3363 } /* each digit */ 3364 } /* non-zero */ 3365 } /* each unit */ 3366 /* [here uc-1 is the msu of the result] */ 3367 res->digits=decGetDigits(res->lsu, uc-res->lsu); 3368 res->exponent=0; /* integer */ 3369 res->bits=0; /* sign=0 */ 3370 return res; /* [no status to set] */ 3371 } /* decNumberXor */ 3372 3373 3374 /* ================================================================== */ 3375 /* Utility routines */ 3376 /* ================================================================== */ 3377 3378 /* ------------------------------------------------------------------ */ 3379 /* decNumberClass -- return the decClass of a decNumber */ 3380 /* dn -- the decNumber to test */ 3381 /* set -- the context to use for Emin */ 3382 /* returns the decClass enum */ 3383 /* ------------------------------------------------------------------ */ 3384 enum decClass decNumberClass(const decNumber *dn, decContext *set) { 3385 if (decNumberIsSpecial(dn)) { 3386 if (decNumberIsQNaN(dn)) return DEC_CLASS_QNAN; 3387 if (decNumberIsSNaN(dn)) return DEC_CLASS_SNAN; 3388 /* must be an infinity */ 3389 if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_INF; 3390 return DEC_CLASS_POS_INF; 3391 } 3392 /* is finite */ 3393 if (decNumberIsNormal(dn, set)) { /* most common */ 3394 if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_NORMAL; 3395 return DEC_CLASS_POS_NORMAL; 3396 } 3397 /* is subnormal or zero */ 3398 if (decNumberIsZero(dn)) { /* most common */ 3399 if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_ZERO; 3400 return DEC_CLASS_POS_ZERO; 3401 } 3402 if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_SUBNORMAL; 3403 return DEC_CLASS_POS_SUBNORMAL; 3404 } /* decNumberClass */ 3405 3406 /* ------------------------------------------------------------------ */ 3407 /* decNumberClassToString -- convert decClass to a string */ 3408 /* */ 3409 /* eclass is a valid decClass */ 3410 /* returns a constant string describing the class (max 13+1 chars) */ 3411 /* ------------------------------------------------------------------ */ 3412 const char *decNumberClassToString(enum decClass eclass) { 3413 if (eclass==DEC_CLASS_POS_NORMAL) return DEC_ClassString_PN; 3414 if (eclass==DEC_CLASS_NEG_NORMAL) return DEC_ClassString_NN; 3415 if (eclass==DEC_CLASS_POS_ZERO) return DEC_ClassString_PZ; 3416 if (eclass==DEC_CLASS_NEG_ZERO) return DEC_ClassString_NZ; 3417 if (eclass==DEC_CLASS_POS_SUBNORMAL) return DEC_ClassString_PS; 3418 if (eclass==DEC_CLASS_NEG_SUBNORMAL) return DEC_ClassString_NS; 3419 if (eclass==DEC_CLASS_POS_INF) return DEC_ClassString_PI; 3420 if (eclass==DEC_CLASS_NEG_INF) return DEC_ClassString_NI; 3421 if (eclass==DEC_CLASS_QNAN) return DEC_ClassString_QN; 3422 if (eclass==DEC_CLASS_SNAN) return DEC_ClassString_SN; 3423 return DEC_ClassString_UN; /* Unknown */ 3424 } /* decNumberClassToString */ 3425 3426 /* ------------------------------------------------------------------ */ 3427 /* decNumberCopy -- copy a number */ 3428 /* */ 3429 /* dest is the target decNumber */ 3430 /* src is the source decNumber */ 3431 /* returns dest */ 3432 /* */ 3433 /* (dest==src is allowed and is a no-op) */ 3434 /* All fields are updated as required. This is a utility operation, */ 3435 /* so special values are unchanged and no error is possible. */ 3436 /* ------------------------------------------------------------------ */ 3437 decNumber * decNumberCopy(decNumber *dest, const decNumber *src) { 3438 3439 #if DECCHECK 3440 if (src==NULL) return decNumberZero(dest); 3441 #endif 3442 3443 if (dest==src) return dest; /* no copy required */ 3444 3445 /* Use explicit assignments here as structure assignment could copy */ 3446 /* more than just the lsu (for small DECDPUN). This would not affect */ 3447 /* the value of the results, but could disturb test harness spill */ 3448 /* checking. */ 3449 dest->bits=src->bits; 3450 dest->exponent=src->exponent; 3451 dest->digits=src->digits; 3452 dest->lsu[0]=src->lsu[0]; 3453 if (src->digits>DECDPUN) { /* more Units to come */ 3454 const Unit *smsup, *s; /* work */ 3455 Unit *d; /* .. */ 3456 /* memcpy for the remaining Units would be safe as they cannot */ 3457 /* overlap. However, this explicit loop is faster in short cases. */ 3458 d=dest->lsu+1; /* -> first destination */ 3459 smsup=src->lsu+D2U(src->digits); /* -> source msu+1 */ 3460 for (s=src->lsu+1; s<smsup; s++, d++) *d=*s; 3461 } 3462 return dest; 3463 } /* decNumberCopy */ 3464 3465 /* ------------------------------------------------------------------ */ 3466 /* decNumberCopyAbs -- quiet absolute value operator */ 3467 /* */ 3468 /* This sets C = abs(A) */ 3469 /* */ 3470 /* res is C, the result. C may be A */ 3471 /* rhs is A */ 3472 /* */ 3473 /* C must have space for set->digits digits. */ 3474 /* No exception or error can occur; this is a quiet bitwise operation.*/ 3475 /* See also decNumberAbs for a checking version of this. */ 3476 /* ------------------------------------------------------------------ */ 3477 decNumber * decNumberCopyAbs(decNumber *res, const decNumber *rhs) { 3478 #if DECCHECK 3479 if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res; 3480 #endif 3481 decNumberCopy(res, rhs); 3482 res->bits&=~DECNEG; /* turn off sign */ 3483 return res; 3484 } /* decNumberCopyAbs */ 3485 3486 /* ------------------------------------------------------------------ */ 3487 /* decNumberCopyNegate -- quiet negate value operator */ 3488 /* */ 3489 /* This sets C = negate(A) */ 3490 /* */ 3491 /* res is C, the result. C may be A */ 3492 /* rhs is A */ 3493 /* */ 3494 /* C must have space for set->digits digits. */ 3495 /* No exception or error can occur; this is a quiet bitwise operation.*/ 3496 /* See also decNumberMinus for a checking version of this. */ 3497 /* ------------------------------------------------------------------ */ 3498 decNumber * decNumberCopyNegate(decNumber *res, const decNumber *rhs) { 3499 #if DECCHECK 3500 if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res; 3501 #endif 3502 decNumberCopy(res, rhs); 3503 res->bits^=DECNEG; /* invert the sign */ 3504 return res; 3505 } /* decNumberCopyNegate */ 3506 3507 /* ------------------------------------------------------------------ */ 3508 /* decNumberCopySign -- quiet copy and set sign operator */ 3509 /* */ 3510 /* This sets C = A with the sign of B */ 3511 /* */ 3512 /* res is C, the result. C may be A */ 3513 /* lhs is A */ 3514 /* rhs is B */ 3515 /* */ 3516 /* C must have space for set->digits digits. */ 3517 /* No exception or error can occur; this is a quiet bitwise operation.*/ 3518 /* ------------------------------------------------------------------ */ 3519 decNumber * decNumberCopySign(decNumber *res, const decNumber *lhs, 3520 const decNumber *rhs) { 3521 uByte sign; /* rhs sign */ 3522 #if DECCHECK 3523 if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res; 3524 #endif 3525 sign=rhs->bits & DECNEG; /* save sign bit */ 3526 decNumberCopy(res, lhs); 3527 res->bits&=~DECNEG; /* clear the sign */ 3528 res->bits|=sign; /* set from rhs */ 3529 return res; 3530 } /* decNumberCopySign */ 3531 3532 /* ------------------------------------------------------------------ */ 3533 /* decNumberGetBCD -- get the coefficient in BCD8 */ 3534 /* dn is the source decNumber */ 3535 /* bcd is the uInt array that will receive dn->digits BCD bytes, */ 3536 /* most-significant at offset 0 */ 3537 /* returns bcd */ 3538 /* */ 3539 /* bcd must have at least dn->digits bytes. No error is possible; if */ 3540 /* dn is a NaN or Infinite, digits must be 1 and the coefficient 0. */ 3541 /* ------------------------------------------------------------------ */ 3542 uByte * decNumberGetBCD(const decNumber *dn, uint8_t *bcd) { 3543 uByte *ub=bcd+dn->digits-1; /* -> lsd */ 3544 const Unit *up=dn->lsu; /* Unit pointer, -> lsu */ 3545 3546 #if DECDPUN==1 /* trivial simple copy */ 3547 for (; ub>=bcd; ub--, up++) *ub=*up; 3548 #else /* chopping needed */ 3549 uInt u=*up; /* work */ 3550 uInt cut=DECDPUN; /* downcounter through unit */ 3551 for (; ub>=bcd; ub--) { 3552 *ub=(uByte)(u%10); /* [*6554 trick inhibits, here] */ 3553 u=u/10; 3554 cut--; 3555 if (cut>0) continue; /* more in this unit */ 3556 up++; 3557 u=*up; 3558 cut=DECDPUN; 3559 } 3560 #endif 3561 return bcd; 3562 } /* decNumberGetBCD */ 3563 3564 /* ------------------------------------------------------------------ */ 3565 /* decNumberSetBCD -- set (replace) the coefficient from BCD8 */ 3566 /* dn is the target decNumber */ 3567 /* bcd is the uInt array that will source n BCD bytes, most- */ 3568 /* significant at offset 0 */ 3569 /* n is the number of digits in the source BCD array (bcd) */ 3570 /* returns dn */ 3571 /* */ 3572 /* dn must have space for at least n digits. No error is possible; */ 3573 /* if dn is a NaN, or Infinite, or is to become a zero, n must be 1 */ 3574 /* and bcd[0] zero. */ 3575 /* ------------------------------------------------------------------ */ 3576 decNumber * decNumberSetBCD(decNumber *dn, const uByte *bcd, uInt n) { 3577 Unit *up = dn->lsu + D2U(n) - 1; /* -> msu [target pointer] */ 3578 const uByte *ub=bcd; /* -> source msd */ 3579 3580 #if DECDPUN==1 /* trivial simple copy */ 3581 for (; ub<bcd+n; ub++, up--) *up=*ub; 3582 #else /* some assembly needed */ 3583 /* calculate how many digits in msu, and hence first cut */ 3584 Int cut=MSUDIGITS(n); /* [faster than remainder] */ 3585 for (;up>=dn->lsu; up--) { /* each Unit from msu */ 3586 *up=0; /* will take <=DECDPUN digits */ 3587 for (; cut>0; ub++, cut--) *up=X10(*up)+*ub; 3588 cut=DECDPUN; /* next Unit has all digits */ 3589 } 3590 #endif 3591 dn->digits=n; /* set digit count */ 3592 return dn; 3593 } /* decNumberSetBCD */ 3594 3595 /* ------------------------------------------------------------------ */ 3596 /* decNumberIsNormal -- test normality of a decNumber */ 3597 /* dn is the decNumber to test */ 3598 /* set is the context to use for Emin */ 3599 /* returns 1 if |dn| is finite and >=Nmin, 0 otherwise */ 3600 /* ------------------------------------------------------------------ */ 3601 Int decNumberIsNormal(const decNumber *dn, decContext *set) { 3602 Int ae; /* adjusted exponent */ 3603 #if DECCHECK 3604 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0; 3605 #endif 3606 3607 if (decNumberIsSpecial(dn)) return 0; /* not finite */ 3608 if (decNumberIsZero(dn)) return 0; /* not non-zero */ 3609 3610 ae=dn->exponent+dn->digits-1; /* adjusted exponent */ 3611 if (ae<set->emin) return 0; /* is subnormal */ 3612 return 1; 3613 } /* decNumberIsNormal */ 3614 3615 /* ------------------------------------------------------------------ */ 3616 /* decNumberIsSubnormal -- test subnormality of a decNumber */ 3617 /* dn is the decNumber to test */ 3618 /* set is the context to use for Emin */ 3619 /* returns 1 if |dn| is finite, non-zero, and <Nmin, 0 otherwise */ 3620 /* ------------------------------------------------------------------ */ 3621 Int decNumberIsSubnormal(const decNumber *dn, decContext *set) { 3622 Int ae; /* adjusted exponent */ 3623 #if DECCHECK 3624 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0; 3625 #endif 3626 3627 if (decNumberIsSpecial(dn)) return 0; /* not finite */ 3628 if (decNumberIsZero(dn)) return 0; /* not non-zero */ 3629 3630 ae=dn->exponent+dn->digits-1; /* adjusted exponent */ 3631 if (ae<set->emin) return 1; /* is subnormal */ 3632 return 0; 3633 } /* decNumberIsSubnormal */ 3634 3635 /* ------------------------------------------------------------------ */ 3636 /* decNumberTrim -- remove insignificant zeros */ 3637 /* */ 3638 /* dn is the number to trim */ 3639 /* returns dn */ 3640 /* */ 3641 /* All fields are updated as required. This is a utility operation, */ 3642 /* so special values are unchanged and no error is possible. */ 3643 /* ------------------------------------------------------------------ */ 3644 decNumber * decNumberTrim(decNumber *dn) { 3645 Int dropped; /* work */ 3646 decContext set; /* .. */ 3647 #if DECCHECK 3648 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, DECUNCONT)) return dn; 3649 #endif 3650 decContextDefault(&set, DEC_INIT_BASE); /* clamp=0 */ 3651 return decTrim(dn, &set, 0, &dropped); 3652 } /* decNumberTrim */ 3653 3654 /* ------------------------------------------------------------------ */ 3655 /* decNumberVersion -- return the name and version of this module */ 3656 /* */ 3657 /* No error is possible. */ 3658 /* ------------------------------------------------------------------ */ 3659 const char * decNumberVersion(void) { 3660 return DECVERSION; 3661 } /* decNumberVersion */ 3662 3663 /* ------------------------------------------------------------------ */ 3664 /* decNumberZero -- set a number to 0 */ 3665 /* */ 3666 /* dn is the number to set, with space for one digit */ 3667 /* returns dn */ 3668 /* */ 3669 /* No error is possible. */ 3670 /* ------------------------------------------------------------------ */ 3671 /* Memset is not used as it is much slower in some environments. */ 3672 decNumber * decNumberZero(decNumber *dn) { 3673 3674 #if DECCHECK 3675 if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn; 3676 #endif 3677 3678 dn->bits=0; 3679 dn->exponent=0; 3680 dn->digits=1; 3681 dn->lsu[0]=0; 3682 return dn; 3683 } /* decNumberZero */ 3684 3685 /* ================================================================== */ 3686 /* Local routines */ 3687 /* ================================================================== */ 3688 3689 /* ------------------------------------------------------------------ */ 3690 /* decToString -- lay out a number into a string */ 3691 /* */ 3692 /* dn is the number to lay out */ 3693 /* string is where to lay out the number */ 3694 /* eng is 1 if Engineering, 0 if Scientific */ 3695 /* */ 3696 /* string must be at least dn->digits+14 characters long */ 3697 /* No error is possible. */ 3698 /* */ 3699 /* Note that this routine can generate a -0 or 0.000. These are */ 3700 /* never generated in subset to-number or arithmetic, but can occur */ 3701 /* in non-subset arithmetic (e.g., -1*0 or 1.234-1.234). */ 3702 /* ------------------------------------------------------------------ */ 3703 /* If DECCHECK is enabled the string "?" is returned if a number is */ 3704 /* invalid. */ 3705 static void decToString(const decNumber *dn, char *string, Flag eng) { 3706 Int exp=dn->exponent; /* local copy */ 3707 Int e; /* E-part value */ 3708 Int pre; /* digits before the '.' */ 3709 Int cut; /* for counting digits in a Unit */ 3710 char *c=string; /* work [output pointer] */ 3711 const Unit *up=dn->lsu+D2U(dn->digits)-1; /* -> msu [input pointer] */ 3712 uInt u, pow; /* work */ 3713 3714 #if DECCHECK 3715 if (decCheckOperands(DECUNRESU, dn, DECUNUSED, DECUNCONT)) { 3716 strcpy(string, "?"); 3717 return;} 3718 #endif 3719 3720 if (decNumberIsNegative(dn)) { /* Negatives get a minus */ 3721 *c='-'; 3722 c++; 3723 } 3724 if (dn->bits&DECSPECIAL) { /* Is a special value */ 3725 if (decNumberIsInfinite(dn)) { 3726 strcpy(c, "Inf"); 3727 strcpy(c+3, "inity"); 3728 return;} 3729 /* a NaN */ 3730 if (dn->bits&DECSNAN) { /* signalling NaN */ 3731 *c='s'; 3732 c++; 3733 } 3734 strcpy(c, "NaN"); 3735 c+=3; /* step past */ 3736 /* if not a clean non-zero coefficient, that's all there is in a */ 3737 /* NaN string */ 3738 if (exp!=0 || (*dn->lsu==0 && dn->digits==1)) return; 3739 /* [drop through to add integer] */ 3740 } 3741 3742 /* calculate how many digits in msu, and hence first cut */ 3743 cut=MSUDIGITS(dn->digits); /* [faster than remainder] */ 3744 cut--; /* power of ten for digit */ 3745 3746 if (exp==0) { /* simple integer [common fastpath] */ 3747 for (;up>=dn->lsu; up--) { /* each Unit from msu */ 3748 u=*up; /* contains DECDPUN digits to lay out */ 3749 for (; cut>=0; c++, cut--) TODIGIT(u, cut, c, pow); 3750 cut=DECDPUN-1; /* next Unit has all digits */ 3751 } 3752 *c='\0'; /* terminate the string */ 3753 return;} 3754 3755 /* non-0 exponent -- assume plain form */ 3756 pre=dn->digits+exp; /* digits before '.' */ 3757 e=0; /* no E */ 3758 if ((exp>0) || (pre<-5)) { /* need exponential form */ 3759 e=exp+dn->digits-1; /* calculate E value */ 3760 pre=1; /* assume one digit before '.' */ 3761 if (eng && (e!=0)) { /* engineering: may need to adjust */ 3762 Int adj; /* adjustment */ 3763 /* The C remainder operator is undefined for negative numbers, so */ 3764 /* a positive remainder calculation must be used here */ 3765 if (e<0) { 3766 adj=(-e)%3; 3767 if (adj!=0) adj=3-adj; 3768 } 3769 else { /* e>0 */ 3770 adj=e%3; 3771 } 3772 e=e-adj; 3773 /* if dealing with zero still produce an exponent which is a */ 3774 /* multiple of three, as expected, but there will only be the */ 3775 /* one zero before the E, still. Otherwise note the padding. */ 3776 if (!ISZERO(dn)) pre+=adj; 3777 else { /* is zero */ 3778 if (adj!=0) { /* 0.00Esnn needed */ 3779 e=e+3; 3780 pre=-(2-adj); 3781 } 3782 } /* zero */ 3783 } /* eng */ 3784 } /* need exponent */ 3785 3786 /* lay out the digits of the coefficient, adding 0s and . as needed */ 3787 u=*up; 3788 if (pre>0) { /* xxx.xxx or xx00 (engineering) form */ 3789 Int n=pre; 3790 for (; pre>0; pre--, c++, cut--) { 3791 if (cut<0) { /* need new Unit */ 3792 if (up==dn->lsu) break; /* out of input digits (pre>digits) */ 3793 up--; 3794 cut=DECDPUN-1; 3795 u=*up; 3796 } 3797 TODIGIT(u, cut, c, pow); 3798 } 3799 if (n<dn->digits) { /* more to come, after '.' */ 3800 *c='.'; c++; 3801 for (;; c++, cut--) { 3802 if (cut<0) { /* need new Unit */ 3803 if (up==dn->lsu) break; /* out of input digits */ 3804 up--; 3805 cut=DECDPUN-1; 3806 u=*up; 3807 } 3808 TODIGIT(u, cut, c, pow); 3809 } 3810 } 3811 else for (; pre>0; pre--, c++) *c='0'; /* 0 padding (for engineering) needed */ 3812 } 3813 else { /* 0.xxx or 0.000xxx form */ 3814 *c='0'; c++; 3815 *c='.'; c++; 3816 for (; pre<0; pre++, c++) *c='0'; /* add any 0's after '.' */ 3817 for (; ; c++, cut--) { 3818 if (cut<0) { /* need new Unit */ 3819 if (up==dn->lsu) break; /* out of input digits */ 3820 up--; 3821 cut=DECDPUN-1; 3822 u=*up; 3823 } 3824 TODIGIT(u, cut, c, pow); 3825 } 3826 } 3827 3828 /* Finally add the E-part, if needed. It will never be 0, has a 3829 base maximum and minimum of +999999999 through -999999999, but 3830 could range down to -1999999998 for anormal numbers */ 3831 if (e!=0) { 3832 Flag had=0; /* 1=had non-zero */ 3833 *c='E'; c++; 3834 *c='+'; c++; /* assume positive */ 3835 u=e; /* .. */ 3836 if (e<0) { 3837 *(c-1)='-'; /* oops, need - */ 3838 u=-e; /* uInt, please */ 3839 } 3840 /* lay out the exponent [_itoa or equivalent is not ANSI C] */ 3841 for (cut=9; cut>=0; cut--) { 3842 TODIGIT(u, cut, c, pow); 3843 if (*c=='0' && !had) continue; /* skip leading zeros */ 3844 had=1; /* had non-0 */ 3845 c++; /* step for next */ 3846 } /* cut */ 3847 } 3848 *c='\0'; /* terminate the string (all paths) */ 3849 return; 3850 } /* decToString */ 3851 3852 /* ------------------------------------------------------------------ */ 3853 /* decAddOp -- add/subtract operation */ 3854 /* */ 3855 /* This computes C = A + B */ 3856 /* */ 3857 /* res is C, the result. C may be A and/or B (e.g., X=X+X) */ 3858 /* lhs is A */ 3859 /* rhs is B */ 3860 /* set is the context */ 3861 /* negate is DECNEG if rhs should be negated, or 0 otherwise */ 3862 /* status accumulates status for the caller */ 3863 /* */ 3864 /* C must have space for set->digits digits. */ 3865 /* Inexact in status must be 0 for correct Exact zero sign in result */ 3866 /* ------------------------------------------------------------------ */ 3867 /* If possible, the coefficient is calculated directly into C. */ 3868 /* However, if: */ 3869 /* -- a digits+1 calculation is needed because the numbers are */ 3870 /* unaligned and span more than set->digits digits */ 3871 /* -- a carry to digits+1 digits looks possible */ 3872 /* -- C is the same as A or B, and the result would destructively */ 3873 /* overlap the A or B coefficient */ 3874 /* then the result must be calculated into a temporary buffer. In */ 3875 /* this case a local (stack) buffer is used if possible, and only if */ 3876 /* too long for that does malloc become the final resort. */ 3877 /* */ 3878 /* Misalignment is handled as follows: */ 3879 /* Apad: (AExp>BExp) Swap operands and proceed as for BExp>AExp. */ 3880 /* BPad: Apply the padding by a combination of shifting (whole */ 3881 /* units) and multiplication (part units). */ 3882 /* */ 3883 /* Addition, especially x=x+1, is speed-critical. */ 3884 /* The static buffer is larger than might be expected to allow for */ 3885 /* calls from higher-level functions (notably exp). */ 3886 /* ------------------------------------------------------------------ */ 3887 static decNumber * decAddOp(decNumber *res, const decNumber *lhs, 3888 const decNumber *rhs, decContext *set, 3889 uByte negate, uInt *status) { 3890 #if DECSUBSET 3891 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */ 3892 decNumber *allocrhs=NULL; /* .., rhs */ 3893 #endif 3894 Int rhsshift; /* working shift (in Units) */ 3895 Int maxdigits; /* longest logical length */ 3896 Int mult; /* multiplier */ 3897 Int residue; /* rounding accumulator */ 3898 uByte bits; /* result bits */ 3899 Flag diffsign; /* non-0 if arguments have different sign */ 3900 Unit *acc; /* accumulator for result */ 3901 Unit accbuff[SD2U(DECBUFFER*2+20)]; /* local buffer [*2+20 reduces many */ 3902 /* allocations when called from */ 3903 /* other operations, notable exp] */ 3904 Unit *allocacc=NULL; /* -> allocated acc buffer, iff allocated */ 3905 Int reqdigits=set->digits; /* local copy; requested DIGITS */ 3906 Int padding; /* work */ 3907 3908 #if DECCHECK 3909 if (decCheckOperands(res, lhs, rhs, set)) return res; 3910 #endif 3911 3912 do { /* protect allocated storage */ 3913 #if DECSUBSET 3914 if (!set->extended) { 3915 /* reduce operands and set lostDigits status, as needed */ 3916 if (lhs->digits>reqdigits) { 3917 alloclhs=decRoundOperand(lhs, set, status); 3918 if (alloclhs==NULL) break; 3919 lhs=alloclhs; 3920 } 3921 if (rhs->digits>reqdigits) { 3922 allocrhs=decRoundOperand(rhs, set, status); 3923 if (allocrhs==NULL) break; 3924 rhs=allocrhs; 3925 } 3926 } 3927 #endif 3928 /* [following code does not require input rounding] */ 3929 3930 /* note whether signs differ [used all paths] */ 3931 diffsign=(Flag)((lhs->bits^rhs->bits^negate)&DECNEG); 3932 3933 /* handle infinities and NaNs */ 3934 if (SPECIALARGS) { /* a special bit set */ 3935 if (SPECIALARGS & (DECSNAN | DECNAN)) /* a NaN */ 3936 decNaNs(res, lhs, rhs, set, status); 3937 else { /* one or two infinities */ 3938 if (decNumberIsInfinite(lhs)) { /* LHS is infinity */ 3939 /* two infinities with different signs is invalid */ 3940 if (decNumberIsInfinite(rhs) && diffsign) { 3941 *status|=DEC_Invalid_operation; 3942 break; 3943 } 3944 bits=lhs->bits & DECNEG; /* get sign from LHS */ 3945 } 3946 else bits=(rhs->bits^negate) & DECNEG;/* RHS must be Infinity */ 3947 bits|=DECINF; 3948 decNumberZero(res); 3949 res->bits=bits; /* set +/- infinity */ 3950 } /* an infinity */ 3951 break; 3952 } 3953 3954 /* Quick exit for add 0s; return the non-0, modified as need be */ 3955 if (ISZERO(lhs)) { 3956 Int adjust; /* work */ 3957 Int lexp=lhs->exponent; /* save in case LHS==RES */ 3958 bits=lhs->bits; /* .. */ 3959 residue=0; /* clear accumulator */ 3960 decCopyFit(res, rhs, set, &residue, status); /* copy (as needed) */ 3961 res->bits^=negate; /* flip if rhs was negated */ 3962 #if DECSUBSET 3963 if (set->extended) { /* exponents on zeros count */ 3964 #endif 3965 /* exponent will be the lower of the two */ 3966 adjust=lexp-res->exponent; /* adjustment needed [if -ve] */ 3967 if (ISZERO(res)) { /* both 0: special IEEE 854 rules */ 3968 if (adjust<0) res->exponent=lexp; /* set exponent */ 3969 /* 0-0 gives +0 unless rounding to -infinity, and -0-0 gives -0 */ 3970 if (diffsign) { 3971 if (set->round!=DEC_ROUND_FLOOR) res->bits=0; 3972 else res->bits=DECNEG; /* preserve 0 sign */ 3973 } 3974 } 3975 else { /* non-0 res */ 3976 if (adjust<0) { /* 0-padding needed */ 3977 if ((res->digits-adjust)>set->digits) { 3978 adjust=res->digits-set->digits; /* to fit exactly */ 3979 *status|=DEC_Rounded; /* [but exact] */ 3980 } 3981 res->digits=decShiftToMost(res->lsu, res->digits, -adjust); 3982 res->exponent+=adjust; /* set the exponent. */ 3983 } 3984 } /* non-0 res */ 3985 #if DECSUBSET 3986 } /* extended */ 3987 #endif 3988 decFinish(res, set, &residue, status); /* clean and finalize */ 3989 break;} 3990 3991 if (ISZERO(rhs)) { /* [lhs is non-zero] */ 3992 Int adjust; /* work */ 3993 Int rexp=rhs->exponent; /* save in case RHS==RES */ 3994 bits=rhs->bits; /* be clean */ 3995 residue=0; /* clear accumulator */ 3996 decCopyFit(res, lhs, set, &residue, status); /* copy (as needed) */ 3997 #if DECSUBSET 3998 if (set->extended) { /* exponents on zeros count */ 3999 #endif 4000 /* exponent will be the lower of the two */ 4001 /* [0-0 case handled above] */ 4002 adjust=rexp-res->exponent; /* adjustment needed [if -ve] */ 4003 if (adjust<0) { /* 0-padding needed */ 4004 if ((res->digits-adjust)>set->digits) { 4005 adjust=res->digits-set->digits; /* to fit exactly */ 4006 *status|=DEC_Rounded; /* [but exact] */ 4007 } 4008 res->digits=decShiftToMost(res->lsu, res->digits, -adjust); 4009 res->exponent+=adjust; /* set the exponent. */ 4010 } 4011 #if DECSUBSET 4012 } /* extended */ 4013 #endif 4014 decFinish(res, set, &residue, status); /* clean and finalize */ 4015 break;} 4016 4017 /* [NB: both fastpath and mainpath code below assume these cases */ 4018 /* (notably 0-0) have already been handled] */ 4019 4020 /* calculate the padding needed to align the operands */ 4021 padding=rhs->exponent-lhs->exponent; 4022 4023 /* Fastpath cases where the numbers are aligned and normal, the RHS */ 4024 /* is all in one unit, no operand rounding is needed, and no carry, */ 4025 /* lengthening, or borrow is needed */ 4026 if (padding==0 4027 && rhs->digits<=DECDPUN 4028 && rhs->exponent>=set->emin /* [some normals drop through] */ 4029 && rhs->exponent<=set->emax-set->digits+1 /* [could clamp] */ 4030 && rhs->digits<=reqdigits 4031 && lhs->digits<=reqdigits) { 4032 Int partial=*lhs->lsu; 4033 if (!diffsign) { /* adding */ 4034 partial+=*rhs->lsu; 4035 if ((partial<=DECDPUNMAX) /* result fits in unit */ 4036 && (lhs->digits>=DECDPUN || /* .. and no digits-count change */ 4037 partial<(Int)powers[lhs->digits])) { /* .. */ 4038 if (res!=lhs) decNumberCopy(res, lhs); /* not in place */ 4039 *res->lsu=(Unit)partial; /* [copy could have overwritten RHS] */ 4040 break; 4041 } 4042 /* else drop out for careful add */ 4043 } 4044 else { /* signs differ */ 4045 partial-=*rhs->lsu; 4046 if (partial>0) { /* no borrow needed, and non-0 result */ 4047 if (res!=lhs) decNumberCopy(res, lhs); /* not in place */ 4048 *res->lsu=(Unit)partial; 4049 /* this could have reduced digits [but result>0] */ 4050 res->digits=decGetDigits(res->lsu, D2U(res->digits)); 4051 break; 4052 } 4053 /* else drop out for careful subtract */ 4054 } 4055 } 4056 4057 /* Now align (pad) the lhs or rhs so they can be added or */ 4058 /* subtracted, as necessary. If one number is much larger than */ 4059 /* the other (that is, if in plain form there is a least one */ 4060 /* digit between the lowest digit of one and the highest of the */ 4061 /* other) padding with up to DIGITS-1 trailing zeros may be */ 4062 /* needed; then apply rounding (as exotic rounding modes may be */ 4063 /* affected by the residue). */ 4064 rhsshift=0; /* rhs shift to left (padding) in Units */ 4065 bits=lhs->bits; /* assume sign is that of LHS */ 4066 mult=1; /* likely multiplier */ 4067 4068 /* [if padding==0 the operands are aligned; no padding is needed] */ 4069 if (padding!=0) { 4070 /* some padding needed; always pad the RHS, as any required */ 4071 /* padding can then be effected by a simple combination of */ 4072 /* shifts and a multiply */ 4073 Flag swapped=0; 4074 if (padding<0) { /* LHS needs the padding */ 4075 const decNumber *t; 4076 padding=-padding; /* will be +ve */ 4077 bits=(uByte)(rhs->bits^negate); /* assumed sign is now that of RHS */ 4078 t=lhs; lhs=rhs; rhs=t; 4079 swapped=1; 4080 } 4081 4082 /* If, after pad, rhs would be longer than lhs by digits+1 or */ 4083 /* more then lhs cannot affect the answer, except as a residue, */ 4084 /* so only need to pad up to a length of DIGITS+1. */ 4085 if (rhs->digits+padding > lhs->digits+reqdigits+1) { 4086 /* The RHS is sufficient */ 4087 /* for residue use the relative sign indication... */ 4088 Int shift=reqdigits-rhs->digits; /* left shift needed */ 4089 residue=1; /* residue for rounding */ 4090 if (diffsign) residue=-residue; /* signs differ */ 4091 /* copy, shortening if necessary */ 4092 decCopyFit(res, rhs, set, &residue, status); 4093 /* if it was already shorter, then need to pad with zeros */ 4094 if (shift>0) { 4095 res->digits=decShiftToMost(res->lsu, res->digits, shift); 4096 res->exponent-=shift; /* adjust the exponent. */ 4097 } 4098 /* flip the result sign if unswapped and rhs was negated */ 4099 if (!swapped) res->bits^=negate; 4100 decFinish(res, set, &residue, status); /* done */ 4101 break;} 4102 4103 /* LHS digits may affect result */ 4104 rhsshift=D2U(padding+1)-1; /* this much by Unit shift .. */ 4105 mult=powers[padding-(rhsshift*DECDPUN)]; /* .. this by multiplication */ 4106 } /* padding needed */ 4107 4108 if (diffsign) mult=-mult; /* signs differ */ 4109 4110 /* determine the longer operand */ 4111 maxdigits=rhs->digits+padding; /* virtual length of RHS */ 4112 if (lhs->digits>maxdigits) maxdigits=lhs->digits; 4113 4114 /* Decide on the result buffer to use; if possible place directly */ 4115 /* into result. */ 4116 acc=res->lsu; /* assume add direct to result */ 4117 /* If destructive overlap, or the number is too long, or a carry or */ 4118 /* borrow to DIGITS+1 might be possible, a buffer must be used. */ 4119 /* [Might be worth more sophisticated tests when maxdigits==reqdigits] */ 4120 if ((maxdigits>=reqdigits) /* is, or could be, too large */ 4121 || (res==rhs && rhsshift>0)) { /* destructive overlap */ 4122 /* buffer needed, choose it; units for maxdigits digits will be */ 4123 /* needed, +1 Unit for carry or borrow */ 4124 Int need=D2U(maxdigits)+1; 4125 acc=accbuff; /* assume use local buffer */ 4126 if (need*sizeof(Unit)>sizeof(accbuff)) { 4127 /* printf("malloc add %ld %ld\n", need, sizeof(accbuff)); */ 4128 allocacc=(Unit *)malloc(need*sizeof(Unit)); 4129 if (allocacc==NULL) { /* hopeless -- abandon */ 4130 *status|=DEC_Insufficient_storage; 4131 break;} 4132 acc=allocacc; 4133 } 4134 } 4135 4136 res->bits=(uByte)(bits&DECNEG); /* it's now safe to overwrite.. */ 4137 res->exponent=lhs->exponent; /* .. operands (even if aliased) */ 4138 4139 #if DECTRACE 4140 decDumpAr('A', lhs->lsu, D2U(lhs->digits)); 4141 decDumpAr('B', rhs->lsu, D2U(rhs->digits)); 4142 printf(" :h: %ld %ld\n", rhsshift, mult); 4143 #endif 4144 4145 /* add [A+B*m] or subtract [A+B*(-m)] */ 4146 res->digits=decUnitAddSub(lhs->lsu, D2U(lhs->digits), 4147 rhs->lsu, D2U(rhs->digits), 4148 rhsshift, acc, mult) 4149 *DECDPUN; /* [units -> digits] */ 4150 if (res->digits<0) { /* borrowed... */ 4151 res->digits=-res->digits; 4152 res->bits^=DECNEG; /* flip the sign */ 4153 } 4154 #if DECTRACE 4155 decDumpAr('+', acc, D2U(res->digits)); 4156 #endif 4157 4158 /* If a buffer was used the result must be copied back, possibly */ 4159 /* shortening. (If no buffer was used then the result must have */ 4160 /* fit, so can't need rounding and residue must be 0.) */ 4161 residue=0; /* clear accumulator */ 4162 if (acc!=res->lsu) { 4163 #if DECSUBSET 4164 if (set->extended) { /* round from first significant digit */ 4165 #endif 4166 /* remove leading zeros that were added due to rounding up to */ 4167 /* integral Units -- before the test for rounding. */ 4168 if (res->digits>reqdigits) 4169 res->digits=decGetDigits(acc, D2U(res->digits)); 4170 decSetCoeff(res, set, acc, res->digits, &residue, status); 4171 #if DECSUBSET 4172 } 4173 else { /* subset arithmetic rounds from original significant digit */ 4174 /* May have an underestimate. This only occurs when both */ 4175 /* numbers fit in DECDPUN digits and are padding with a */ 4176 /* negative multiple (-10, -100...) and the top digit(s) become */ 4177 /* 0. (This only matters when using X3.274 rules where the */ 4178 /* leading zero could be included in the rounding.) */ 4179 if (res->digits<maxdigits) { 4180 *(acc+D2U(res->digits))=0; /* ensure leading 0 is there */ 4181 res->digits=maxdigits; 4182 } 4183 else { 4184 /* remove leading zeros that added due to rounding up to */ 4185 /* integral Units (but only those in excess of the original */ 4186 /* maxdigits length, unless extended) before test for rounding. */ 4187 if (res->digits>reqdigits) { 4188 res->digits=decGetDigits(acc, D2U(res->digits)); 4189 if (res->digits<maxdigits) res->digits=maxdigits; 4190 } 4191 } 4192 decSetCoeff(res, set, acc, res->digits, &residue, status); 4193 /* Now apply rounding if needed before removing leading zeros. */ 4194 /* This is safe because subnormals are not a possibility */ 4195 if (residue!=0) { 4196 decApplyRound(res, set, residue, status); 4197 residue=0; /* did what needed to be done */ 4198 } 4199 } /* subset */ 4200 #endif 4201 } /* used buffer */ 4202 4203 /* strip leading zeros [these were left on in case of subset subtract] */ 4204 res->digits=decGetDigits(res->lsu, D2U(res->digits)); 4205 4206 /* apply checks and rounding */ 4207 decFinish(res, set, &residue, status); 4208 4209 /* "When the sum of two operands with opposite signs is exactly */ 4210 /* zero, the sign of that sum shall be '+' in all rounding modes */ 4211 /* except round toward -Infinity, in which mode that sign shall be */ 4212 /* '-'." [Subset zeros also never have '-', set by decFinish.] */ 4213 if (ISZERO(res) && diffsign 4214 #if DECSUBSET 4215 && set->extended 4216 #endif 4217 && (*status&DEC_Inexact)==0) { 4218 if (set->round==DEC_ROUND_FLOOR) res->bits|=DECNEG; /* sign - */ 4219 else res->bits&=~DECNEG; /* sign + */ 4220 } 4221 } while(0); /* end protected */ 4222 4223 if (allocacc!=NULL) free(allocacc); /* drop any storage used */ 4224 #if DECSUBSET 4225 if (allocrhs!=NULL) free(allocrhs); /* .. */ 4226 if (alloclhs!=NULL) free(alloclhs); /* .. */ 4227 #endif 4228 return res; 4229 } /* decAddOp */ 4230 4231 /* ------------------------------------------------------------------ */ 4232 /* decDivideOp -- division operation */ 4233 /* */ 4234 /* This routine performs the calculations for all four division */ 4235 /* operators (divide, divideInteger, remainder, remainderNear). */ 4236 /* */ 4237 /* C=A op B */ 4238 /* */ 4239 /* res is C, the result. C may be A and/or B (e.g., X=X/X) */ 4240 /* lhs is A */ 4241 /* rhs is B */ 4242 /* set is the context */ 4243 /* op is DIVIDE, DIVIDEINT, REMAINDER, or REMNEAR respectively. */ 4244 /* status is the usual accumulator */ 4245 /* */ 4246 /* C must have space for set->digits digits. */ 4247 /* */ 4248 /* ------------------------------------------------------------------ */ 4249 /* The underlying algorithm of this routine is the same as in the */ 4250 /* 1981 S/370 implementation, that is, non-restoring long division */ 4251 /* with bi-unit (rather than bi-digit) estimation for each unit */ 4252 /* multiplier. In this pseudocode overview, complications for the */ 4253 /* Remainder operators and division residues for exact rounding are */ 4254 /* omitted for clarity. */ 4255 /* */ 4256 /* Prepare operands and handle special values */ 4257 /* Test for x/0 and then 0/x */ 4258 /* Exp =Exp1 - Exp2 */ 4259 /* Exp =Exp +len(var1) -len(var2) */ 4260 /* Sign=Sign1 * Sign2 */ 4261 /* Pad accumulator (Var1) to double-length with 0's (pad1) */ 4262 /* Pad Var2 to same length as Var1 */ 4263 /* msu2pair/plus=1st 2 or 1 units of var2, +1 to allow for round */ 4264 /* have=0 */ 4265 /* Do until (have=digits+1 OR residue=0) */ 4266 /* if exp<0 then if integer divide/residue then leave */ 4267 /* this_unit=0 */ 4268 /* Do forever */ 4269 /* compare numbers */ 4270 /* if <0 then leave inner_loop */ 4271 /* if =0 then (* quick exit without subtract *) do */ 4272 /* this_unit=this_unit+1; output this_unit */ 4273 /* leave outer_loop; end */ 4274 /* Compare lengths of numbers (mantissae): */ 4275 /* If same then tops2=msu2pair -- {units 1&2 of var2} */ 4276 /* else tops2=msu2plus -- {0, unit 1 of var2} */ 4277 /* tops1=first_unit_of_Var1*10**DECDPUN +second_unit_of_var1 */ 4278 /* mult=tops1/tops2 -- Good and safe guess at divisor */ 4279 /* if mult=0 then mult=1 */ 4280 /* this_unit=this_unit+mult */ 4281 /* subtract */ 4282 /* end inner_loop */ 4283 /* if have\=0 | this_unit\=0 then do */ 4284 /* output this_unit */ 4285 /* have=have+1; end */ 4286 /* var2=var2/10 */ 4287 /* exp=exp-1 */ 4288 /* end outer_loop */ 4289 /* exp=exp+1 -- set the proper exponent */ 4290 /* if have=0 then generate answer=0 */ 4291 /* Return (Result is defined by Var1) */ 4292 /* */ 4293 /* ------------------------------------------------------------------ */ 4294 /* Two working buffers are needed during the division; one (digits+ */ 4295 /* 1) to accumulate the result, and the other (up to 2*digits+1) for */ 4296 /* long subtractions. These are acc and var1 respectively. */ 4297 /* var1 is a copy of the lhs coefficient, var2 is the rhs coefficient.*/ 4298 /* The static buffers may be larger than might be expected to allow */ 4299 /* for calls from higher-level functions (notably exp). */ 4300 /* ------------------------------------------------------------------ */ 4301 static decNumber * decDivideOp(decNumber *res, 4302 const decNumber *lhs, const decNumber *rhs, 4303 decContext *set, Flag op, uInt *status) { 4304 #if DECSUBSET 4305 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */ 4306 decNumber *allocrhs=NULL; /* .., rhs */ 4307 #endif 4308 Unit accbuff[SD2U(DECBUFFER+DECDPUN+10)]; /* local buffer */ 4309 Unit *acc=accbuff; /* -> accumulator array for result */ 4310 Unit *allocacc=NULL; /* -> allocated buffer, iff allocated */ 4311 Unit *accnext; /* -> where next digit will go */ 4312 Int acclength; /* length of acc needed [Units] */ 4313 Int accunits; /* count of units accumulated */ 4314 Int accdigits; /* count of digits accumulated */ 4315 4316 Unit varbuff[SD2U(DECBUFFER*2+DECDPUN)*sizeof(Unit)]; /* buffer for var1 */ 4317 Unit *var1=varbuff; /* -> var1 array for long subtraction */ 4318 Unit *varalloc=NULL; /* -> allocated buffer, iff used */ 4319 Unit *msu1; /* -> msu of var1 */ 4320 4321 const Unit *var2; /* -> var2 array */ 4322 const Unit *msu2; /* -> msu of var2 */ 4323 Int msu2plus; /* msu2 plus one [does not vary] */ 4324 eInt msu2pair; /* msu2 pair plus one [does not vary] */ 4325 4326 Int var1units, var2units; /* actual lengths */ 4327 Int var2ulen; /* logical length (units) */ 4328 Int var1initpad=0; /* var1 initial padding (digits) */ 4329 Int maxdigits; /* longest LHS or required acc length */ 4330 Int mult; /* multiplier for subtraction */ 4331 Unit thisunit; /* current unit being accumulated */ 4332 Int residue; /* for rounding */ 4333 Int reqdigits=set->digits; /* requested DIGITS */ 4334 Int exponent; /* working exponent */ 4335 Int maxexponent=0; /* DIVIDE maximum exponent if unrounded */ 4336 uByte bits; /* working sign */ 4337 Unit *target; /* work */ 4338 const Unit *source; /* .. */ 4339 uLong const *pow; /* .. */ 4340 Int shift, cut; /* .. */ 4341 #if DECSUBSET 4342 Int dropped; /* work */ 4343 #endif 4344 4345 #if DECCHECK 4346 if (decCheckOperands(res, lhs, rhs, set)) return res; 4347 #endif 4348 4349 do { /* protect allocated storage */ 4350 #if DECSUBSET 4351 if (!set->extended) { 4352 /* reduce operands and set lostDigits status, as needed */ 4353 if (lhs->digits>reqdigits) { 4354 alloclhs=decRoundOperand(lhs, set, status); 4355 if (alloclhs==NULL) break; 4356 lhs=alloclhs; 4357 } 4358 if (rhs->digits>reqdigits) { 4359 allocrhs=decRoundOperand(rhs, set, status); 4360 if (allocrhs==NULL) break; 4361 rhs=allocrhs; 4362 } 4363 } 4364 #endif 4365 /* [following code does not require input rounding] */ 4366 4367 bits=(lhs->bits^rhs->bits)&DECNEG; /* assumed sign for divisions */ 4368 4369 /* handle infinities and NaNs */ 4370 if (SPECIALARGS) { /* a special bit set */ 4371 if (SPECIALARGS & (DECSNAN | DECNAN)) { /* one or two NaNs */ 4372 decNaNs(res, lhs, rhs, set, status); 4373 break; 4374 } 4375 /* one or two infinities */ 4376 if (decNumberIsInfinite(lhs)) { /* LHS (dividend) is infinite */ 4377 if (decNumberIsInfinite(rhs) || /* two infinities are invalid .. */ 4378 op & (REMAINDER | REMNEAR)) { /* as is remainder of infinity */ 4379 *status|=DEC_Invalid_operation; 4380 break; 4381 } 4382 /* [Note that infinity/0 raises no exceptions] */ 4383 decNumberZero(res); 4384 res->bits=bits|DECINF; /* set +/- infinity */ 4385 break; 4386 } 4387 else { /* RHS (divisor) is infinite */ 4388 residue=0; 4389 if (op&(REMAINDER|REMNEAR)) { 4390 /* result is [finished clone of] lhs */ 4391 decCopyFit(res, lhs, set, &residue, status); 4392 } 4393 else { /* a division */ 4394 decNumberZero(res); 4395 res->bits=bits; /* set +/- zero */ 4396 /* for DIVIDEINT the exponent is always 0. For DIVIDE, result */ 4397 /* is a 0 with infinitely negative exponent, clamped to minimum */ 4398 if (op&DIVIDE) { 4399 res->exponent=set->emin-set->digits+1; 4400 *status|=DEC_Clamped; 4401 } 4402 } 4403 decFinish(res, set, &residue, status); 4404 break; 4405 } 4406 } 4407 4408 /* handle 0 rhs (x/0) */ 4409 if (ISZERO(rhs)) { /* x/0 is always exceptional */ 4410 if (ISZERO(lhs)) { 4411 decNumberZero(res); /* [after lhs test] */ 4412 *status|=DEC_Division_undefined;/* 0/0 will become NaN */ 4413 } 4414 else { 4415 decNumberZero(res); 4416 if (op&(REMAINDER|REMNEAR)) *status|=DEC_Invalid_operation; 4417 else { 4418 *status|=DEC_Division_by_zero; /* x/0 */ 4419 res->bits=bits|DECINF; /* .. is +/- Infinity */ 4420 } 4421 } 4422 break;} 4423 4424 /* handle 0 lhs (0/x) */ 4425 if (ISZERO(lhs)) { /* 0/x [x!=0] */ 4426 #if DECSUBSET 4427 if (!set->extended) decNumberZero(res); 4428 else { 4429 #endif 4430 if (op&DIVIDE) { 4431 residue=0; 4432 exponent=lhs->exponent-rhs->exponent; /* ideal exponent */ 4433 decNumberCopy(res, lhs); /* [zeros always fit] */ 4434 res->bits=bits; /* sign as computed */ 4435 res->exponent=exponent; /* exponent, too */ 4436 decFinalize(res, set, &residue, status); /* check exponent */ 4437 } 4438 else if (op&DIVIDEINT) { 4439 decNumberZero(res); /* integer 0 */ 4440 res->bits=bits; /* sign as computed */ 4441 } 4442 else { /* a remainder */ 4443 exponent=rhs->exponent; /* [save in case overwrite] */ 4444 decNumberCopy(res, lhs); /* [zeros always fit] */ 4445 if (exponent<res->exponent) res->exponent=exponent; /* use lower */ 4446 } 4447 #if DECSUBSET 4448 } 4449 #endif 4450 break;} 4451 4452 /* Precalculate exponent. This starts off adjusted (and hence fits */ 4453 /* in 31 bits) and becomes the usual unadjusted exponent as the */ 4454 /* division proceeds. The order of evaluation is important, here, */ 4455 /* to avoid wrap. */ 4456 exponent=(lhs->exponent+lhs->digits)-(rhs->exponent+rhs->digits); 4457 4458 /* If the working exponent is -ve, then some quick exits are */ 4459 /* possible because the quotient is known to be <1 */ 4460 /* [for REMNEAR, it needs to be < -1, as -0.5 could need work] */ 4461 if (exponent<0 && !(op==DIVIDE)) { 4462 if (op&DIVIDEINT) { 4463 decNumberZero(res); /* integer part is 0 */ 4464 #if DECSUBSET 4465 if (set->extended) 4466 #endif 4467 res->bits=bits; /* set +/- zero */ 4468 break;} 4469 /* fastpath remainders so long as the lhs has the smaller */ 4470 /* (or equal) exponent */ 4471 if (lhs->exponent<=rhs->exponent) { 4472 if (op&REMAINDER || exponent<-1) { 4473 /* It is REMAINDER or safe REMNEAR; result is [finished */ 4474 /* clone of] lhs (r = x - 0*y) */ 4475 residue=0; 4476 decCopyFit(res, lhs, set, &residue, status); 4477 decFinish(res, set, &residue, status); 4478 break; 4479 } 4480 /* [unsafe REMNEAR drops through] */ 4481 } 4482 } /* fastpaths */ 4483 4484 /* Long (slow) division is needed; roll up the sleeves... */ 4485 4486 /* The accumulator will hold the quotient of the division. */ 4487 /* If it needs to be too long for stack storage, then allocate. */ 4488 acclength=D2U(reqdigits+DECDPUN); /* in Units */ 4489 if (acclength*sizeof(Unit)>sizeof(accbuff)) { 4490 /* printf("malloc dvacc %ld units\n", acclength); */ 4491 allocacc=(Unit *)malloc(acclength*sizeof(Unit)); 4492 if (allocacc==NULL) { /* hopeless -- abandon */ 4493 *status|=DEC_Insufficient_storage; 4494 break;} 4495 acc=allocacc; /* use the allocated space */ 4496 } 4497 4498 /* var1 is the padded LHS ready for subtractions. */ 4499 /* If it needs to be too long for stack storage, then allocate. */ 4500 /* The maximum units needed for var1 (long subtraction) is: */ 4501 /* Enough for */ 4502 /* (rhs->digits+reqdigits-1) -- to allow full slide to right */ 4503 /* or (lhs->digits) -- to allow for long lhs */ 4504 /* whichever is larger */ 4505 /* +1 -- for rounding of slide to right */ 4506 /* +1 -- for leading 0s */ 4507 /* +1 -- for pre-adjust if a remainder or DIVIDEINT */ 4508 /* [Note: unused units do not participate in decUnitAddSub data] */ 4509 maxdigits=rhs->digits+reqdigits-1; 4510 if (lhs->digits>maxdigits) maxdigits=lhs->digits; 4511 var1units=D2U(maxdigits)+2; 4512 /* allocate a guard unit above msu1 for REMAINDERNEAR */ 4513 if (!(op&DIVIDE)) var1units++; 4514 if ((var1units+1)*sizeof(Unit)>sizeof(varbuff)) { 4515 /* printf("malloc dvvar %ld units\n", var1units+1); */ 4516 varalloc=(Unit *)malloc((var1units+1)*sizeof(Unit)); 4517 if (varalloc==NULL) { /* hopeless -- abandon */ 4518 *status|=DEC_Insufficient_storage; 4519 break;} 4520 var1=varalloc; /* use the allocated space */ 4521 } 4522 4523 /* Extend the lhs and rhs to full long subtraction length. The lhs */ 4524 /* is truly extended into the var1 buffer, with 0 padding, so a */ 4525 /* subtract in place is always possible. The rhs (var2) has */ 4526 /* virtual padding (implemented by decUnitAddSub). */ 4527 /* One guard unit was allocated above msu1 for rem=rem+rem in */ 4528 /* REMAINDERNEAR. */ 4529 msu1=var1+var1units-1; /* msu of var1 */ 4530 source=lhs->lsu+D2U(lhs->digits)-1; /* msu of input array */ 4531 for (target=msu1; source>=lhs->lsu; source--, target--) *target=*source; 4532 for (; target>=var1; target--) *target=0; 4533 4534 /* rhs (var2) is left-aligned with var1 at the start */ 4535 var2ulen=var1units; /* rhs logical length (units) */ 4536 var2units=D2U(rhs->digits); /* rhs actual length (units) */ 4537 var2=rhs->lsu; /* -> rhs array */ 4538 msu2=var2+var2units-1; /* -> msu of var2 [never changes] */ 4539 /* now set up the variables which will be used for estimating the */ 4540 /* multiplication factor. If these variables are not exact, add */ 4541 /* 1 to make sure that the multiplier is never overestimated. */ 4542 msu2plus=*msu2; /* it's value .. */ 4543 if (var2units>1) msu2plus++; /* .. +1 if any more */ 4544 msu2pair=(eInt)*msu2*(DECDPUNMAX+1);/* top two pair .. */ 4545 if (var2units>1) { /* .. [else treat 2nd as 0] */ 4546 msu2pair+=*(msu2-1); /* .. */ 4547 if (var2units>2) msu2pair++; /* .. +1 if any more */ 4548 } 4549 4550 /* The calculation is working in units, which may have leading zeros, */ 4551 /* but the exponent was calculated on the assumption that they are */ 4552 /* both left-aligned. Adjust the exponent to compensate: add the */ 4553 /* number of leading zeros in var1 msu and subtract those in var2 msu. */ 4554 /* [This is actually done by counting the digits and negating, as */ 4555 /* lead1=DECDPUN-digits1, and similarly for lead2.] */ 4556 for (pow=&powers[1]; *msu1>=*pow; pow++) exponent--; 4557 for (pow=&powers[1]; *msu2>=*pow; pow++) exponent++; 4558 4559 /* Now, if doing an integer divide or remainder, ensure that */ 4560 /* the result will be Unit-aligned. To do this, shift the var1 */ 4561 /* accumulator towards least if need be. (It's much easier to */ 4562 /* do this now than to reassemble the residue afterwards, if */ 4563 /* doing a remainder.) Also ensure the exponent is not negative. */ 4564 if (!(op&DIVIDE)) { 4565 Unit *u; /* work */ 4566 /* save the initial 'false' padding of var1, in digits */ 4567 var1initpad=(var1units-D2U(lhs->digits))*DECDPUN; 4568 /* Determine the shift to do. */ 4569 if (exponent<0) cut=-exponent; 4570 else cut=DECDPUN-exponent%DECDPUN; 4571 decShiftToLeast(var1, var1units, cut); 4572 exponent+=cut; /* maintain numerical value */ 4573 var1initpad-=cut; /* .. and reduce padding */ 4574 /* clean any most-significant units which were just emptied */ 4575 for (u=msu1; cut>=DECDPUN; cut-=DECDPUN, u--) *u=0; 4576 } /* align */ 4577 else { /* is DIVIDE */ 4578 maxexponent=lhs->exponent-rhs->exponent; /* save */ 4579 /* optimization: if the first iteration will just produce 0, */ 4580 /* preadjust to skip it [valid for DIVIDE only] */ 4581 if (*msu1<*msu2) { 4582 var2ulen--; /* shift down */ 4583 exponent-=DECDPUN; /* update the exponent */ 4584 } 4585 } 4586 4587 /* ---- start the long-division loops ------------------------------ */ 4588 accunits=0; /* no units accumulated yet */ 4589 accdigits=0; /* .. or digits */ 4590 accnext=acc+acclength-1; /* -> msu of acc [NB: allows digits+1] */ 4591 for (;;) { /* outer forever loop */ 4592 thisunit=0; /* current unit assumed 0 */ 4593 /* find the next unit */ 4594 for (;;) { /* inner forever loop */ 4595 /* strip leading zero units [from either pre-adjust or from */ 4596 /* subtract last time around]. Leave at least one unit. */ 4597 for (; *msu1==0 && msu1>var1; msu1--) var1units--; 4598 4599 if (var1units<var2ulen) break; /* var1 too low for subtract */ 4600 if (var1units==var2ulen) { /* unit-by-unit compare needed */ 4601 /* compare the two numbers, from msu */ 4602 const Unit *pv1, *pv2; 4603 Unit v2; /* units to compare */ 4604 pv2=msu2; /* -> msu */ 4605 for (pv1=msu1; ; pv1--, pv2--) { 4606 /* v1=*pv1 -- always OK */ 4607 v2=0; /* assume in padding */ 4608 if (pv2>=var2) v2=*pv2; /* in range */ 4609 if (*pv1!=v2) break; /* no longer the same */ 4610 if (pv1==var1) break; /* done; leave pv1 as is */ 4611 } 4612 /* here when all inspected or a difference seen */ 4613 if (*pv1<v2) break; /* var1 too low to subtract */ 4614 if (*pv1==v2) { /* var1 == var2 */ 4615 /* reach here if var1 and var2 are identical; subtraction */ 4616 /* would increase digit by one, and the residue will be 0 so */ 4617 /* the calculation is done; leave the loop with residue=0. */ 4618 thisunit++; /* as though subtracted */ 4619 *var1=0; /* set var1 to 0 */ 4620 var1units=1; /* .. */ 4621 break; /* from inner */ 4622 } /* var1 == var2 */ 4623 /* *pv1>v2. Prepare for real subtraction; the lengths are equal */ 4624 /* Estimate the multiplier (there's always a msu1-1)... */ 4625 /* Bring in two units of var2 to provide a good estimate. */ 4626 mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2pair); 4627 } /* lengths the same */ 4628 else { /* var1units > var2ulen, so subtraction is safe */ 4629 /* The var2 msu is one unit towards the lsu of the var1 msu, */ 4630 /* so only one unit for var2 can be used. */ 4631 mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2plus); 4632 } 4633 if (mult==0) mult=1; /* must always be at least 1 */ 4634 /* subtraction needed; var1 is > var2 */ 4635 thisunit=(Unit)(thisunit+mult); /* accumulate */ 4636 /* subtract var1-var2, into var1; only the overlap needs */ 4637 /* processing, as this is an in-place calculation */ 4638 shift=var2ulen-var2units; 4639 #if DECTRACE 4640 decDumpAr('1', &var1[shift], var1units-shift); 4641 decDumpAr('2', var2, var2units); 4642 printf("m=%ld\n", -mult); 4643 #endif 4644 decUnitAddSub(&var1[shift], var1units-shift, 4645 var2, var2units, 0, 4646 &var1[shift], -mult); 4647 #if DECTRACE 4648 decDumpAr('#', &var1[shift], var1units-shift); 4649 #endif 4650 /* var1 now probably has leading zeros; these are removed at the */ 4651 /* top of the inner loop. */ 4652 } /* inner loop */ 4653 4654 /* The next unit has been calculated in full; unless it's a */ 4655 /* leading zero, add to acc */ 4656 if (accunits!=0 || thisunit!=0) { /* is first or non-zero */ 4657 *accnext=thisunit; /* store in accumulator */ 4658 /* account exactly for the new digits */ 4659 if (accunits==0) { 4660 accdigits++; /* at least one */ 4661 for (pow=&powers[1]; thisunit>=*pow; pow++) accdigits++; 4662 } 4663 else accdigits+=DECDPUN; 4664 accunits++; /* update count */ 4665 accnext--; /* ready for next */ 4666 if (accdigits>reqdigits) break; /* have enough digits */ 4667 } 4668 4669 /* if the residue is zero, the operation is done (unless divide */ 4670 /* or divideInteger and still not enough digits yet) */ 4671 if (*var1==0 && var1units==1) { /* residue is 0 */ 4672 if (op&(REMAINDER|REMNEAR)) break; 4673 if ((op&DIVIDE) && (exponent<=maxexponent)) break; 4674 /* [drop through if divideInteger] */ 4675 } 4676 /* also done enough if calculating remainder or integer */ 4677 /* divide and just did the last ('units') unit */ 4678 if (exponent==0 && !(op&DIVIDE)) break; 4679 4680 /* to get here, var1 is less than var2, so divide var2 by the per- */ 4681 /* Unit power of ten and go for the next digit */ 4682 var2ulen--; /* shift down */ 4683 exponent-=DECDPUN; /* update the exponent */ 4684 } /* outer loop */ 4685 4686 /* ---- division is complete --------------------------------------- */ 4687 /* here: acc has at least reqdigits+1 of good results (or fewer */ 4688 /* if early stop), starting at accnext+1 (its lsu) */ 4689 /* var1 has any residue at the stopping point */ 4690 /* accunits is the number of digits collected in acc */ 4691 if (accunits==0) { /* acc is 0 */ 4692 accunits=1; /* show have a unit .. */ 4693 accdigits=1; /* .. */ 4694 *accnext=0; /* .. whose value is 0 */ 4695 } 4696 else accnext++; /* back to last placed */ 4697 /* accnext now -> lowest unit of result */ 4698 4699 residue=0; /* assume no residue */ 4700 if (op&DIVIDE) { 4701 /* record the presence of any residue, for rounding */ 4702 if (*var1!=0 || var1units>1) residue=1; 4703 else { /* no residue */ 4704 /* Had an exact division; clean up spurious trailing 0s. */ 4705 /* There will be at most DECDPUN-1, from the final multiply, */ 4706 /* and then only if the result is non-0 (and even) and the */ 4707 /* exponent is 'loose'. */ 4708 #if DECDPUN>1 4709 Unit lsu=*accnext; 4710 if (!(lsu&0x01) && (lsu!=0)) { 4711 /* count the trailing zeros */ 4712 Int drop=0; 4713 for (;; drop++) { /* [will terminate because lsu!=0] */ 4714 if (exponent>=maxexponent) break; /* don't chop real 0s */ 4715 #if DECDPUN<=4 4716 if ((lsu-QUOT10(lsu, drop+1) 4717 *powers[drop+1])!=0) break; /* found non-0 digit */ 4718 #else 4719 if (lsu%powers[drop+1]!=0) break; /* found non-0 digit */ 4720 #endif 4721 exponent++; 4722 } 4723 if (drop>0) { 4724 accunits=decShiftToLeast(accnext, accunits, drop); 4725 accdigits=decGetDigits(accnext, accunits); 4726 accunits=D2U(accdigits); 4727 /* [exponent was adjusted in the loop] */ 4728 } 4729 } /* neither odd nor 0 */ 4730 #endif 4731 } /* exact divide */ 4732 } /* divide */ 4733 else /* op!=DIVIDE */ { 4734 /* check for coefficient overflow */ 4735 if (accdigits+exponent>reqdigits) { 4736 *status|=DEC_Division_impossible; 4737 break; 4738 } 4739 if (op & (REMAINDER|REMNEAR)) { 4740 /* [Here, the exponent will be 0, because var1 was adjusted */ 4741 /* appropriately.] */ 4742 Int postshift; /* work */ 4743 Flag wasodd=0; /* integer was odd */ 4744 Unit *quotlsu; /* for save */ 4745 Int quotdigits; /* .. */ 4746 4747 bits=lhs->bits; /* remainder sign is always as lhs */ 4748 4749 /* Fastpath when residue is truly 0 is worthwhile [and */ 4750 /* simplifies the code below] */ 4751 if (*var1==0 && var1units==1) { /* residue is 0 */ 4752 Int exp=lhs->exponent; /* save min(exponents) */ 4753 if (rhs->exponent<exp) exp=rhs->exponent; 4754 decNumberZero(res); /* 0 coefficient */ 4755 #if DECSUBSET 4756 if (set->extended) 4757 #endif 4758 res->exponent=exp; /* .. with proper exponent */ 4759 res->bits=(uByte)(bits&DECNEG); /* [cleaned] */ 4760 decFinish(res, set, &residue, status); /* might clamp */ 4761 break; 4762 } 4763 /* note if the quotient was odd */ 4764 if (*accnext & 0x01) wasodd=1; /* acc is odd */ 4765 quotlsu=accnext; /* save in case need to reinspect */ 4766 quotdigits=accdigits; /* .. */ 4767 4768 /* treat the residue, in var1, as the value to return, via acc */ 4769 /* calculate the unused zero digits. This is the smaller of: */ 4770 /* var1 initial padding (saved above) */ 4771 /* var2 residual padding, which happens to be given by: */ 4772 postshift=var1initpad+exponent-lhs->exponent+rhs->exponent; 4773 /* [the 'exponent' term accounts for the shifts during divide] */ 4774 if (var1initpad<postshift) postshift=var1initpad; 4775 4776 /* shift var1 the requested amount, and adjust its digits */ 4777 var1units=decShiftToLeast(var1, var1units, postshift); 4778 accnext=var1; 4779 accdigits=decGetDigits(var1, var1units); 4780 accunits=D2U(accdigits); 4781 4782 exponent=lhs->exponent; /* exponent is smaller of lhs & rhs */ 4783 if (rhs->exponent<exponent) exponent=rhs->exponent; 4784 4785 /* Now correct the result if doing remainderNear; if it */ 4786 /* (looking just at coefficients) is > rhs/2, or == rhs/2 and */ 4787 /* the integer was odd then the result should be rem-rhs. */ 4788 if (op&REMNEAR) { 4789 Int compare, tarunits; /* work */ 4790 Unit *up; /* .. */ 4791 /* calculate remainder*2 into the var1 buffer (which has */ 4792 /* 'headroom' of an extra unit and hence enough space) */ 4793 /* [a dedicated 'double' loop would be faster, here] */ 4794 tarunits=decUnitAddSub(accnext, accunits, accnext, accunits, 4795 0, accnext, 1); 4796 /* decDumpAr('r', accnext, tarunits); */ 4797 4798 /* Here, accnext (var1) holds tarunits Units with twice the */ 4799 /* remainder's coefficient, which must now be compared to the */ 4800 /* RHS. The remainder's exponent may be smaller than the RHS's. */ 4801 compare=decUnitCompare(accnext, tarunits, rhs->lsu, D2U(rhs->digits), 4802 rhs->exponent-exponent); 4803 if (compare==BADINT) { /* deep trouble */ 4804 *status|=DEC_Insufficient_storage; 4805 break;} 4806 4807 /* now restore the remainder by dividing by two; the lsu */ 4808 /* is known to be even. */ 4809 for (up=accnext; up<accnext+tarunits; up++) { 4810 Int half; /* half to add to lower unit */ 4811 half=*up & 0x01; 4812 *up/=2; /* [shift] */ 4813 if (!half) continue; 4814 *(up-1)+=DIV_ROUND_UP(DECDPUNMAX, 2); 4815 } 4816 /* [accunits still describes the original remainder length] */ 4817 4818 if (compare>0 || (compare==0 && wasodd)) { /* adjustment needed */ 4819 Int exp, expunits, exprem; /* work */ 4820 /* This is effectively causing round-up of the quotient, */ 4821 /* so if it was the rare case where it was full and all */ 4822 /* nines, it would overflow and hence division-impossible */ 4823 /* should be raised */ 4824 Flag allnines=0; /* 1 if quotient all nines */ 4825 if (quotdigits==reqdigits) { /* could be borderline */ 4826 for (up=quotlsu; ; up++) { 4827 if (quotdigits>DECDPUN) { 4828 if (*up!=DECDPUNMAX) break;/* non-nines */ 4829 } 4830 else { /* this is the last Unit */ 4831 if (*up==powers[quotdigits]-1) allnines=1; 4832 break; 4833 } 4834 quotdigits-=DECDPUN; /* checked those digits */ 4835 } /* up */ 4836 } /* borderline check */ 4837 if (allnines) { 4838 *status|=DEC_Division_impossible; 4839 break;} 4840 4841 /* rem-rhs is needed; the sign will invert. Again, var1 */ 4842 /* can safely be used for the working Units array. */ 4843 exp=rhs->exponent-exponent; /* RHS padding needed */ 4844 /* Calculate units and remainder from exponent. */ 4845 expunits=exp/DECDPUN; 4846 exprem=exp%DECDPUN; 4847 /* subtract [A+B*(-m)]; the result will always be negative */ 4848 accunits=-decUnitAddSub(accnext, accunits, 4849 rhs->lsu, D2U(rhs->digits), 4850 expunits, accnext, -(Int)powers[exprem]); 4851 accdigits=decGetDigits(accnext, accunits); /* count digits exactly */ 4852 accunits=D2U(accdigits); /* and recalculate the units for copy */ 4853 /* [exponent is as for original remainder] */ 4854 bits^=DECNEG; /* flip the sign */ 4855 } 4856 } /* REMNEAR */ 4857 } /* REMAINDER or REMNEAR */ 4858 } /* not DIVIDE */ 4859 4860 /* Set exponent and bits */ 4861 res->exponent=exponent; 4862 res->bits=(uByte)(bits&DECNEG); /* [cleaned] */ 4863 4864 /* Now the coefficient. */ 4865 decSetCoeff(res, set, accnext, accdigits, &residue, status); 4866 4867 decFinish(res, set, &residue, status); /* final cleanup */ 4868 4869 #if DECSUBSET 4870 /* If a divide then strip trailing zeros if subset [after round] */ 4871 if (!set->extended && (op==DIVIDE)) decTrim(res, set, 0, &dropped); 4872 #endif 4873 } while(0); /* end protected */ 4874 4875 if (varalloc!=NULL) free(varalloc); /* drop any storage used */ 4876 if (allocacc!=NULL) free(allocacc); /* .. */ 4877 #if DECSUBSET 4878 if (allocrhs!=NULL) free(allocrhs); /* .. */ 4879 if (alloclhs!=NULL) free(alloclhs); /* .. */ 4880 #endif 4881 return res; 4882 } /* decDivideOp */ 4883 4884 /* ------------------------------------------------------------------ */ 4885 /* decMultiplyOp -- multiplication operation */ 4886 /* */ 4887 /* This routine performs the multiplication C=A x B. */ 4888 /* */ 4889 /* res is C, the result. C may be A and/or B (e.g., X=X*X) */ 4890 /* lhs is A */ 4891 /* rhs is B */ 4892 /* set is the context */ 4893 /* status is the usual accumulator */ 4894 /* */ 4895 /* C must have space for set->digits digits. */ 4896 /* */ 4897 /* ------------------------------------------------------------------ */ 4898 /* 'Classic' multiplication is used rather than Karatsuba, as the */ 4899 /* latter would give only a minor improvement for the short numbers */ 4900 /* expected to be handled most (and uses much more memory). */ 4901 /* */ 4902 /* There are two major paths here: the general-purpose ('old code') */ 4903 /* path which handles all DECDPUN values, and a fastpath version */ 4904 /* which is used if 64-bit ints are available, DECDPUN<=4, and more */ 4905 /* than two calls to decUnitAddSub would be made. */ 4906 /* */ 4907 /* The fastpath version lumps units together into 8-digit or 9-digit */ 4908 /* chunks, and also uses a lazy carry strategy to minimise expensive */ 4909 /* 64-bit divisions. The chunks are then broken apart again into */ 4910 /* units for continuing processing. Despite this overhead, the */ 4911 /* fastpath can speed up some 16-digit operations by 10x (and much */ 4912 /* more for higher-precision calculations). */ 4913 /* */ 4914 /* A buffer always has to be used for the accumulator; in the */ 4915 /* fastpath, buffers are also always needed for the chunked copies of */ 4916 /* of the operand coefficients. */ 4917 /* Static buffers are larger than needed just for multiply, to allow */ 4918 /* for calls from other operations (notably exp). */ 4919 /* ------------------------------------------------------------------ */ 4920 #define FASTMUL (DECUSE64 && DECDPUN<5) 4921 static decNumber * decMultiplyOp(decNumber *res, const decNumber *lhs, 4922 const decNumber *rhs, decContext *set, 4923 uInt *status) { 4924 Int accunits; /* Units of accumulator in use */ 4925 Int exponent; /* work */ 4926 Int residue=0; /* rounding residue */ 4927 uByte bits; /* result sign */ 4928 Unit *acc; /* -> accumulator Unit array */ 4929 Int needbytes; /* size calculator */ 4930 void *allocacc=NULL; /* -> allocated accumulator, iff allocated */ 4931 Unit accbuff[SD2U(DECBUFFER*4+1)]; /* buffer (+1 for DECBUFFER==0, */ 4932 /* *4 for calls from other operations) */ 4933 const Unit *mer, *mermsup; /* work */ 4934 Int madlength; /* Units in multiplicand */ 4935 Int shift; /* Units to shift multiplicand by */ 4936 4937 #if FASTMUL 4938 /* if DECDPUN is 1 or 3 work in base 10**9, otherwise */ 4939 /* (DECDPUN is 2 or 4) then work in base 10**8 */ 4940 #if DECDPUN & 1 /* odd */ 4941 #define FASTBASE 1000000000 /* base */ 4942 #define FASTDIGS 9 /* digits in base */ 4943 #define FASTLAZY 18 /* carry resolution point [1->18] */ 4944 #else 4945 #define FASTBASE 100000000 4946 #define FASTDIGS 8 4947 #define FASTLAZY 1844 /* carry resolution point [1->1844] */ 4948 #endif 4949 /* three buffers are used, two for chunked copies of the operands */ 4950 /* (base 10**8 or base 10**9) and one base 2**64 accumulator with */ 4951 /* lazy carry evaluation */ 4952 uInt zlhibuff[(DECBUFFER*2+1)/8+1]; /* buffer (+1 for DECBUFFER==0) */ 4953 uInt *zlhi=zlhibuff; /* -> lhs array */ 4954 uInt *alloclhi=NULL; /* -> allocated buffer, iff allocated */ 4955 uInt zrhibuff[(DECBUFFER*2+1)/8+1]; /* buffer (+1 for DECBUFFER==0) */ 4956 uInt *zrhi=zrhibuff; /* -> rhs array */ 4957 uInt *allocrhi=NULL; /* -> allocated buffer, iff allocated */ 4958 uLong zaccbuff[(DECBUFFER*2+1)/4+2]; /* buffer (+1 for DECBUFFER==0) */ 4959 /* [allocacc is shared for both paths, as only one will run] */ 4960 uLong *zacc=zaccbuff; /* -> accumulator array for exact result */ 4961 #if DECDPUN==1 4962 Int zoff; /* accumulator offset */ 4963 #endif 4964 uInt *lip, *rip; /* item pointers */ 4965 uInt *lmsi, *rmsi; /* most significant items */ 4966 Int ilhs, irhs, iacc; /* item counts in the arrays */ 4967 Int lazy; /* lazy carry counter */ 4968 uLong lcarry; /* uLong carry */ 4969 uInt carry; /* carry (NB not uLong) */ 4970 Int count; /* work */ 4971 const Unit *cup; /* .. */ 4972 Unit *up; /* .. */ 4973 uLong *lp; /* .. */ 4974 Int p; /* .. */ 4975 #endif 4976 4977 #if DECSUBSET 4978 decNumber *alloclhs=NULL; /* -> allocated buffer, iff allocated */ 4979 decNumber *allocrhs=NULL; /* -> allocated buffer, iff allocated */ 4980 #endif 4981 4982 #if DECCHECK 4983 if (decCheckOperands(res, lhs, rhs, set)) return res; 4984 #endif 4985 4986 /* precalculate result sign */ 4987 bits=(uByte)((lhs->bits^rhs->bits)&DECNEG); 4988 4989 /* handle infinities and NaNs */ 4990 if (SPECIALARGS) { /* a special bit set */ 4991 if (SPECIALARGS & (DECSNAN | DECNAN)) { /* one or two NaNs */ 4992 decNaNs(res, lhs, rhs, set, status); 4993 return res;} 4994 /* one or two infinities; Infinity * 0 is invalid */ 4995 if (((lhs->bits & DECINF)==0 && ISZERO(lhs)) 4996 ||((rhs->bits & DECINF)==0 && ISZERO(rhs))) { 4997 *status|=DEC_Invalid_operation; 4998 return res;} 4999 decNumberZero(res); 5000 res->bits=bits|DECINF; /* infinity */ 5001 return res;} 5002 5003 /* For best speed, as in DMSRCN [the original Rexx numerics */ 5004 /* module], use the shorter number as the multiplier (rhs) and */ 5005 /* the longer as the multiplicand (lhs) to minimise the number of */ 5006 /* adds (partial products) */ 5007 if (lhs->digits<rhs->digits) { /* swap... */ 5008 const decNumber *hold=lhs; 5009 lhs=rhs; 5010 rhs=hold; 5011 } 5012 5013 do { /* protect allocated storage */ 5014 #if DECSUBSET 5015 if (!set->extended) { 5016 /* reduce operands and set lostDigits status, as needed */ 5017 if (lhs->digits>set->digits) { 5018 alloclhs=decRoundOperand(lhs, set, status); 5019 if (alloclhs==NULL) break; 5020 lhs=alloclhs; 5021 } 5022 if (rhs->digits>set->digits) { 5023 allocrhs=decRoundOperand(rhs, set, status); 5024 if (allocrhs==NULL) break; 5025 rhs=allocrhs; 5026 } 5027 } 5028 #endif 5029 /* [following code does not require input rounding] */ 5030 5031 #if FASTMUL /* fastpath can be used */ 5032 /* use the fast path if there are enough digits in the shorter */ 5033 /* operand to make the setup and takedown worthwhile */ 5034 #define NEEDTWO (DECDPUN*2) /* within two decUnitAddSub calls */ 5035 if (rhs->digits>NEEDTWO) { /* use fastpath... */ 5036 /* calculate the number of elements in each array */ 5037 ilhs=(lhs->digits+FASTDIGS-1)/FASTDIGS; /* [ceiling] */ 5038 irhs=(rhs->digits+FASTDIGS-1)/FASTDIGS; /* .. */ 5039 iacc=ilhs+irhs; 5040 5041 /* allocate buffers if required, as usual */ 5042 needbytes=ilhs*sizeof(uInt); 5043 if (needbytes>(Int)sizeof(zlhibuff)) { 5044 alloclhi=(uInt *)malloc(needbytes); 5045 zlhi=alloclhi;} 5046 needbytes=irhs*sizeof(uInt); 5047 if (needbytes>(Int)sizeof(zrhibuff)) { 5048 allocrhi=(uInt *)malloc(needbytes); 5049 zrhi=allocrhi;} 5050 5051 /* Allocating the accumulator space needs a special case when */ 5052 /* DECDPUN=1 because when converting the accumulator to Units */ 5053 /* after the multiplication each 8-byte item becomes 9 1-byte */ 5054 /* units. Therefore iacc extra bytes are needed at the front */ 5055 /* (rounded up to a multiple of 8 bytes), and the uLong */ 5056 /* accumulator starts offset the appropriate number of units */ 5057 /* to the right to avoid overwrite during the unchunking. */ 5058 needbytes=iacc*sizeof(uLong); 5059 #if DECDPUN==1 5060 zoff=(iacc+7)/8; /* items to offset by */ 5061 needbytes+=zoff*8; 5062 #endif 5063 if (needbytes>(Int)sizeof(zaccbuff)) { 5064 allocacc=(uLong *)malloc(needbytes); 5065 zacc=(uLong *)allocacc;} 5066 if (zlhi==NULL||zrhi==NULL||zacc==NULL) { 5067 *status|=DEC_Insufficient_storage; 5068 break;} 5069 5070 acc=(Unit *)zacc; /* -> target Unit array */ 5071 #if DECDPUN==1 5072 zacc+=zoff; /* start uLong accumulator to right */ 5073 #endif 5074 5075 /* assemble the chunked copies of the left and right sides */ 5076 for (count=lhs->digits, cup=lhs->lsu, lip=zlhi; count>0; lip++) 5077 for (p=0, *lip=0; p<FASTDIGS && count>0; 5078 p+=DECDPUN, cup++, count-=DECDPUN) 5079 *lip+=*cup*powers[p]; 5080 lmsi=lip-1; /* save -> msi */ 5081 for (count=rhs->digits, cup=rhs->lsu, rip=zrhi; count>0; rip++) 5082 for (p=0, *rip=0; p<FASTDIGS && count>0; 5083 p+=DECDPUN, cup++, count-=DECDPUN) 5084 *rip+=*cup*powers[p]; 5085 rmsi=rip-1; /* save -> msi */ 5086 5087 /* zero the accumulator */ 5088 for (lp=zacc; lp<zacc+iacc; lp++) *lp=0; 5089 5090 /* Start the multiplication */ 5091 /* Resolving carries can dominate the cost of accumulating the */ 5092 /* partial products, so this is only done when necessary. */ 5093 /* Each uLong item in the accumulator can hold values up to */ 5094 /* 2**64-1, and each partial product can be as large as */ 5095 /* (10**FASTDIGS-1)**2. When FASTDIGS=9, this can be added to */ 5096 /* itself 18.4 times in a uLong without overflowing, so during */ 5097 /* the main calculation resolution is carried out every 18th */ 5098 /* add -- every 162 digits. Similarly, when FASTDIGS=8, the */ 5099 /* partial products can be added to themselves 1844.6 times in */ 5100 /* a uLong without overflowing, so intermediate carry */ 5101 /* resolution occurs only every 14752 digits. Hence for common */ 5102 /* short numbers usually only the one final carry resolution */ 5103 /* occurs. */ 5104 /* (The count is set via FASTLAZY to simplify experiments to */ 5105 /* measure the value of this approach: a 35% improvement on a */ 5106 /* [34x34] multiply.) */ 5107 lazy=FASTLAZY; /* carry delay count */ 5108 for (rip=zrhi; rip<=rmsi; rip++) { /* over each item in rhs */ 5109 lp=zacc+(rip-zrhi); /* where to add the lhs */ 5110 for (lip=zlhi; lip<=lmsi; lip++, lp++) { /* over each item in lhs */ 5111 *lp+=(uLong)(*lip)*(*rip); /* [this should in-line] */ 5112 } /* lip loop */ 5113 lazy--; 5114 if (lazy>0 && rip!=rmsi) continue; 5115 lazy=FASTLAZY; /* reset delay count */ 5116 /* spin up the accumulator resolving overflows */ 5117 for (lp=zacc; lp<zacc+iacc; lp++) { 5118 if (*lp<FASTBASE) continue; /* it fits */ 5119 lcarry=*lp/FASTBASE; /* top part [slow divide] */ 5120 /* lcarry can exceed 2**32-1, so check again; this check */ 5121 /* and occasional extra divide (slow) is well worth it, as */ 5122 /* it allows FASTLAZY to be increased to 18 rather than 4 */ 5123 /* in the FASTDIGS=9 case */ 5124 if (lcarry<FASTBASE) carry=(uInt)lcarry; /* [usual] */ 5125 else { /* two-place carry [fairly rare] */ 5126 uInt carry2=(uInt)(lcarry/FASTBASE); /* top top part */ 5127 *(lp+2)+=carry2; /* add to item+2 */ 5128 *lp-=((uLong)FASTBASE*FASTBASE*carry2); /* [slow] */ 5129 carry=(uInt)(lcarry-((uLong)FASTBASE*carry2)); /* [inline] */ 5130 } 5131 *(lp+1)+=carry; /* add to item above [inline] */ 5132 *lp-=((uLong)FASTBASE*carry); /* [inline] */ 5133 } /* carry resolution */ 5134 } /* rip loop */ 5135 5136 /* The multiplication is complete; time to convert back into */ 5137 /* units. This can be done in-place in the accumulator and in */ 5138 /* 32-bit operations, because carries were resolved after the */ 5139 /* final add. This needs N-1 divides and multiplies for */ 5140 /* each item in the accumulator (which will become up to N */ 5141 /* units, where 2<=N<=9). */ 5142 for (lp=zacc, up=acc; lp<zacc+iacc; lp++) { 5143 uInt item=(uInt)*lp; /* decapitate to uInt */ 5144 for (p=0; p<FASTDIGS-DECDPUN; p+=DECDPUN, up++) { 5145 uInt part=item/(DECDPUNMAX+1); 5146 *up=(Unit)(item-(part*(DECDPUNMAX+1))); 5147 item=part; 5148 } /* p */ 5149 *up=(Unit)item; up++; /* [final needs no division] */ 5150 } /* lp */ 5151 accunits=up-acc; /* count of units */ 5152 } 5153 else { /* here to use units directly, without chunking ['old code'] */ 5154 #endif 5155 5156 /* if accumulator will be too long for local storage, then allocate */ 5157 acc=accbuff; /* -> assume buffer for accumulator */ 5158 needbytes=(D2U(lhs->digits)+D2U(rhs->digits))*sizeof(Unit); 5159 if (needbytes>(Int)sizeof(accbuff)) { 5160 allocacc=(Unit *)malloc(needbytes); 5161 if (allocacc==NULL) {*status|=DEC_Insufficient_storage; break;} 5162 acc=(Unit *)allocacc; /* use the allocated space */ 5163 } 5164 5165 /* Now the main long multiplication loop */ 5166 /* Unlike the equivalent in the IBM Java implementation, there */ 5167 /* is no advantage in calculating from msu to lsu. So, do it */ 5168 /* by the book, as it were. */ 5169 /* Each iteration calculates ACC=ACC+MULTAND*MULT */ 5170 accunits=1; /* accumulator starts at '0' */ 5171 *acc=0; /* .. (lsu=0) */ 5172 shift=0; /* no multiplicand shift at first */ 5173 madlength=D2U(lhs->digits); /* this won't change */ 5174 mermsup=rhs->lsu+D2U(rhs->digits); /* -> msu+1 of multiplier */ 5175 5176 for (mer=rhs->lsu; mer<mermsup; mer++) { 5177 /* Here, *mer is the next Unit in the multiplier to use */ 5178 /* If non-zero [optimization] add it... */ 5179 if (*mer!=0) accunits=decUnitAddSub(&acc[shift], accunits-shift, 5180 lhs->lsu, madlength, 0, 5181 &acc[shift], *mer) 5182 + shift; 5183 else { /* extend acc with a 0; it will be used shortly */ 5184 *(acc+accunits)=0; /* [this avoids length of <=0 later] */ 5185 accunits++; 5186 } 5187 /* multiply multiplicand by 10**DECDPUN for next Unit to left */ 5188 shift++; /* add this for 'logical length' */ 5189 } /* n */ 5190 #if FASTMUL 5191 } /* unchunked units */ 5192 #endif 5193 /* common end-path */ 5194 #if DECTRACE 5195 decDumpAr('*', acc, accunits); /* Show exact result */ 5196 #endif 5197 5198 /* acc now contains the exact result of the multiplication, */ 5199 /* possibly with a leading zero unit; build the decNumber from */ 5200 /* it, noting if any residue */ 5201 res->bits=bits; /* set sign */ 5202 res->digits=decGetDigits(acc, accunits); /* count digits exactly */ 5203 5204 /* There can be a 31-bit wrap in calculating the exponent. */ 5205 /* This can only happen if both input exponents are negative and */ 5206 /* both their magnitudes are large. If there was a wrap, set a */ 5207 /* safe very negative exponent, from which decFinalize() will */ 5208 /* raise a hard underflow shortly. */ 5209 exponent=lhs->exponent+rhs->exponent; /* calculate exponent */ 5210 if (lhs->exponent<0 && rhs->exponent<0 && exponent>0) 5211 exponent=-2*DECNUMMAXE; /* force underflow */ 5212 res->exponent=exponent; /* OK to overwrite now */ 5213 5214 5215 /* Set the coefficient. If any rounding, residue records */ 5216 decSetCoeff(res, set, acc, res->digits, &residue, status); 5217 decFinish(res, set, &residue, status); /* final cleanup */ 5218 } while(0); /* end protected */ 5219 5220 if (allocacc!=NULL) free(allocacc); /* drop any storage used */ 5221 #if DECSUBSET 5222 if (allocrhs!=NULL) free(allocrhs); /* .. */ 5223 if (alloclhs!=NULL) free(alloclhs); /* .. */ 5224 #endif 5225 #if FASTMUL 5226 if (allocrhi!=NULL) free(allocrhi); /* .. */ 5227 if (alloclhi!=NULL) free(alloclhi); /* .. */ 5228 #endif 5229 return res; 5230 } /* decMultiplyOp */ 5231 5232 /* ------------------------------------------------------------------ */ 5233 /* decExpOp -- effect exponentiation */ 5234 /* */ 5235 /* This computes C = exp(A) */ 5236 /* */ 5237 /* res is C, the result. C may be A */ 5238 /* rhs is A */ 5239 /* set is the context; note that rounding mode has no effect */ 5240 /* */ 5241 /* C must have space for set->digits digits. status is updated but */ 5242 /* not set. */ 5243 /* */ 5244 /* Restrictions: */ 5245 /* */ 5246 /* digits, emax, and -emin in the context must be less than */ 5247 /* 2*DEC_MAX_MATH (1999998), and the rhs must be within these */ 5248 /* bounds or a zero. This is an internal routine, so these */ 5249 /* restrictions are contractual and not enforced. */ 5250 /* */ 5251 /* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will */ 5252 /* almost always be correctly rounded, but may be up to 1 ulp in */ 5253 /* error in rare cases. */ 5254 /* */ 5255 /* Finite results will always be full precision and Inexact, except */ 5256 /* when A is a zero or -Infinity (giving 1 or 0 respectively). */ 5257 /* ------------------------------------------------------------------ */ 5258 /* This approach used here is similar to the algorithm described in */ 5259 /* */ 5260 /* Variable Precision Exponential Function, T. E. Hull and */ 5261 /* A. Abrham, ACM Transactions on Mathematical Software, Vol 12 #2, */ 5262 /* pp79-91, ACM, June 1986. */ 5263 /* */ 5264 /* with the main difference being that the iterations in the series */ 5265 /* evaluation are terminated dynamically (which does not require the */ 5266 /* extra variable-precision variables which are expensive in this */ 5267 /* context). */ 5268 /* */ 5269 /* The error analysis in Hull & Abrham's paper applies except for the */ 5270 /* round-off error accumulation during the series evaluation. This */ 5271 /* code does not precalculate the number of iterations and so cannot */ 5272 /* use Horner's scheme. Instead, the accumulation is done at double- */ 5273 /* precision, which ensures that the additions of the terms are exact */ 5274 /* and do not accumulate round-off (and any round-off errors in the */ 5275 /* terms themselves move 'to the right' faster than they can */ 5276 /* accumulate). This code also extends the calculation by allowing, */ 5277 /* in the spirit of other decNumber operators, the input to be more */ 5278 /* precise than the result (the precision used is based on the more */ 5279 /* precise of the input or requested result). */ 5280 /* */ 5281 /* Implementation notes: */ 5282 /* */ 5283 /* 1. This is separated out as decExpOp so it can be called from */ 5284 /* other Mathematical functions (notably Ln) with a wider range */ 5285 /* than normal. In particular, it can handle the slightly wider */ 5286 /* (double) range needed by Ln (which has to be able to calculate */ 5287 /* exp(-x) where x can be the tiniest number (Ntiny). */ 5288 /* */ 5289 /* 2. Normalizing x to be <=0.1 (instead of <=1) reduces loop */ 5290 /* iterations by approximately a third with additional (although */ 5291 /* diminishing) returns as the range is reduced to even smaller */ 5292 /* fractions. However, h (the power of 10 used to correct the */ 5293 /* result at the end, see below) must be kept <=8 as otherwise */ 5294 /* the final result cannot be computed. Hence the leverage is a */ 5295 /* sliding value (8-h), where potentially the range is reduced */ 5296 /* more for smaller values. */ 5297 /* */ 5298 /* The leverage that can be applied in this way is severely */ 5299 /* limited by the cost of the raise-to-the power at the end, */ 5300 /* which dominates when the number of iterations is small (less */ 5301 /* than ten) or when rhs is short. As an example, the adjustment */ 5302 /* x**10,000,000 needs 31 multiplications, all but one full-width. */ 5303 /* */ 5304 /* 3. The restrictions (especially precision) could be raised with */ 5305 /* care, but the full decNumber range seems very hard within the */ 5306 /* 32-bit limits. */ 5307 /* */ 5308 /* 4. The working precisions for the static buffers are twice the */ 5309 /* obvious size to allow for calls from decNumberPower. */ 5310 /* ------------------------------------------------------------------ */ 5311 static decNumber *decExpOp(decNumber *res, const decNumber *rhs, 5312 decContext *set, uInt *status) { 5313 uInt ignore=0; /* working status */ 5314 Int h; /* adjusted exponent for 0.xxxx */ 5315 Int p; /* working precision */ 5316 Int residue; /* rounding residue */ 5317 uInt needbytes; /* for space calculations */ 5318 const decNumber *x=rhs; /* (may point to safe copy later) */ 5319 decContext aset, tset, dset; /* working contexts */ 5320 Int comp; /* work */ 5321 5322 /* the argument is often copied to normalize it, so (unusually) it */ 5323 /* is treated like other buffers, using DECBUFFER, +1 in case */ 5324 /* DECBUFFER is 0 */ 5325 decNumber bufr[D2N(DECBUFFER*2+1)]; 5326 decNumber *allocrhs=NULL; /* non-NULL if rhs buffer allocated */ 5327 5328 /* the working precision will be no more than set->digits+8+1 */ 5329 /* so for on-stack buffers DECBUFFER+9 is used, +1 in case DECBUFFER */ 5330 /* is 0 (and twice that for the accumulator) */ 5331 5332 /* buffer for t, term (working precision plus) */ 5333 decNumber buft[D2N(DECBUFFER*2+9+1)]; 5334 decNumber *allocbuft=NULL; /* -> allocated buft, iff allocated */ 5335 decNumber *t=buft; /* term */ 5336 /* buffer for a, accumulator (working precision * 2), at least 9 */ 5337 decNumber bufa[D2N(DECBUFFER*4+18+1)]; 5338 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */ 5339 decNumber *a=bufa; /* accumulator */ 5340 /* decNumber for the divisor term; this needs at most 9 digits */ 5341 /* and so can be fixed size [16 so can use standard context] */ 5342 decNumber bufd[D2N(16)]; 5343 decNumber *d=bufd; /* divisor */ 5344 decNumber numone; /* constant 1 */ 5345 5346 #if DECCHECK 5347 Int iterations=0; /* for later sanity check */ 5348 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; 5349 #endif 5350 5351 do { /* protect allocated storage */ 5352 if (SPECIALARG) { /* handle infinities and NaNs */ 5353 if (decNumberIsInfinite(rhs)) { /* an infinity */ 5354 if (decNumberIsNegative(rhs)) /* -Infinity -> +0 */ 5355 decNumberZero(res); 5356 else decNumberCopy(res, rhs); /* +Infinity -> self */ 5357 } 5358 else decNaNs(res, rhs, NULL, set, status); /* a NaN */ 5359 break;} 5360 5361 if (ISZERO(rhs)) { /* zeros -> exact 1 */ 5362 decNumberZero(res); /* make clean 1 */ 5363 *res->lsu=1; /* .. */ 5364 break;} /* [no status to set] */ 5365 5366 /* e**x when 0 < x < 0.66 is < 1+3x/2, hence can fast-path */ 5367 /* positive and negative tiny cases which will result in inexact */ 5368 /* 1. This also allows the later add-accumulate to always be */ 5369 /* exact (because its length will never be more than twice the */ 5370 /* working precision). */ 5371 /* The comparator (tiny) needs just one digit, so use the */ 5372 /* decNumber d for it (reused as the divisor, etc., below); its */ 5373 /* exponent is such that if x is positive it will have */ 5374 /* set->digits-1 zeros between the decimal point and the digit, */ 5375 /* which is 4, and if x is negative one more zero there as the */ 5376 /* more precise result will be of the form 0.9999999 rather than */ 5377 /* 1.0000001. Hence, tiny will be 0.0000004 if digits=7 and x>0 */ 5378 /* or 0.00000004 if digits=7 and x<0. If RHS not larger than */ 5379 /* this then the result will be 1.000000 */ 5380 decNumberZero(d); /* clean */ 5381 *d->lsu=4; /* set 4 .. */ 5382 d->exponent=-set->digits; /* * 10**(-d) */ 5383 if (decNumberIsNegative(rhs)) d->exponent--; /* negative case */ 5384 comp=decCompare(d, rhs, 1); /* signless compare */ 5385 if (comp==BADINT) { 5386 *status|=DEC_Insufficient_storage; 5387 break;} 5388 if (comp>=0) { /* rhs < d */ 5389 Int shift=set->digits-1; 5390 decNumberZero(res); /* set 1 */ 5391 *res->lsu=1; /* .. */ 5392 res->digits=decShiftToMost(res->lsu, 1, shift); 5393 res->exponent=-shift; /* make 1.0000... */ 5394 *status|=DEC_Inexact | DEC_Rounded; /* .. inexactly */ 5395 break;} /* tiny */ 5396 5397 /* set up the context to be used for calculating a, as this is */ 5398 /* used on both paths below */ 5399 decContextDefault(&aset, DEC_INIT_DECIMAL64); 5400 /* accumulator bounds are as requested (could underflow) */ 5401 aset.emax=set->emax; /* usual bounds */ 5402 aset.emin=set->emin; /* .. */ 5403 aset.clamp=0; /* and no concrete format */ 5404 5405 /* calculate the adjusted (Hull & Abrham) exponent (where the */ 5406 /* decimal point is just to the left of the coefficient msd) */ 5407 h=rhs->exponent+rhs->digits; 5408 /* if h>8 then 10**h cannot be calculated safely; however, when */ 5409 /* h=8 then exp(|rhs|) will be at least exp(1E+7) which is at */ 5410 /* least 6.59E+4342944, so (due to the restriction on Emax/Emin) */ 5411 /* overflow (or underflow to 0) is guaranteed -- so this case can */ 5412 /* be handled by simply forcing the appropriate excess */ 5413 if (h>8) { /* overflow/underflow */ 5414 /* set up here so Power call below will over or underflow to */ 5415 /* zero; set accumulator to either 2 or 0.02 */ 5416 /* [stack buffer for a is always big enough for this] */ 5417 decNumberZero(a); 5418 *a->lsu=2; /* not 1 but < exp(1) */ 5419 if (decNumberIsNegative(rhs)) a->exponent=-2; /* make 0.02 */ 5420 h=8; /* clamp so 10**h computable */ 5421 p=9; /* set a working precision */ 5422 } 5423 else { /* h<=8 */ 5424 Int maxlever=(rhs->digits>8?1:0); 5425 /* [could/should increase this for precisions >40 or so, too] */ 5426 5427 /* if h is 8, cannot normalize to a lower upper limit because */ 5428 /* the final result will not be computable (see notes above), */ 5429 /* but leverage can be applied whenever h is less than 8. */ 5430 /* Apply as much as possible, up to a MAXLEVER digits, which */ 5431 /* sets the tradeoff against the cost of the later a**(10**h). */ 5432 /* As h is increased, the working precision below also */ 5433 /* increases to compensate for the "constant digits at the */ 5434 /* front" effect. */ 5435 Int lever=MINI(8-h, maxlever); /* leverage attainable */ 5436 Int use=-rhs->digits-lever; /* exponent to use for RHS */ 5437 h+=lever; /* apply leverage selected */ 5438 if (h<0) { /* clamp */ 5439 use+=h; /* [may end up subnormal] */ 5440 h=0; 5441 } 5442 /* Take a copy of RHS if it needs normalization (true whenever x>=1) */ 5443 if (rhs->exponent!=use) { 5444 decNumber *newrhs=bufr; /* assume will fit on stack */ 5445 needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit); 5446 if (needbytes>sizeof(bufr)) { /* need malloc space */ 5447 allocrhs=(decNumber *)malloc(needbytes); 5448 if (allocrhs==NULL) { /* hopeless -- abandon */ 5449 *status|=DEC_Insufficient_storage; 5450 break;} 5451 newrhs=allocrhs; /* use the allocated space */ 5452 } 5453 decNumberCopy(newrhs, rhs); /* copy to safe space */ 5454 newrhs->exponent=use; /* normalize; now <1 */ 5455 x=newrhs; /* ready for use */ 5456 /* decNumberShow(x); */ 5457 } 5458 5459 /* Now use the usual power series to evaluate exp(x). The */ 5460 /* series starts as 1 + x + x^2/2 ... so prime ready for the */ 5461 /* third term by setting the term variable t=x, the accumulator */ 5462 /* a=1, and the divisor d=2. */ 5463 5464 /* First determine the working precision. From Hull & Abrham */ 5465 /* this is set->digits+h+2. However, if x is 'over-precise' we */ 5466 /* need to allow for all its digits to potentially participate */ 5467 /* (consider an x where all the excess digits are 9s) so in */ 5468 /* this case use x->digits+h+2 */ 5469 p=MAXI(x->digits, set->digits)+h+2; /* [h<=8] */ 5470 5471 /* a and t are variable precision, and depend on p, so space */ 5472 /* must be allocated for them if necessary */ 5473 5474 /* the accumulator needs to be able to hold 2p digits so that */ 5475 /* the additions on the second and subsequent iterations are */ 5476 /* sufficiently exact. */ 5477 needbytes=sizeof(decNumber)+(D2U(p*2)-1)*sizeof(Unit); 5478 if (needbytes>sizeof(bufa)) { /* need malloc space */ 5479 allocbufa=(decNumber *)malloc(needbytes); 5480 if (allocbufa==NULL) { /* hopeless -- abandon */ 5481 *status|=DEC_Insufficient_storage; 5482 break;} 5483 a=allocbufa; /* use the allocated space */ 5484 } 5485 /* the term needs to be able to hold p digits (which is */ 5486 /* guaranteed to be larger than x->digits, so the initial copy */ 5487 /* is safe); it may also be used for the raise-to-power */ 5488 /* calculation below, which needs an extra two digits */ 5489 needbytes=sizeof(decNumber)+(D2U(p+2)-1)*sizeof(Unit); 5490 if (needbytes>sizeof(buft)) { /* need malloc space */ 5491 allocbuft=(decNumber *)malloc(needbytes); 5492 if (allocbuft==NULL) { /* hopeless -- abandon */ 5493 *status|=DEC_Insufficient_storage; 5494 break;} 5495 t=allocbuft; /* use the allocated space */ 5496 } 5497 5498 decNumberCopy(t, x); /* term=x */ 5499 decNumberZero(a); *a->lsu=1; /* accumulator=1 */ 5500 decNumberZero(d); *d->lsu=2; /* divisor=2 */ 5501 decNumberZero(&numone); *numone.lsu=1; /* constant 1 for increment */ 5502 5503 /* set up the contexts for calculating a, t, and d */ 5504 decContextDefault(&tset, DEC_INIT_DECIMAL64); 5505 dset=tset; 5506 /* accumulator bounds are set above, set precision now */ 5507 aset.digits=p*2; /* double */ 5508 /* term bounds avoid any underflow or overflow */ 5509 tset.digits=p; 5510 tset.emin=DEC_MIN_EMIN; /* [emax is plenty] */ 5511 /* [dset.digits=16, etc., are sufficient] */ 5512 5513 /* finally ready to roll */ 5514 for (;;) { 5515 #if DECCHECK 5516 iterations++; 5517 #endif 5518 /* only the status from the accumulation is interesting */ 5519 /* [but it should remain unchanged after first add] */ 5520 decAddOp(a, a, t, &aset, 0, status); /* a=a+t */ 5521 decMultiplyOp(t, t, x, &tset, &ignore); /* t=t*x */ 5522 decDivideOp(t, t, d, &tset, DIVIDE, &ignore); /* t=t/d */ 5523 /* the iteration ends when the term cannot affect the result, */ 5524 /* if rounded to p digits, which is when its value is smaller */ 5525 /* than the accumulator by p+1 digits. There must also be */ 5526 /* full precision in a. */ 5527 if (((a->digits+a->exponent)>=(t->digits+t->exponent+p+1)) 5528 && (a->digits>=p)) break; 5529 decAddOp(d, d, &numone, &dset, 0, &ignore); /* d=d+1 */ 5530 } /* iterate */ 5531 5532 #if DECCHECK 5533 /* just a sanity check; comment out test to show always */ 5534 if (iterations>p+3) 5535 printf("Exp iterations=%ld, status=%08lx, p=%ld, d=%ld\n", 5536 iterations, *status, p, x->digits); 5537 #endif 5538 } /* h<=8 */ 5539 5540 /* apply postconditioning: a=a**(10**h) -- this is calculated */ 5541 /* at a slightly higher precision than Hull & Abrham suggest */ 5542 if (h>0) { 5543 Int seenbit=0; /* set once a 1-bit is seen */ 5544 Int i; /* counter */ 5545 Int n=powers[h]; /* always positive */ 5546 aset.digits=p+2; /* sufficient precision */ 5547 /* avoid the overhead and many extra digits of decNumberPower */ 5548 /* as all that is needed is the short 'multipliers' loop; here */ 5549 /* accumulate the answer into t */ 5550 decNumberZero(t); *t->lsu=1; /* acc=1 */ 5551 for (i=1;;i++){ /* for each bit [top bit ignored] */ 5552 /* abandon if have had overflow or terminal underflow */ 5553 if (*status & (DEC_Overflow|DEC_Underflow)) { /* interesting? */ 5554 if (*status&DEC_Overflow || ISZERO(t)) break;} 5555 n=n<<1; /* move next bit to testable position */ 5556 if (n<0) { /* top bit is set */ 5557 seenbit=1; /* OK, have a significant bit */ 5558 decMultiplyOp(t, t, a, &aset, status); /* acc=acc*x */ 5559 } 5560 if (i==31) break; /* that was the last bit */ 5561 if (!seenbit) continue; /* no need to square 1 */ 5562 decMultiplyOp(t, t, t, &aset, status); /* acc=acc*acc [square] */ 5563 } /*i*/ /* 32 bits */ 5564 /* decNumberShow(t); */ 5565 a=t; /* and carry on using t instead of a */ 5566 } 5567 5568 /* Copy and round the result to res */ 5569 residue=1; /* indicate dirt to right .. */ 5570 if (ISZERO(a)) residue=0; /* .. unless underflowed to 0 */ 5571 aset.digits=set->digits; /* [use default rounding] */ 5572 decCopyFit(res, a, &aset, &residue, status); /* copy & shorten */ 5573 decFinish(res, set, &residue, status); /* cleanup/set flags */ 5574 } while(0); /* end protected */ 5575 5576 if (allocrhs !=NULL) free(allocrhs); /* drop any storage used */ 5577 if (allocbufa!=NULL) free(allocbufa); /* .. */ 5578 if (allocbuft!=NULL) free(allocbuft); /* .. */ 5579 /* [status is handled by caller] */ 5580 return res; 5581 } /* decExpOp */ 5582 5583 /* ------------------------------------------------------------------ */ 5584 /* Initial-estimate natural logarithm table */ 5585 /* */ 5586 /* LNnn -- 90-entry 16-bit table for values from .10 through .99. */ 5587 /* The result is a 4-digit encode of the coefficient (c=the */ 5588 /* top 14 bits encoding 0-9999) and a 2-digit encode of the */ 5589 /* exponent (e=the bottom 2 bits encoding 0-3) */ 5590 /* */ 5591 /* The resulting value is given by: */ 5592 /* */ 5593 /* v = -c * 10**(-e-3) */ 5594 /* */ 5595 /* where e and c are extracted from entry k = LNnn[x-10] */ 5596 /* where x is truncated (NB) into the range 10 through 99, */ 5597 /* and then c = k>>2 and e = k&3. */ 5598 /* ------------------------------------------------------------------ */ 5599 static const uShort LNnn[90] = { 5600 9016, 8652, 8316, 8008, 7724, 7456, 7208, 5601 6972, 6748, 6540, 6340, 6148, 5968, 5792, 5628, 5464, 5312, 5602 5164, 5020, 4884, 4748, 4620, 4496, 4376, 4256, 4144, 4032, 5603 39233, 38181, 37157, 36157, 35181, 34229, 33297, 32389, 31501, 30629, 5604 29777, 28945, 28129, 27329, 26545, 25777, 25021, 24281, 23553, 22837, 5605 22137, 21445, 20769, 20101, 19445, 18801, 18165, 17541, 16925, 16321, 5606 15721, 15133, 14553, 13985, 13421, 12865, 12317, 11777, 11241, 10717, 5607 10197, 9685, 9177, 8677, 8185, 7697, 7213, 6737, 6269, 5801, 5608 5341, 4889, 4437, 39930, 35534, 31186, 26886, 22630, 18418, 14254, 5609 10130, 6046, 20055}; 5610 5611 /* ------------------------------------------------------------------ */ 5612 /* decLnOp -- effect natural logarithm */ 5613 /* */ 5614 /* This computes C = ln(A) */ 5615 /* */ 5616 /* res is C, the result. C may be A */ 5617 /* rhs is A */ 5618 /* set is the context; note that rounding mode has no effect */ 5619 /* */ 5620 /* C must have space for set->digits digits. */ 5621 /* */ 5622 /* Notable cases: */ 5623 /* A<0 -> Invalid */ 5624 /* A=0 -> -Infinity (Exact) */ 5625 /* A=+Infinity -> +Infinity (Exact) */ 5626 /* A=1 exactly -> 0 (Exact) */ 5627 /* */ 5628 /* Restrictions (as for Exp): */ 5629 /* */ 5630 /* digits, emax, and -emin in the context must be less than */ 5631 /* DEC_MAX_MATH+11 (1000010), and the rhs must be within these */ 5632 /* bounds or a zero. This is an internal routine, so these */ 5633 /* restrictions are contractual and not enforced. */ 5634 /* */ 5635 /* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will */ 5636 /* almost always be correctly rounded, but may be up to 1 ulp in */ 5637 /* error in rare cases. */ 5638 /* ------------------------------------------------------------------ */ 5639 /* The result is calculated using Newton's method, with each */ 5640 /* iteration calculating a' = a + x * exp(-a) - 1. See, for example, */ 5641 /* Epperson 1989. */ 5642 /* */ 5643 /* The iteration ends when the adjustment x*exp(-a)-1 is tiny enough. */ 5644 /* This has to be calculated at the sum of the precision of x and the */ 5645 /* working precision. */ 5646 /* */ 5647 /* Implementation notes: */ 5648 /* */ 5649 /* 1. This is separated out as decLnOp so it can be called from */ 5650 /* other Mathematical functions (e.g., Log 10) with a wider range */ 5651 /* than normal. In particular, it can handle the slightly wider */ 5652 /* (+9+2) range needed by a power function. */ 5653 /* */ 5654 /* 2. The speed of this function is about 10x slower than exp, as */ 5655 /* it typically needs 4-6 iterations for short numbers, and the */ 5656 /* extra precision needed adds a squaring effect, twice. */ 5657 /* */ 5658 /* 3. Fastpaths are included for ln(10) and ln(2), up to length 40, */ 5659 /* as these are common requests. ln(10) is used by log10(x). */ 5660 /* */ 5661 /* 4. An iteration might be saved by widening the LNnn table, and */ 5662 /* would certainly save at least one if it were made ten times */ 5663 /* bigger, too (for truncated fractions 0.100 through 0.999). */ 5664 /* However, for most practical evaluations, at least four or five */ 5665 /* iterations will be needed -- so this would only speed up by */ 5666 /* 20-25% and that probably does not justify increasing the table */ 5667 /* size. */ 5668 /* */ 5669 /* 5. The static buffers are larger than might be expected to allow */ 5670 /* for calls from decNumberPower. */ 5671 /* ------------------------------------------------------------------ */ 5672 static decNumber *decLnOp(decNumber *res, const decNumber *rhs, 5673 decContext *set, uInt *status) { 5674 uInt ignore=0; /* working status accumulator */ 5675 uInt needbytes; /* for space calculations */ 5676 Int residue; /* rounding residue */ 5677 Int r; /* rhs=f*10**r [see below] */ 5678 Int p; /* working precision */ 5679 Int pp; /* precision for iteration */ 5680 Int t; /* work */ 5681 5682 /* buffers for a (accumulator, typically precision+2) and b */ 5683 /* (adjustment calculator, same size) */ 5684 decNumber bufa[D2N(DECBUFFER+12)]; 5685 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */ 5686 decNumber *a=bufa; /* accumulator/work */ 5687 decNumber bufb[D2N(DECBUFFER*2+2)]; 5688 decNumber *allocbufb=NULL; /* -> allocated bufa, iff allocated */ 5689 decNumber *b=bufb; /* adjustment/work */ 5690 5691 decNumber numone; /* constant 1 */ 5692 decNumber cmp; /* work */ 5693 decContext aset, bset; /* working contexts */ 5694 5695 #if DECCHECK 5696 Int iterations=0; /* for later sanity check */ 5697 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; 5698 #endif 5699 5700 do { /* protect allocated storage */ 5701 if (SPECIALARG) { /* handle infinities and NaNs */ 5702 if (decNumberIsInfinite(rhs)) { /* an infinity */ 5703 if (decNumberIsNegative(rhs)) /* -Infinity -> error */ 5704 *status|=DEC_Invalid_operation; 5705 else decNumberCopy(res, rhs); /* +Infinity -> self */ 5706 } 5707 else decNaNs(res, rhs, NULL, set, status); /* a NaN */ 5708 break;} 5709 5710 if (ISZERO(rhs)) { /* +/- zeros -> -Infinity */ 5711 decNumberZero(res); /* make clean */ 5712 res->bits=DECINF|DECNEG; /* set - infinity */ 5713 break;} /* [no status to set] */ 5714 5715 /* Non-zero negatives are bad... */ 5716 if (decNumberIsNegative(rhs)) { /* -x -> error */ 5717 *status|=DEC_Invalid_operation; 5718 break;} 5719 5720 /* Here, rhs is positive, finite, and in range */ 5721 5722 /* lookaside fastpath code for ln(2) and ln(10) at common lengths */ 5723 if (rhs->exponent==0 && set->digits<=40) { 5724 #if DECDPUN==1 5725 if (rhs->lsu[0]==0 && rhs->lsu[1]==1 && rhs->digits==2) { /* ln(10) */ 5726 #else 5727 if (rhs->lsu[0]==10 && rhs->digits==2) { /* ln(10) */ 5728 #endif 5729 aset=*set; aset.round=DEC_ROUND_HALF_EVEN; 5730 #define LN10 "2.302585092994045684017991454684364207601" 5731 decNumberFromString(res, LN10, &aset); 5732 *status|=(DEC_Inexact | DEC_Rounded); /* is inexact */ 5733 break;} 5734 if (rhs->lsu[0]==2 && rhs->digits==1) { /* ln(2) */ 5735 aset=*set; aset.round=DEC_ROUND_HALF_EVEN; 5736 #define LN2 "0.6931471805599453094172321214581765680755" 5737 decNumberFromString(res, LN2, &aset); 5738 *status|=(DEC_Inexact | DEC_Rounded); 5739 break;} 5740 } /* integer and short */ 5741 5742 /* Determine the working precision. This is normally the */ 5743 /* requested precision + 2, with a minimum of 9. However, if */ 5744 /* the rhs is 'over-precise' then allow for all its digits to */ 5745 /* potentially participate (consider an rhs where all the excess */ 5746 /* digits are 9s) so in this case use rhs->digits+2. */ 5747 p=MAXI(rhs->digits, MAXI(set->digits, 7))+2; 5748 5749 /* Allocate space for the accumulator and the high-precision */ 5750 /* adjustment calculator, if necessary. The accumulator must */ 5751 /* be able to hold p digits, and the adjustment up to */ 5752 /* rhs->digits+p digits. They are also made big enough for 16 */ 5753 /* digits so that they can be used for calculating the initial */ 5754 /* estimate. */ 5755 needbytes=sizeof(decNumber)+(D2U(MAXI(p,16))-1)*sizeof(Unit); 5756 if (needbytes>sizeof(bufa)) { /* need malloc space */ 5757 allocbufa=(decNumber *)malloc(needbytes); 5758 if (allocbufa==NULL) { /* hopeless -- abandon */ 5759 *status|=DEC_Insufficient_storage; 5760 break;} 5761 a=allocbufa; /* use the allocated space */ 5762 } 5763 pp=p+rhs->digits; 5764 needbytes=sizeof(decNumber)+(D2U(MAXI(pp,16))-1)*sizeof(Unit); 5765 if (needbytes>sizeof(bufb)) { /* need malloc space */ 5766 allocbufb=(decNumber *)malloc(needbytes); 5767 if (allocbufb==NULL) { /* hopeless -- abandon */ 5768 *status|=DEC_Insufficient_storage; 5769 break;} 5770 b=allocbufb; /* use the allocated space */ 5771 } 5772 5773 /* Prepare an initial estimate in acc. Calculate this by */ 5774 /* considering the coefficient of x to be a normalized fraction, */ 5775 /* f, with the decimal point at far left and multiplied by */ 5776 /* 10**r. Then, rhs=f*10**r and 0.1<=f<1, and */ 5777 /* ln(x) = ln(f) + ln(10)*r */ 5778 /* Get the initial estimate for ln(f) from a small lookup */ 5779 /* table (see above) indexed by the first two digits of f, */ 5780 /* truncated. */ 5781 5782 decContextDefault(&aset, DEC_INIT_DECIMAL64); /* 16-digit extended */ 5783 r=rhs->exponent+rhs->digits; /* 'normalised' exponent */ 5784 decNumberFromInt32(a, r); /* a=r */ 5785 decNumberFromInt32(b, 2302585); /* b=ln(10) (2.302585) */ 5786 b->exponent=-6; /* .. */ 5787 decMultiplyOp(a, a, b, &aset, &ignore); /* a=a*b */ 5788 /* now get top two digits of rhs into b by simple truncate and */ 5789 /* force to integer */ 5790 residue=0; /* (no residue) */ 5791 aset.digits=2; aset.round=DEC_ROUND_DOWN; 5792 decCopyFit(b, rhs, &aset, &residue, &ignore); /* copy & shorten */ 5793 b->exponent=0; /* make integer */ 5794 t=decGetInt(b); /* [cannot fail] */ 5795 if (t<10) t=X10(t); /* adjust single-digit b */ 5796 t=LNnn[t-10]; /* look up ln(b) */ 5797 decNumberFromInt32(b, t>>2); /* b=ln(b) coefficient */ 5798 b->exponent=-(t&3)-3; /* set exponent */ 5799 b->bits=DECNEG; /* ln(0.10)->ln(0.99) always -ve */ 5800 aset.digits=16; aset.round=DEC_ROUND_HALF_EVEN; /* restore */ 5801 decAddOp(a, a, b, &aset, 0, &ignore); /* acc=a+b */ 5802 /* the initial estimate is now in a, with up to 4 digits correct. */ 5803 /* When rhs is at or near Nmax the estimate will be low, so we */ 5804 /* will approach it from below, avoiding overflow when calling exp. */ 5805 5806 decNumberZero(&numone); *numone.lsu=1; /* constant 1 for adjustment */ 5807 5808 /* accumulator bounds are as requested (could underflow, but */ 5809 /* cannot overflow) */ 5810 aset.emax=set->emax; 5811 aset.emin=set->emin; 5812 aset.clamp=0; /* no concrete format */ 5813 /* set up a context to be used for the multiply and subtract */ 5814 bset=aset; 5815 bset.emax=DEC_MAX_MATH*2; /* use double bounds for the */ 5816 bset.emin=-DEC_MAX_MATH*2; /* adjustment calculation */ 5817 /* [see decExpOp call below] */ 5818 /* for each iteration double the number of digits to calculate, */ 5819 /* up to a maximum of p */ 5820 pp=9; /* initial precision */ 5821 /* [initially 9 as then the sequence starts 7+2, 16+2, and */ 5822 /* 34+2, which is ideal for standard-sized numbers] */ 5823 aset.digits=pp; /* working context */ 5824 bset.digits=pp+rhs->digits; /* wider context */ 5825 for (;;) { /* iterate */ 5826 #if DECCHECK 5827 iterations++; 5828 if (iterations>24) break; /* consider 9 * 2**24 */ 5829 #endif 5830 /* calculate the adjustment (exp(-a)*x-1) into b. This is a */ 5831 /* catastrophic subtraction but it really is the difference */ 5832 /* from 1 that is of interest. */ 5833 /* Use the internal entry point to Exp as it allows the double */ 5834 /* range for calculating exp(-a) when a is the tiniest subnormal. */ 5835 a->bits^=DECNEG; /* make -a */ 5836 decExpOp(b, a, &bset, &ignore); /* b=exp(-a) */ 5837 a->bits^=DECNEG; /* restore sign of a */ 5838 /* now multiply by rhs and subtract 1, at the wider precision */ 5839 decMultiplyOp(b, b, rhs, &bset, &ignore); /* b=b*rhs */ 5840 decAddOp(b, b, &numone, &bset, DECNEG, &ignore); /* b=b-1 */ 5841 5842 /* the iteration ends when the adjustment cannot affect the */ 5843 /* result by >=0.5 ulp (at the requested digits), which */ 5844 /* is when its value is smaller than the accumulator by */ 5845 /* set->digits+1 digits (or it is zero) -- this is a looser */ 5846 /* requirement than for Exp because all that happens to the */ 5847 /* accumulator after this is the final rounding (but note that */ 5848 /* there must also be full precision in a, or a=0). */ 5849 5850 if (decNumberIsZero(b) || 5851 (a->digits+a->exponent)>=(b->digits+b->exponent+set->digits+1)) { 5852 if (a->digits==p) break; 5853 if (decNumberIsZero(a)) { 5854 decCompareOp(&cmp, rhs, &numone, &aset, COMPARE, &ignore); /* rhs=1 ? */ 5855 if (cmp.lsu[0]==0) a->exponent=0; /* yes, exact 0 */ 5856 else *status|=(DEC_Inexact | DEC_Rounded); /* no, inexact */ 5857 break; 5858 } 5859 /* force padding if adjustment has gone to 0 before full length */ 5860 if (decNumberIsZero(b)) b->exponent=a->exponent-p; 5861 } 5862 5863 /* not done yet ... */ 5864 decAddOp(a, a, b, &aset, 0, &ignore); /* a=a+b for next estimate */ 5865 if (pp==p) continue; /* precision is at maximum */ 5866 /* lengthen the next calculation */ 5867 pp=pp*2; /* double precision */ 5868 if (pp>p) pp=p; /* clamp to maximum */ 5869 aset.digits=pp; /* working context */ 5870 bset.digits=pp+rhs->digits; /* wider context */ 5871 } /* Newton's iteration */ 5872 5873 #if DECCHECK 5874 /* just a sanity check; remove the test to show always */ 5875 if (iterations>24) 5876 printf("Ln iterations=%ld, status=%08lx, p=%ld, d=%ld\n", 5877 iterations, *status, p, rhs->digits); 5878 #endif 5879 5880 /* Copy and round the result to res */ 5881 residue=1; /* indicate dirt to right */ 5882 if (ISZERO(a)) residue=0; /* .. unless underflowed to 0 */ 5883 aset.digits=set->digits; /* [use default rounding] */ 5884 decCopyFit(res, a, &aset, &residue, status); /* copy & shorten */ 5885 decFinish(res, set, &residue, status); /* cleanup/set flags */ 5886 } while(0); /* end protected */ 5887 5888 if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */ 5889 if (allocbufb!=NULL) free(allocbufb); /* .. */ 5890 /* [status is handled by caller] */ 5891 return res; 5892 } /* decLnOp */ 5893 5894 /* ------------------------------------------------------------------ */ 5895 /* decQuantizeOp -- force exponent to requested value */ 5896 /* */ 5897 /* This computes C = op(A, B), where op adjusts the coefficient */ 5898 /* of C (by rounding or shifting) such that the exponent (-scale) */ 5899 /* of C has the value B or matches the exponent of B. */ 5900 /* The numerical value of C will equal A, except for the effects of */ 5901 /* any rounding that occurred. */ 5902 /* */ 5903 /* res is C, the result. C may be A or B */ 5904 /* lhs is A, the number to adjust */ 5905 /* rhs is B, the requested exponent */ 5906 /* set is the context */ 5907 /* quant is 1 for quantize or 0 for rescale */ 5908 /* status is the status accumulator (this can be called without */ 5909 /* risk of control loss) */ 5910 /* */ 5911 /* C must have space for set->digits digits. */ 5912 /* */ 5913 /* Unless there is an error or the result is infinite, the exponent */ 5914 /* after the operation is guaranteed to be that requested. */ 5915 /* ------------------------------------------------------------------ */ 5916 static decNumber * decQuantizeOp(decNumber *res, const decNumber *lhs, 5917 const decNumber *rhs, decContext *set, 5918 Flag quant, uInt *status) { 5919 #if DECSUBSET 5920 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */ 5921 decNumber *allocrhs=NULL; /* .., rhs */ 5922 #endif 5923 const decNumber *inrhs=rhs; /* save original rhs */ 5924 Int reqdigits=set->digits; /* requested DIGITS */ 5925 Int reqexp; /* requested exponent [-scale] */ 5926 Int residue=0; /* rounding residue */ 5927 Int etiny=set->emin-(reqdigits-1); 5928 5929 #if DECCHECK 5930 if (decCheckOperands(res, lhs, rhs, set)) return res; 5931 #endif 5932 5933 do { /* protect allocated storage */ 5934 #if DECSUBSET 5935 if (!set->extended) { 5936 /* reduce operands and set lostDigits status, as needed */ 5937 if (lhs->digits>reqdigits) { 5938 alloclhs=decRoundOperand(lhs, set, status); 5939 if (alloclhs==NULL) break; 5940 lhs=alloclhs; 5941 } 5942 if (rhs->digits>reqdigits) { /* [this only checks lostDigits] */ 5943 allocrhs=decRoundOperand(rhs, set, status); 5944 if (allocrhs==NULL) break; 5945 rhs=allocrhs; 5946 } 5947 } 5948 #endif 5949 /* [following code does not require input rounding] */ 5950 5951 /* Handle special values */ 5952 if (SPECIALARGS) { 5953 /* NaNs get usual processing */ 5954 if (SPECIALARGS & (DECSNAN | DECNAN)) 5955 decNaNs(res, lhs, rhs, set, status); 5956 /* one infinity but not both is bad */ 5957 else if ((lhs->bits ^ rhs->bits) & DECINF) 5958 *status|=DEC_Invalid_operation; 5959 /* both infinity: return lhs */ 5960 else decNumberCopy(res, lhs); /* [nop if in place] */ 5961 break; 5962 } 5963 5964 /* set requested exponent */ 5965 if (quant) reqexp=inrhs->exponent; /* quantize -- match exponents */ 5966 else { /* rescale -- use value of rhs */ 5967 /* Original rhs must be an integer that fits and is in range, */ 5968 /* which could be from -1999999997 to +999999999, thanks to */ 5969 /* subnormals */ 5970 reqexp=decGetInt(inrhs); /* [cannot fail] */ 5971 } 5972 5973 #if DECSUBSET 5974 if (!set->extended) etiny=set->emin; /* no subnormals */ 5975 #endif 5976 5977 if (reqexp==BADINT /* bad (rescale only) or .. */ 5978 || reqexp==BIGODD || reqexp==BIGEVEN /* very big (ditto) or .. */ 5979 || (reqexp<etiny) /* < lowest */ 5980 || (reqexp>set->emax)) { /* > emax */ 5981 *status|=DEC_Invalid_operation; 5982 break;} 5983 5984 /* the RHS has been processed, so it can be overwritten now if necessary */ 5985 if (ISZERO(lhs)) { /* zero coefficient unchanged */ 5986 decNumberCopy(res, lhs); /* [nop if in place] */ 5987 res->exponent=reqexp; /* .. just set exponent */ 5988 #if DECSUBSET 5989 if (!set->extended) res->bits=0; /* subset specification; no -0 */ 5990 #endif 5991 } 5992 else { /* non-zero lhs */ 5993 Int adjust=reqexp-lhs->exponent; /* digit adjustment needed */ 5994 /* if adjusted coefficient will definitely not fit, give up now */ 5995 if ((lhs->digits-adjust)>reqdigits) { 5996 *status|=DEC_Invalid_operation; 5997 break; 5998 } 5999 6000 if (adjust>0) { /* increasing exponent */ 6001 /* this will decrease the length of the coefficient by adjust */ 6002 /* digits, and must round as it does so */ 6003 decContext workset; /* work */ 6004 workset=*set; /* clone rounding, etc. */ 6005 workset.digits=lhs->digits-adjust; /* set requested length */ 6006 /* [note that the latter can be <1, here] */ 6007 decCopyFit(res, lhs, &workset, &residue, status); /* fit to result */ 6008 decApplyRound(res, &workset, residue, status); /* .. and round */ 6009 residue=0; /* [used] */ 6010 /* If just rounded a 999s case, exponent will be off by one; */ 6011 /* adjust back (after checking space), if so. */ 6012 if (res->exponent>reqexp) { 6013 /* re-check needed, e.g., for quantize(0.9999, 0.001) under */ 6014 /* set->digits==3 */ 6015 if (res->digits==reqdigits) { /* cannot shift by 1 */ 6016 *status&=~(DEC_Inexact | DEC_Rounded); /* [clean these] */ 6017 *status|=DEC_Invalid_operation; 6018 break; 6019 } 6020 res->digits=decShiftToMost(res->lsu, res->digits, 1); /* shift */ 6021 res->exponent--; /* (re)adjust the exponent. */ 6022 } 6023 #if DECSUBSET 6024 if (ISZERO(res) && !set->extended) res->bits=0; /* subset; no -0 */ 6025 #endif 6026 } /* increase */ 6027 else /* adjust<=0 */ { /* decreasing or = exponent */ 6028 /* this will increase the length of the coefficient by -adjust */ 6029 /* digits, by adding zero or more trailing zeros; this is */ 6030 /* already checked for fit, above */ 6031 decNumberCopy(res, lhs); /* [it will fit] */ 6032 /* if padding needed (adjust<0), add it now... */ 6033 if (adjust<0) { 6034 res->digits=decShiftToMost(res->lsu, res->digits, -adjust); 6035 res->exponent+=adjust; /* adjust the exponent */ 6036 } 6037 } /* decrease */ 6038 } /* non-zero */ 6039 6040 /* Check for overflow [do not use Finalize in this case, as an */ 6041 /* overflow here is a "don't fit" situation] */ 6042 if (res->exponent>set->emax-res->digits+1) { /* too big */ 6043 *status|=DEC_Invalid_operation; 6044 break; 6045 } 6046 else { 6047 decFinalize(res, set, &residue, status); /* set subnormal flags */ 6048 *status&=~DEC_Underflow; /* suppress Underflow [754r] */ 6049 } 6050 } while(0); /* end protected */ 6051 6052 #if DECSUBSET 6053 if (allocrhs!=NULL) free(allocrhs); /* drop any storage used */ 6054 if (alloclhs!=NULL) free(alloclhs); /* .. */ 6055 #endif 6056 return res; 6057 } /* decQuantizeOp */ 6058 6059 /* ------------------------------------------------------------------ */ 6060 /* decCompareOp -- compare, min, or max two Numbers */ 6061 /* */ 6062 /* This computes C = A ? B and carries out one of four operations: */ 6063 /* COMPARE -- returns the signum (as a number) giving the */ 6064 /* result of a comparison unless one or both */ 6065 /* operands is a NaN (in which case a NaN results) */ 6066 /* COMPSIG -- as COMPARE except that a quiet NaN raises */ 6067 /* Invalid operation. */ 6068 /* COMPMAX -- returns the larger of the operands, using the */ 6069 /* 754r maxnum operation */ 6070 /* COMPMAXMAG -- ditto, comparing absolute values */ 6071 /* COMPMIN -- the 754r minnum operation */ 6072 /* COMPMINMAG -- ditto, comparing absolute values */ 6073 /* COMTOTAL -- returns the signum (as a number) giving the */ 6074 /* result of a comparison using 754r total ordering */ 6075 /* */ 6076 /* res is C, the result. C may be A and/or B (e.g., X=X?X) */ 6077 /* lhs is A */ 6078 /* rhs is B */ 6079 /* set is the context */ 6080 /* op is the operation flag */ 6081 /* status is the usual accumulator */ 6082 /* */ 6083 /* C must have space for one digit for COMPARE or set->digits for */ 6084 /* COMPMAX, COMPMIN, COMPMAXMAG, or COMPMINMAG. */ 6085 /* ------------------------------------------------------------------ */ 6086 /* The emphasis here is on speed for common cases, and avoiding */ 6087 /* coefficient comparison if possible. */ 6088 /* ------------------------------------------------------------------ */ 6089 static decNumber *decCompareOp(decNumber *res, const decNumber *lhs, 6090 const decNumber *rhs, decContext *set, 6091 Flag op, uInt *status) { 6092 #if DECSUBSET 6093 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */ 6094 decNumber *allocrhs=NULL; /* .., rhs */ 6095 #endif 6096 Int result=0; /* default result value */ 6097 uByte merged; /* work */ 6098 6099 #if DECCHECK 6100 if (decCheckOperands(res, lhs, rhs, set)) return res; 6101 #endif 6102 6103 do { /* protect allocated storage */ 6104 #if DECSUBSET 6105 if (!set->extended) { 6106 /* reduce operands and set lostDigits status, as needed */ 6107 if (lhs->digits>set->digits) { 6108 alloclhs=decRoundOperand(lhs, set, status); 6109 if (alloclhs==NULL) {result=BADINT; break;} 6110 lhs=alloclhs; 6111 } 6112 if (rhs->digits>set->digits) { 6113 allocrhs=decRoundOperand(rhs, set, status); 6114 if (allocrhs==NULL) {result=BADINT; break;} 6115 rhs=allocrhs; 6116 } 6117 } 6118 #endif 6119 /* [following code does not require input rounding] */ 6120 6121 /* If total ordering then handle differing signs 'up front' */ 6122 if (op==COMPTOTAL) { /* total ordering */ 6123 if (decNumberIsNegative(lhs) && !decNumberIsNegative(rhs)) { 6124 result=-1; 6125 break; 6126 } 6127 if (!decNumberIsNegative(lhs) && decNumberIsNegative(rhs)) { 6128 result=+1; 6129 break; 6130 } 6131 } 6132 6133 /* handle NaNs specially; let infinities drop through */ 6134 /* This assumes sNaN (even just one) leads to NaN. */ 6135 merged=(lhs->bits | rhs->bits) & (DECSNAN | DECNAN); 6136 if (merged) { /* a NaN bit set */ 6137 if (op==COMPARE); /* result will be NaN */ 6138 else if (op==COMPSIG) /* treat qNaN as sNaN */ 6139 *status|=DEC_Invalid_operation | DEC_sNaN; 6140 else if (op==COMPTOTAL) { /* total ordering, always finite */ 6141 /* signs are known to be the same; compute the ordering here */ 6142 /* as if the signs are both positive, then invert for negatives */ 6143 if (!decNumberIsNaN(lhs)) result=-1; 6144 else if (!decNumberIsNaN(rhs)) result=+1; 6145 /* here if both NaNs */ 6146 else if (decNumberIsSNaN(lhs) && decNumberIsQNaN(rhs)) result=-1; 6147 else if (decNumberIsQNaN(lhs) && decNumberIsSNaN(rhs)) result=+1; 6148 else { /* both NaN or both sNaN */ 6149 /* now it just depends on the payload */ 6150 result=decUnitCompare(lhs->lsu, D2U(lhs->digits), 6151 rhs->lsu, D2U(rhs->digits), 0); 6152 /* [Error not possible, as these are 'aligned'] */ 6153 } /* both same NaNs */ 6154 if (decNumberIsNegative(lhs)) result=-result; 6155 break; 6156 } /* total order */ 6157 6158 else if (merged & DECSNAN); /* sNaN -> qNaN */ 6159 else { /* here if MIN or MAX and one or two quiet NaNs */ 6160 /* min or max -- 754r rules ignore single NaN */ 6161 if (!decNumberIsNaN(lhs) || !decNumberIsNaN(rhs)) { 6162 /* just one NaN; force choice to be the non-NaN operand */ 6163 op=COMPMAX; 6164 if (lhs->bits & DECNAN) result=-1; /* pick rhs */ 6165 else result=+1; /* pick lhs */ 6166 break; 6167 } 6168 } /* max or min */ 6169 op=COMPNAN; /* use special path */ 6170 decNaNs(res, lhs, rhs, set, status); /* propagate NaN */ 6171 break; 6172 } 6173 /* have numbers */ 6174 if (op==COMPMAXMAG || op==COMPMINMAG) result=decCompare(lhs, rhs, 1); 6175 else result=decCompare(lhs, rhs, 0); /* sign matters */ 6176 } while(0); /* end protected */ 6177 6178 if (result==BADINT) *status|=DEC_Insufficient_storage; /* rare */ 6179 else { 6180 if (op==COMPARE || op==COMPSIG ||op==COMPTOTAL) { /* returning signum */ 6181 if (op==COMPTOTAL && result==0) { 6182 /* operands are numerically equal or same NaN (and same sign, */ 6183 /* tested first); if identical, leave result 0 */ 6184 if (lhs->exponent!=rhs->exponent) { 6185 if (lhs->exponent<rhs->exponent) result=-1; 6186 else result=+1; 6187 if (decNumberIsNegative(lhs)) result=-result; 6188 } /* lexp!=rexp */ 6189 } /* total-order by exponent */ 6190 decNumberZero(res); /* [always a valid result] */ 6191 if (result!=0) { /* must be -1 or +1 */ 6192 *res->lsu=1; 6193 if (result<0) res->bits=DECNEG; 6194 } 6195 } 6196 else if (op==COMPNAN); /* special, drop through */ 6197 else { /* MAX or MIN, non-NaN result */ 6198 Int residue=0; /* rounding accumulator */ 6199 /* choose the operand for the result */ 6200 const decNumber *choice; 6201 if (result==0) { /* operands are numerically equal */ 6202 /* choose according to sign then exponent (see 754r) */ 6203 uByte slhs=(lhs->bits & DECNEG); 6204 uByte srhs=(rhs->bits & DECNEG); 6205 #if DECSUBSET 6206 if (!set->extended) { /* subset: force left-hand */ 6207 op=COMPMAX; 6208 result=+1; 6209 } 6210 else 6211 #endif 6212 if (slhs!=srhs) { /* signs differ */ 6213 if (slhs) result=-1; /* rhs is max */ 6214 else result=+1; /* lhs is max */ 6215 } 6216 else if (slhs && srhs) { /* both negative */ 6217 if (lhs->exponent<rhs->exponent) result=+1; 6218 else result=-1; 6219 /* [if equal, use lhs, technically identical] */ 6220 } 6221 else { /* both positive */ 6222 if (lhs->exponent>rhs->exponent) result=+1; 6223 else result=-1; 6224 /* [ditto] */ 6225 } 6226 } /* numerically equal */ 6227 /* here result will be non-0; reverse if looking for MIN */ 6228 if (op==COMPMIN || op==COMPMINMAG) result=-result; 6229 choice=(result>0 ? lhs : rhs); /* choose */ 6230 /* copy chosen to result, rounding if need be */ 6231 decCopyFit(res, choice, set, &residue, status); 6232 decFinish(res, set, &residue, status); 6233 } 6234 } 6235 #if DECSUBSET 6236 if (allocrhs!=NULL) free(allocrhs); /* free any storage used */ 6237 if (alloclhs!=NULL) free(alloclhs); /* .. */ 6238 #endif 6239 return res; 6240 } /* decCompareOp */ 6241 6242 /* ------------------------------------------------------------------ */ 6243 /* decCompare -- compare two decNumbers by numerical value */ 6244 /* */ 6245 /* This routine compares A ? B without altering them. */ 6246 /* */ 6247 /* Arg1 is A, a decNumber which is not a NaN */ 6248 /* Arg2 is B, a decNumber which is not a NaN */ 6249 /* Arg3 is 1 for a sign-independent compare, 0 otherwise */ 6250 /* */ 6251 /* returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure */ 6252 /* (the only possible failure is an allocation error) */ 6253 /* ------------------------------------------------------------------ */ 6254 static Int decCompare(const decNumber *lhs, const decNumber *rhs, 6255 Flag abs) { 6256 Int result; /* result value */ 6257 Int sigr; /* rhs signum */ 6258 Int compare; /* work */ 6259 6260 result=1; /* assume signum(lhs) */ 6261 if (ISZERO(lhs)) result=0; 6262 if (abs) { 6263 if (ISZERO(rhs)) return result; /* LHS wins or both 0 */ 6264 /* RHS is non-zero */ 6265 if (result==0) return -1; /* LHS is 0; RHS wins */ 6266 /* [here, both non-zero, result=1] */ 6267 } 6268 else { /* signs matter */ 6269 if (result && decNumberIsNegative(lhs)) result=-1; 6270 sigr=1; /* compute signum(rhs) */ 6271 if (ISZERO(rhs)) sigr=0; 6272 else if (decNumberIsNegative(rhs)) sigr=-1; 6273 if (result > sigr) return +1; /* L > R, return 1 */ 6274 if (result < sigr) return -1; /* L < R, return -1 */ 6275 if (result==0) return 0; /* both 0 */ 6276 } 6277 6278 /* signums are the same; both are non-zero */ 6279 if ((lhs->bits | rhs->bits) & DECINF) { /* one or more infinities */ 6280 if (decNumberIsInfinite(rhs)) { 6281 if (decNumberIsInfinite(lhs)) result=0;/* both infinite */ 6282 else result=-result; /* only rhs infinite */ 6283 } 6284 return result; 6285 } 6286 /* must compare the coefficients, allowing for exponents */ 6287 if (lhs->exponent>rhs->exponent) { /* LHS exponent larger */ 6288 /* swap sides, and sign */ 6289 const decNumber *temp=lhs; 6290 lhs=rhs; 6291 rhs=temp; 6292 result=-result; 6293 } 6294 compare=decUnitCompare(lhs->lsu, D2U(lhs->digits), 6295 rhs->lsu, D2U(rhs->digits), 6296 rhs->exponent-lhs->exponent); 6297 if (compare!=BADINT) compare*=result; /* comparison succeeded */ 6298 return compare; 6299 } /* decCompare */ 6300 6301 /* ------------------------------------------------------------------ */ 6302 /* decUnitCompare -- compare two >=0 integers in Unit arrays */ 6303 /* */ 6304 /* This routine compares A ? B*10**E where A and B are unit arrays */ 6305 /* A is a plain integer */ 6306 /* B has an exponent of E (which must be non-negative) */ 6307 /* */ 6308 /* Arg1 is A first Unit (lsu) */ 6309 /* Arg2 is A length in Units */ 6310 /* Arg3 is B first Unit (lsu) */ 6311 /* Arg4 is B length in Units */ 6312 /* Arg5 is E (0 if the units are aligned) */ 6313 /* */ 6314 /* returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure */ 6315 /* (the only possible failure is an allocation error, which can */ 6316 /* only occur if E!=0) */ 6317 /* ------------------------------------------------------------------ */ 6318 static Int decUnitCompare(const Unit *a, Int alength, 6319 const Unit *b, Int blength, Int exp) { 6320 Unit *acc; /* accumulator for result */ 6321 Unit accbuff[SD2U(DECBUFFER*2+1)]; /* local buffer */ 6322 Unit *allocacc=NULL; /* -> allocated acc buffer, iff allocated */ 6323 Int accunits, need; /* units in use or needed for acc */ 6324 const Unit *l, *r, *u; /* work */ 6325 Int expunits, exprem, result; /* .. */ 6326 6327 if (exp==0) { /* aligned; fastpath */ 6328 if (alength>blength) return 1; 6329 if (alength<blength) return -1; 6330 /* same number of units in both -- need unit-by-unit compare */ 6331 l=a+alength-1; 6332 r=b+alength-1; 6333 for (;l>=a; l--, r--) { 6334 if (*l>*r) return 1; 6335 if (*l<*r) return -1; 6336 } 6337 return 0; /* all units match */ 6338 } /* aligned */ 6339 6340 /* Unaligned. If one is >1 unit longer than the other, padded */ 6341 /* approximately, then can return easily */ 6342 if (alength>blength+(Int)D2U(exp)) return 1; 6343 if (alength+1<blength+(Int)D2U(exp)) return -1; 6344 6345 /* Need to do a real subtract. For this, a result buffer is needed */ 6346 /* even though only the sign is of interest. Its length needs */ 6347 /* to be the larger of alength and padded blength, +2 */ 6348 need=blength+D2U(exp); /* maximum real length of B */ 6349 if (need<alength) need=alength; 6350 need+=2; 6351 acc=accbuff; /* assume use local buffer */ 6352 if (need*sizeof(Unit)>sizeof(accbuff)) { 6353 allocacc=(Unit *)malloc(need*sizeof(Unit)); 6354 if (allocacc==NULL) return BADINT; /* hopeless -- abandon */ 6355 acc=allocacc; 6356 } 6357 /* Calculate units and remainder from exponent. */ 6358 expunits=exp/DECDPUN; 6359 exprem=exp%DECDPUN; 6360 /* subtract [A+B*(-m)] */ 6361 accunits=decUnitAddSub(a, alength, b, blength, expunits, acc, 6362 -(Int)powers[exprem]); 6363 /* [UnitAddSub result may have leading zeros, even on zero] */ 6364 if (accunits<0) result=-1; /* negative result */ 6365 else { /* non-negative result */ 6366 /* check units of the result before freeing any storage */ 6367 for (u=acc; u<acc+accunits-1 && *u==0;) u++; 6368 result=(*u==0 ? 0 : +1); 6369 } 6370 /* clean up and return the result */ 6371 if (allocacc!=NULL) free(allocacc); /* drop any storage used */ 6372 return result; 6373 } /* decUnitCompare */ 6374 6375 /* ------------------------------------------------------------------ */ 6376 /* decUnitAddSub -- add or subtract two >=0 integers in Unit arrays */ 6377 /* */ 6378 /* This routine performs the calculation: */ 6379 /* */ 6380 /* C=A+(B*M) */ 6381 /* */ 6382 /* Where M is in the range -DECDPUNMAX through +DECDPUNMAX. */ 6383 /* */ 6384 /* A may be shorter or longer than B. */ 6385 /* */ 6386 /* Leading zeros are not removed after a calculation. The result is */ 6387 /* either the same length as the longer of A and B (adding any */ 6388 /* shift), or one Unit longer than that (if a Unit carry occurred). */ 6389 /* */ 6390 /* A and B content are not altered unless C is also A or B. */ 6391 /* C may be the same array as A or B, but only if no zero padding is */ 6392 /* requested (that is, C may be B only if bshift==0). */ 6393 /* C is filled from the lsu; only those units necessary to complete */ 6394 /* the calculation are referenced. */ 6395 /* */ 6396 /* Arg1 is A first Unit (lsu) */ 6397 /* Arg2 is A length in Units */ 6398 /* Arg3 is B first Unit (lsu) */ 6399 /* Arg4 is B length in Units */ 6400 /* Arg5 is B shift in Units (>=0; pads with 0 units if positive) */ 6401 /* Arg6 is C first Unit (lsu) */ 6402 /* Arg7 is M, the multiplier */ 6403 /* */ 6404 /* returns the count of Units written to C, which will be non-zero */ 6405 /* and negated if the result is negative. That is, the sign of the */ 6406 /* returned Int is the sign of the result (positive for zero) and */ 6407 /* the absolute value of the Int is the count of Units. */ 6408 /* */ 6409 /* It is the caller's responsibility to make sure that C size is */ 6410 /* safe, allowing space if necessary for a one-Unit carry. */ 6411 /* */ 6412 /* This routine is severely performance-critical; *any* change here */ 6413 /* must be measured (timed) to assure no performance degradation. */ 6414 /* In particular, trickery here tends to be counter-productive, as */ 6415 /* increased complexity of code hurts register optimizations on */ 6416 /* register-poor architectures. Avoiding divisions is nearly */ 6417 /* always a Good Idea, however. */ 6418 /* */ 6419 /* Special thanks to Rick McGuire (IBM Cambridge, MA) and Dave Clark */ 6420 /* (IBM Warwick, UK) for some of the ideas used in this routine. */ 6421 /* ------------------------------------------------------------------ */ 6422 static Int decUnitAddSub(const Unit *a, Int alength, 6423 const Unit *b, Int blength, Int bshift, 6424 Unit *c, Int m) { 6425 const Unit *alsu=a; /* A lsu [need to remember it] */ 6426 Unit *clsu=c; /* C ditto */ 6427 Unit *minC; /* low water mark for C */ 6428 Unit *maxC; /* high water mark for C */ 6429 eInt carry=0; /* carry integer (could be Long) */ 6430 Int add; /* work */ 6431 #if DECDPUN<=4 /* myriadal, millenary, etc. */ 6432 Int est; /* estimated quotient */ 6433 #endif 6434 6435 #if DECTRACE 6436 if (alength<1 || blength<1) 6437 printf("decUnitAddSub: alen blen m %ld %ld [%ld]\n", alength, blength, m); 6438 #endif 6439 6440 maxC=c+alength; /* A is usually the longer */ 6441 minC=c+blength; /* .. and B the shorter */ 6442 if (bshift!=0) { /* B is shifted; low As copy across */ 6443 minC+=bshift; 6444 /* if in place [common], skip copy unless there's a gap [rare] */ 6445 if (a==c && bshift<=alength) { 6446 c+=bshift; 6447 a+=bshift; 6448 } 6449 else for (; c<clsu+bshift; a++, c++) { /* copy needed */ 6450 if (a<alsu+alength) *c=*a; 6451 else *c=0; 6452 } 6453 } 6454 if (minC>maxC) { /* swap */ 6455 Unit *hold=minC; 6456 minC=maxC; 6457 maxC=hold; 6458 } 6459 6460 /* For speed, do the addition as two loops; the first where both A */ 6461 /* and B contribute, and the second (if necessary) where only one or */ 6462 /* other of the numbers contribute. */ 6463 /* Carry handling is the same (i.e., duplicated) in each case. */ 6464 for (; c<minC; c++) { 6465 carry+=*a; 6466 a++; 6467 carry+=((eInt)*b)*m; /* [special-casing m=1/-1 */ 6468 b++; /* here is not a win] */ 6469 /* here carry is new Unit of digits; it could be +ve or -ve */ 6470 if ((ueInt)carry<=DECDPUNMAX) { /* fastpath 0-DECDPUNMAX */ 6471 *c=(Unit)carry; 6472 carry=0; 6473 continue; 6474 } 6475 #if DECDPUN==4 /* use divide-by-multiply */ 6476 if (carry>=0) { 6477 est=(((ueInt)carry>>11)*53687)>>18; 6478 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */ 6479 carry=est; /* likely quotient [89%] */ 6480 if (*c<DECDPUNMAX+1) continue; /* estimate was correct */ 6481 carry++; 6482 *c-=DECDPUNMAX+1; 6483 continue; 6484 } 6485 /* negative case */ 6486 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */ 6487 est=(((ueInt)carry>>11)*53687)>>18; 6488 *c=(Unit)(carry-est*(DECDPUNMAX+1)); 6489 carry=est-(DECDPUNMAX+1); /* correctly negative */ 6490 if (*c<DECDPUNMAX+1) continue; /* was OK */ 6491 carry++; 6492 *c-=DECDPUNMAX+1; 6493 #elif DECDPUN==3 6494 if (carry>=0) { 6495 est=(((ueInt)carry>>3)*16777)>>21; 6496 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */ 6497 carry=est; /* likely quotient [99%] */ 6498 if (*c<DECDPUNMAX+1) continue; /* estimate was correct */ 6499 carry++; 6500 *c-=DECDPUNMAX+1; 6501 continue; 6502 } 6503 /* negative case */ 6504 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */ 6505 est=(((ueInt)carry>>3)*16777)>>21; 6506 *c=(Unit)(carry-est*(DECDPUNMAX+1)); 6507 carry=est-(DECDPUNMAX+1); /* correctly negative */ 6508 if (*c<DECDPUNMAX+1) continue; /* was OK */ 6509 carry++; 6510 *c-=DECDPUNMAX+1; 6511 #elif DECDPUN<=2 6512 /* Can use QUOT10 as carry <= 4 digits */ 6513 if (carry>=0) { 6514 est=QUOT10(carry, DECDPUN); 6515 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */ 6516 carry=est; /* quotient */ 6517 continue; 6518 } 6519 /* negative case */ 6520 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */ 6521 est=QUOT10(carry, DECDPUN); 6522 *c=(Unit)(carry-est*(DECDPUNMAX+1)); 6523 carry=est-(DECDPUNMAX+1); /* correctly negative */ 6524 #else 6525 /* remainder operator is undefined if negative, so must test */ 6526 if ((ueInt)carry<(DECDPUNMAX+1)*2) { /* fastpath carry +1 */ 6527 *c=(Unit)(carry-(DECDPUNMAX+1)); /* [helps additions] */ 6528 carry=1; 6529 continue; 6530 } 6531 if (carry>=0) { 6532 *c=(Unit)(carry%(DECDPUNMAX+1)); 6533 carry=carry/(DECDPUNMAX+1); 6534 continue; 6535 } 6536 /* negative case */ 6537 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */ 6538 *c=(Unit)(carry%(DECDPUNMAX+1)); 6539 carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1); 6540 #endif 6541 } /* c */ 6542 6543 /* now may have one or other to complete */ 6544 /* [pretest to avoid loop setup/shutdown] */ 6545 if (c<maxC) for (; c<maxC; c++) { 6546 if (a<alsu+alength) { /* still in A */ 6547 carry+=*a; 6548 a++; 6549 } 6550 else { /* inside B */ 6551 carry+=((eInt)*b)*m; 6552 b++; 6553 } 6554 /* here carry is new Unit of digits; it could be +ve or -ve and */ 6555 /* magnitude up to DECDPUNMAX squared */ 6556 if ((ueInt)carry<=DECDPUNMAX) { /* fastpath 0-DECDPUNMAX */ 6557 *c=(Unit)carry; 6558 carry=0; 6559 continue; 6560 } 6561 /* result for this unit is negative or >DECDPUNMAX */ 6562 #if DECDPUN==4 /* use divide-by-multiply */ 6563 if (carry>=0) { 6564 est=(((ueInt)carry>>11)*53687)>>18; 6565 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */ 6566 carry=est; /* likely quotient [79.7%] */ 6567 if (*c<DECDPUNMAX+1) continue; /* estimate was correct */ 6568 carry++; 6569 *c-=DECDPUNMAX+1; 6570 continue; 6571 } 6572 /* negative case */ 6573 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */ 6574 est=(((ueInt)carry>>11)*53687)>>18; 6575 *c=(Unit)(carry-est*(DECDPUNMAX+1)); 6576 carry=est-(DECDPUNMAX+1); /* correctly negative */ 6577 if (*c<DECDPUNMAX+1) continue; /* was OK */ 6578 carry++; 6579 *c-=DECDPUNMAX+1; 6580 #elif DECDPUN==3 6581 if (carry>=0) { 6582 est=(((ueInt)carry>>3)*16777)>>21; 6583 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */ 6584 carry=est; /* likely quotient [99%] */ 6585 if (*c<DECDPUNMAX+1) continue; /* estimate was correct */ 6586 carry++; 6587 *c-=DECDPUNMAX+1; 6588 continue; 6589 } 6590 /* negative case */ 6591 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */ 6592 est=(((ueInt)carry>>3)*16777)>>21; 6593 *c=(Unit)(carry-est*(DECDPUNMAX+1)); 6594 carry=est-(DECDPUNMAX+1); /* correctly negative */ 6595 if (*c<DECDPUNMAX+1) continue; /* was OK */ 6596 carry++; 6597 *c-=DECDPUNMAX+1; 6598 #elif DECDPUN<=2 6599 if (carry>=0) { 6600 est=QUOT10(carry, DECDPUN); 6601 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */ 6602 carry=est; /* quotient */ 6603 continue; 6604 } 6605 /* negative case */ 6606 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */ 6607 est=QUOT10(carry, DECDPUN); 6608 *c=(Unit)(carry-est*(DECDPUNMAX+1)); 6609 carry=est-(DECDPUNMAX+1); /* correctly negative */ 6610 #else 6611 if ((ueInt)carry<(DECDPUNMAX+1)*2){ /* fastpath carry 1 */ 6612 *c=(Unit)(carry-(DECDPUNMAX+1)); 6613 carry=1; 6614 continue; 6615 } 6616 /* remainder operator is undefined if negative, so must test */ 6617 if (carry>=0) { 6618 *c=(Unit)(carry%(DECDPUNMAX+1)); 6619 carry=carry/(DECDPUNMAX+1); 6620 continue; 6621 } 6622 /* negative case */ 6623 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */ 6624 *c=(Unit)(carry%(DECDPUNMAX+1)); 6625 carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1); 6626 #endif 6627 } /* c */ 6628 6629 /* OK, all A and B processed; might still have carry or borrow */ 6630 /* return number of Units in the result, negated if a borrow */ 6631 if (carry==0) return c-clsu; /* no carry, so no more to do */ 6632 if (carry>0) { /* positive carry */ 6633 *c=(Unit)carry; /* place as new unit */ 6634 c++; /* .. */ 6635 return c-clsu; 6636 } 6637 /* -ve carry: it's a borrow; complement needed */ 6638 add=1; /* temporary carry... */ 6639 for (c=clsu; c<maxC; c++) { 6640 add=DECDPUNMAX+add-*c; 6641 if (add<=DECDPUNMAX) { 6642 *c=(Unit)add; 6643 add=0; 6644 } 6645 else { 6646 *c=0; 6647 add=1; 6648 } 6649 } 6650 /* add an extra unit iff it would be non-zero */ 6651 #if DECTRACE 6652 printf("UAS borrow: add %ld, carry %ld\n", add, carry); 6653 #endif 6654 if ((add-carry-1)!=0) { 6655 *c=(Unit)(add-carry-1); 6656 c++; /* interesting, include it */ 6657 } 6658 return clsu-c; /* -ve result indicates borrowed */ 6659 } /* decUnitAddSub */ 6660 6661 /* ------------------------------------------------------------------ */ 6662 /* decTrim -- trim trailing zeros or normalize */ 6663 /* */ 6664 /* dn is the number to trim or normalize */ 6665 /* set is the context to use to check for clamp */ 6666 /* all is 1 to remove all trailing zeros, 0 for just fraction ones */ 6667 /* dropped returns the number of discarded trailing zeros */ 6668 /* returns dn */ 6669 /* */ 6670 /* If clamp is set in the context then the number of zeros trimmed */ 6671 /* may be limited if the exponent is high. */ 6672 /* All fields are updated as required. This is a utility operation, */ 6673 /* so special values are unchanged and no error is possible. */ 6674 /* ------------------------------------------------------------------ */ 6675 static decNumber * decTrim(decNumber *dn, decContext *set, Flag all, 6676 Int *dropped) { 6677 Int d, exp; /* work */ 6678 uInt cut; /* .. */ 6679 Unit *up; /* -> current Unit */ 6680 6681 #if DECCHECK 6682 if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn; 6683 #endif 6684 6685 *dropped=0; /* assume no zeros dropped */ 6686 if ((dn->bits & DECSPECIAL) /* fast exit if special .. */ 6687 || (*dn->lsu & 0x01)) return dn; /* .. or odd */ 6688 if (ISZERO(dn)) { /* .. or 0 */ 6689 dn->exponent=0; /* (sign is preserved) */ 6690 return dn; 6691 } 6692 6693 /* have a finite number which is even */ 6694 exp=dn->exponent; 6695 cut=1; /* digit (1-DECDPUN) in Unit */ 6696 up=dn->lsu; /* -> current Unit */ 6697 for (d=0; d<dn->digits-1; d++) { /* [don't strip the final digit] */ 6698 /* slice by powers */ 6699 #if DECDPUN<=4 6700 uInt quot=QUOT10(*up, cut); 6701 if ((*up-quot*powers[cut])!=0) break; /* found non-0 digit */ 6702 #else 6703 if (*up%powers[cut]!=0) break; /* found non-0 digit */ 6704 #endif 6705 /* have a trailing 0 */ 6706 if (!all) { /* trimming */ 6707 /* [if exp>0 then all trailing 0s are significant for trim] */ 6708 if (exp<=0) { /* if digit might be significant */ 6709 if (exp==0) break; /* then quit */ 6710 exp++; /* next digit might be significant */ 6711 } 6712 } 6713 cut++; /* next power */ 6714 if (cut>DECDPUN) { /* need new Unit */ 6715 up++; 6716 cut=1; 6717 } 6718 } /* d */ 6719 if (d==0) return dn; /* none to drop */ 6720 6721 /* may need to limit drop if clamping */ 6722 if (set->clamp) { 6723 Int maxd=set->emax-set->digits+1-dn->exponent; 6724 if (maxd<=0) return dn; /* nothing possible */ 6725 if (d>maxd) d=maxd; 6726 } 6727 6728 /* effect the drop */ 6729 decShiftToLeast(dn->lsu, D2U(dn->digits), d); 6730 dn->exponent+=d; /* maintain numerical value */ 6731 dn->digits-=d; /* new length */ 6732 *dropped=d; /* report the count */ 6733 return dn; 6734 } /* decTrim */ 6735 6736 /* ------------------------------------------------------------------ */ 6737 /* decReverse -- reverse a Unit array in place */ 6738 /* */ 6739 /* ulo is the start of the array */ 6740 /* uhi is the end of the array (highest Unit to include) */ 6741 /* */ 6742 /* The units ulo through uhi are reversed in place (if the number */ 6743 /* of units is odd, the middle one is untouched). Note that the */ 6744 /* digit(s) in each unit are unaffected. */ 6745 /* ------------------------------------------------------------------ */ 6746 static void decReverse(Unit *ulo, Unit *uhi) { 6747 Unit temp; 6748 for (; ulo<uhi; ulo++, uhi--) { 6749 temp=*ulo; 6750 *ulo=*uhi; 6751 *uhi=temp; 6752 } 6753 return; 6754 } /* decReverse */ 6755 6756 /* ------------------------------------------------------------------ */ 6757 /* decShiftToMost -- shift digits in array towards most significant */ 6758 /* */ 6759 /* uar is the array */ 6760 /* digits is the count of digits in use in the array */ 6761 /* shift is the number of zeros to pad with (least significant); */ 6762 /* it must be zero or positive */ 6763 /* */ 6764 /* returns the new length of the integer in the array, in digits */ 6765 /* */ 6766 /* No overflow is permitted (that is, the uar array must be known to */ 6767 /* be large enough to hold the result, after shifting). */ 6768 /* ------------------------------------------------------------------ */ 6769 static Int decShiftToMost(Unit *uar, Int digits, Int shift) { 6770 Unit *target, *source, *first; /* work */ 6771 Int cut; /* odd 0's to add */ 6772 uInt next; /* work */ 6773 6774 if (shift==0) return digits; /* [fastpath] nothing to do */ 6775 if ((digits+shift)<=DECDPUN) { /* [fastpath] single-unit case */ 6776 *uar=(Unit)(*uar*powers[shift]); 6777 return digits+shift; 6778 } 6779 6780 next=0; /* all paths */ 6781 source=uar+D2U(digits)-1; /* where msu comes from */ 6782 target=source+D2U(shift); /* where upper part of first cut goes */ 6783 cut=DECDPUN-MSUDIGITS(shift); /* where to slice */ 6784 if (cut==0) { /* unit-boundary case */ 6785 for (; source>=uar; source--, target--) *target=*source; 6786 } 6787 else { 6788 first=uar+D2U(digits+shift)-1; /* where msu of source will end up */ 6789 for (; source>=uar; source--, target--) { 6790 /* split the source Unit and accumulate remainder for next */ 6791 #if DECDPUN<=4 6792 uInt quot=QUOT10(*source, cut); 6793 uInt rem=*source-quot*powers[cut]; 6794 next+=quot; 6795 #else 6796 uInt rem=*source%powers[cut]; 6797 next+=*source/powers[cut]; 6798 #endif 6799 if (target<=first) *target=(Unit)next; /* write to target iff valid */ 6800 next=rem*powers[DECDPUN-cut]; /* save remainder for next Unit */ 6801 } 6802 } /* shift-move */ 6803 6804 /* propagate any partial unit to one below and clear the rest */ 6805 for (; target>=uar; target--) { 6806 *target=(Unit)next; 6807 next=0; 6808 } 6809 return digits+shift; 6810 } /* decShiftToMost */ 6811 6812 /* ------------------------------------------------------------------ */ 6813 /* decShiftToLeast -- shift digits in array towards least significant */ 6814 /* */ 6815 /* uar is the array */ 6816 /* units is length of the array, in units */ 6817 /* shift is the number of digits to remove from the lsu end; it */ 6818 /* must be zero or positive and <= than units*DECDPUN. */ 6819 /* */ 6820 /* returns the new length of the integer in the array, in units */ 6821 /* */ 6822 /* Removed digits are discarded (lost). Units not required to hold */ 6823 /* the final result are unchanged. */ 6824 /* ------------------------------------------------------------------ */ 6825 static Int decShiftToLeast(Unit *uar, Int units, Int shift) { 6826 Unit *target, *up; /* work */ 6827 Int cut, count; /* work */ 6828 Int quot, rem; /* for division */ 6829 6830 if (shift==0) return units; /* [fastpath] nothing to do */ 6831 if (shift==units*DECDPUN) { /* [fastpath] little to do */ 6832 *uar=0; /* all digits cleared gives zero */ 6833 return 1; /* leaves just the one */ 6834 } 6835 6836 target=uar; /* both paths */ 6837 cut=MSUDIGITS(shift); 6838 if (cut==DECDPUN) { /* unit-boundary case; easy */ 6839 up=uar+D2U(shift); 6840 for (; up<uar+units; target++, up++) *target=*up; 6841 return target-uar; 6842 } 6843 6844 /* messier */ 6845 up=uar+D2U(shift-cut); /* source; correct to whole Units */ 6846 count=units*DECDPUN-shift; /* the maximum new length */ 6847 #if DECDPUN<=4 6848 quot=QUOT10(*up, cut); 6849 #else 6850 quot=*up/powers[cut]; 6851 #endif 6852 for (; ; target++) { 6853 *target=(Unit)quot; 6854 count-=(DECDPUN-cut); 6855 if (count<=0) break; 6856 up++; 6857 quot=*up; 6858 #if DECDPUN<=4 6859 quot=QUOT10(quot, cut); 6860 rem=*up-quot*powers[cut]; 6861 #else 6862 rem=quot%powers[cut]; 6863 quot=quot/powers[cut]; 6864 #endif 6865 *target=(Unit)(*target+rem*powers[DECDPUN-cut]); 6866 count-=cut; 6867 if (count<=0) break; 6868 } 6869 return target-uar+1; 6870 } /* decShiftToLeast */ 6871 6872 #if DECSUBSET 6873 /* ------------------------------------------------------------------ */ 6874 /* decRoundOperand -- round an operand [used for subset only] */ 6875 /* */ 6876 /* dn is the number to round (dn->digits is > set->digits) */ 6877 /* set is the relevant context */ 6878 /* status is the status accumulator */ 6879 /* */ 6880 /* returns an allocated decNumber with the rounded result. */ 6881 /* */ 6882 /* lostDigits and other status may be set by this. */ 6883 /* */ 6884 /* Since the input is an operand, it must not be modified. */ 6885 /* Instead, return an allocated decNumber, rounded as required. */ 6886 /* It is the caller's responsibility to free the allocated storage. */ 6887 /* */ 6888 /* If no storage is available then the result cannot be used, so NULL */ 6889 /* is returned. */ 6890 /* ------------------------------------------------------------------ */ 6891 static decNumber *decRoundOperand(const decNumber *dn, decContext *set, 6892 uInt *status) { 6893 decNumber *res; /* result structure */ 6894 uInt newstatus=0; /* status from round */ 6895 Int residue=0; /* rounding accumulator */ 6896 6897 /* Allocate storage for the returned decNumber, big enough for the */ 6898 /* length specified by the context */ 6899 res=(decNumber *)malloc(sizeof(decNumber) 6900 +(D2U(set->digits)-1)*sizeof(Unit)); 6901 if (res==NULL) { 6902 *status|=DEC_Insufficient_storage; 6903 return NULL; 6904 } 6905 decCopyFit(res, dn, set, &residue, &newstatus); 6906 decApplyRound(res, set, residue, &newstatus); 6907 6908 /* If that set Inexact then "lost digits" is raised... */ 6909 if (newstatus & DEC_Inexact) newstatus|=DEC_Lost_digits; 6910 *status|=newstatus; 6911 return res; 6912 } /* decRoundOperand */ 6913 #endif 6914 6915 /* ------------------------------------------------------------------ */ 6916 /* decCopyFit -- copy a number, truncating the coefficient if needed */ 6917 /* */ 6918 /* dest is the target decNumber */ 6919 /* src is the source decNumber */ 6920 /* set is the context [used for length (digits) and rounding mode] */ 6921 /* residue is the residue accumulator */ 6922 /* status contains the current status to be updated */ 6923 /* */ 6924 /* (dest==src is allowed and will be a no-op if fits) */ 6925 /* All fields are updated as required. */ 6926 /* ------------------------------------------------------------------ */ 6927 static void decCopyFit(decNumber *dest, const decNumber *src, 6928 decContext *set, Int *residue, uInt *status) { 6929 dest->bits=src->bits; 6930 dest->exponent=src->exponent; 6931 decSetCoeff(dest, set, src->lsu, src->digits, residue, status); 6932 } /* decCopyFit */ 6933 6934 /* ------------------------------------------------------------------ */ 6935 /* decSetCoeff -- set the coefficient of a number */ 6936 /* */ 6937 /* dn is the number whose coefficient array is to be set. */ 6938 /* It must have space for set->digits digits */ 6939 /* set is the context [for size] */ 6940 /* lsu -> lsu of the source coefficient [may be dn->lsu] */ 6941 /* len is digits in the source coefficient [may be dn->digits] */ 6942 /* residue is the residue accumulator. This has values as in */ 6943 /* decApplyRound, and will be unchanged unless the */ 6944 /* target size is less than len. In this case, the */ 6945 /* coefficient is truncated and the residue is updated to */ 6946 /* reflect the previous residue and the dropped digits. */ 6947 /* status is the status accumulator, as usual */ 6948 /* */ 6949 /* The coefficient may already be in the number, or it can be an */ 6950 /* external intermediate array. If it is in the number, lsu must == */ 6951 /* dn->lsu and len must == dn->digits. */ 6952 /* */ 6953 /* Note that the coefficient length (len) may be < set->digits, and */ 6954 /* in this case this merely copies the coefficient (or is a no-op */ 6955 /* if dn->lsu==lsu). */ 6956 /* */ 6957 /* Note also that (only internally, from decQuantizeOp and */ 6958 /* decSetSubnormal) the value of set->digits may be less than one, */ 6959 /* indicating a round to left. This routine handles that case */ 6960 /* correctly; caller ensures space. */ 6961 /* */ 6962 /* dn->digits, dn->lsu (and as required), and dn->exponent are */ 6963 /* updated as necessary. dn->bits (sign) is unchanged. */ 6964 /* */ 6965 /* DEC_Rounded status is set if any digits are discarded. */ 6966 /* DEC_Inexact status is set if any non-zero digits are discarded, or */ 6967 /* incoming residue was non-0 (implies rounded) */ 6968 /* ------------------------------------------------------------------ */ 6969 /* mapping array: maps 0-9 to canonical residues, so that a residue */ 6970 /* can be adjusted in the range [-1, +1] and achieve correct rounding */ 6971 /* 0 1 2 3 4 5 6 7 8 9 */ 6972 static const uByte resmap[10]={0, 3, 3, 3, 3, 5, 7, 7, 7, 7}; 6973 static void decSetCoeff(decNumber *dn, decContext *set, const Unit *lsu, 6974 Int len, Int *residue, uInt *status) { 6975 Int discard; /* number of digits to discard */ 6976 uInt cut; /* cut point in Unit */ 6977 const Unit *up; /* work */ 6978 Unit *target; /* .. */ 6979 Int count; /* .. */ 6980 #if DECDPUN<=4 6981 uInt temp; /* .. */ 6982 #endif 6983 6984 discard=len-set->digits; /* digits to discard */ 6985 if (discard<=0) { /* no digits are being discarded */ 6986 if (dn->lsu!=lsu) { /* copy needed */ 6987 /* copy the coefficient array to the result number; no shift needed */ 6988 count=len; /* avoids D2U */ 6989 up=lsu; 6990 for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN) 6991 *target=*up; 6992 dn->digits=len; /* set the new length */ 6993 } 6994 /* dn->exponent and residue are unchanged, record any inexactitude */ 6995 if (*residue!=0) *status|=(DEC_Inexact | DEC_Rounded); 6996 return; 6997 } 6998 6999 /* some digits must be discarded ... */ 7000 dn->exponent+=discard; /* maintain numerical value */ 7001 *status|=DEC_Rounded; /* accumulate Rounded status */ 7002 if (*residue>1) *residue=1; /* previous residue now to right, so reduce */ 7003 7004 if (discard>len) { /* everything, +1, is being discarded */ 7005 /* guard digit is 0 */ 7006 /* residue is all the number [NB could be all 0s] */ 7007 if (*residue<=0) { /* not already positive */ 7008 count=len; /* avoids D2U */ 7009 for (up=lsu; count>0; up++, count-=DECDPUN) if (*up!=0) { /* found non-0 */ 7010 *residue=1; 7011 break; /* no need to check any others */ 7012 } 7013 } 7014 if (*residue!=0) *status|=DEC_Inexact; /* record inexactitude */ 7015 *dn->lsu=0; /* coefficient will now be 0 */ 7016 dn->digits=1; /* .. */ 7017 return; 7018 } /* total discard */ 7019 7020 /* partial discard [most common case] */ 7021 /* here, at least the first (most significant) discarded digit exists */ 7022 7023 /* spin up the number, noting residue during the spin, until get to */ 7024 /* the Unit with the first discarded digit. When reach it, extract */ 7025 /* it and remember its position */ 7026 count=0; 7027 for (up=lsu;; up++) { 7028 count+=DECDPUN; 7029 if (count>=discard) break; /* full ones all checked */ 7030 if (*up!=0) *residue=1; 7031 } /* up */ 7032 7033 /* here up -> Unit with first discarded digit */ 7034 cut=discard-(count-DECDPUN)-1; 7035 if (cut==DECDPUN-1) { /* unit-boundary case (fast) */ 7036 Unit half=(Unit)powers[DECDPUN]>>1; 7037 /* set residue directly */ 7038 if (*up>=half) { 7039 if (*up>half) *residue=7; 7040 else *residue+=5; /* add sticky bit */ 7041 } 7042 else { /* <half */ 7043 if (*up!=0) *residue=3; /* [else is 0, leave as sticky bit] */ 7044 } 7045 if (set->digits<=0) { /* special for Quantize/Subnormal :-( */ 7046 *dn->lsu=0; /* .. result is 0 */ 7047 dn->digits=1; /* .. */ 7048 } 7049 else { /* shift to least */ 7050 count=set->digits; /* now digits to end up with */ 7051 dn->digits=count; /* set the new length */ 7052 up++; /* move to next */ 7053 /* on unit boundary, so shift-down copy loop is simple */ 7054 for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN) 7055 *target=*up; 7056 } 7057 } /* unit-boundary case */ 7058 7059 else { /* discard digit is in low digit(s), and not top digit */ 7060 uInt discard1; /* first discarded digit */ 7061 uInt quot, rem; /* for divisions */ 7062 if (cut==0) quot=*up; /* is at bottom of unit */ 7063 else /* cut>0 */ { /* it's not at bottom of unit */ 7064 #if DECDPUN<=4 7065 quot=QUOT10(*up, cut); 7066 rem=*up-quot*powers[cut]; 7067 #else 7068 rem=*up%powers[cut]; 7069 quot=*up/powers[cut]; 7070 #endif 7071 if (rem!=0) *residue=1; 7072 } 7073 /* discard digit is now at bottom of quot */ 7074 #if DECDPUN<=4 7075 temp=(quot*6554)>>16; /* fast /10 */ 7076 /* Vowels algorithm here not a win (9 instructions) */ 7077 discard1=quot-X10(temp); 7078 quot=temp; 7079 #else 7080 discard1=quot%10; 7081 quot=quot/10; 7082 #endif 7083 /* here, discard1 is the guard digit, and residue is everything */ 7084 /* else [use mapping array to accumulate residue safely] */ 7085 *residue+=resmap[discard1]; 7086 cut++; /* update cut */ 7087 /* here: up -> Unit of the array with bottom digit */ 7088 /* cut is the division point for each Unit */ 7089 /* quot holds the uncut high-order digits for the current unit */ 7090 if (set->digits<=0) { /* special for Quantize/Subnormal :-( */ 7091 *dn->lsu=0; /* .. result is 0 */ 7092 dn->digits=1; /* .. */ 7093 } 7094 else { /* shift to least needed */ 7095 count=set->digits; /* now digits to end up with */ 7096 dn->digits=count; /* set the new length */ 7097 /* shift-copy the coefficient array to the result number */ 7098 for (target=dn->lsu; ; target++) { 7099 *target=(Unit)quot; 7100 count-=(DECDPUN-cut); 7101 if (count<=0) break; 7102 up++; 7103 quot=*up; 7104 #if DECDPUN<=4 7105 quot=QUOT10(quot, cut); 7106 rem=*up-quot*powers[cut]; 7107 #else 7108 rem=quot%powers[cut]; 7109 quot=quot/powers[cut]; 7110 #endif 7111 *target=(Unit)(*target+rem*powers[DECDPUN-cut]); 7112 count-=cut; 7113 if (count<=0) break; 7114 } /* shift-copy loop */ 7115 } /* shift to least */ 7116 } /* not unit boundary */ 7117 7118 if (*residue!=0) *status|=DEC_Inexact; /* record inexactitude */ 7119 return; 7120 } /* decSetCoeff */ 7121 7122 /* ------------------------------------------------------------------ */ 7123 /* decApplyRound -- apply pending rounding to a number */ 7124 /* */ 7125 /* dn is the number, with space for set->digits digits */ 7126 /* set is the context [for size and rounding mode] */ 7127 /* residue indicates pending rounding, being any accumulated */ 7128 /* guard and sticky information. It may be: */ 7129 /* 6-9: rounding digit is >5 */ 7130 /* 5: rounding digit is exactly half-way */ 7131 /* 1-4: rounding digit is <5 and >0 */ 7132 /* 0: the coefficient is exact */ 7133 /* -1: as 1, but the hidden digits are subtractive, that */ 7134 /* is, of the opposite sign to dn. In this case the */ 7135 /* coefficient must be non-0. This case occurs when */ 7136 /* subtracting a small number (which can be reduced to */ 7137 /* a sticky bit); see decAddOp. */ 7138 /* status is the status accumulator, as usual */ 7139 /* */ 7140 /* This routine applies rounding while keeping the length of the */ 7141 /* coefficient constant. The exponent and status are unchanged */ 7142 /* except if: */ 7143 /* */ 7144 /* -- the coefficient was increased and is all nines (in which */ 7145 /* case Overflow could occur, and is handled directly here so */ 7146 /* the caller does not need to re-test for overflow) */ 7147 /* */ 7148 /* -- the coefficient was decreased and becomes all nines (in which */ 7149 /* case Underflow could occur, and is also handled directly). */ 7150 /* */ 7151 /* All fields in dn are updated as required. */ 7152 /* */ 7153 /* ------------------------------------------------------------------ */ 7154 static void decApplyRound(decNumber *dn, decContext *set, Int residue, 7155 uInt *status) { 7156 Int bump; /* 1 if coefficient needs to be incremented */ 7157 /* -1 if coefficient needs to be decremented */ 7158 7159 if (residue==0) return; /* nothing to apply */ 7160 7161 bump=0; /* assume a smooth ride */ 7162 7163 /* now decide whether, and how, to round, depending on mode */ 7164 switch (set->round) { 7165 case DEC_ROUND_05UP: { /* round zero or five up (for reround) */ 7166 /* This is the same as DEC_ROUND_DOWN unless there is a */ 7167 /* positive residue and the lsd of dn is 0 or 5, in which case */ 7168 /* it is bumped; when residue is <0, the number is therefore */ 7169 /* bumped down unless the final digit was 1 or 6 (in which */ 7170 /* case it is bumped down and then up -- a no-op) */ 7171 Int lsd5=*dn->lsu%5; /* get lsd and quintate */ 7172 if (residue<0 && lsd5!=1) bump=-1; 7173 else if (residue>0 && lsd5==0) bump=1; 7174 /* [bump==1 could be applied directly; use common path for clarity] */ 7175 break;} /* r-05 */ 7176 7177 case DEC_ROUND_DOWN: { 7178 /* no change, except if negative residue */ 7179 if (residue<0) bump=-1; 7180 break;} /* r-d */ 7181 7182 case DEC_ROUND_HALF_DOWN: { 7183 if (residue>5) bump=1; 7184 break;} /* r-h-d */ 7185 7186 case DEC_ROUND_HALF_EVEN: { 7187 if (residue>5) bump=1; /* >0.5 goes up */ 7188 else if (residue==5) { /* exactly 0.5000... */ 7189 /* 0.5 goes up iff [new] lsd is odd */ 7190 if (*dn->lsu & 0x01) bump=1; 7191 } 7192 break;} /* r-h-e */ 7193 7194 case DEC_ROUND_HALF_UP: { 7195 if (residue>=5) bump=1; 7196 break;} /* r-h-u */ 7197 7198 case DEC_ROUND_UP: { 7199 if (residue>0) bump=1; 7200 break;} /* r-u */ 7201 7202 case DEC_ROUND_CEILING: { 7203 /* same as _UP for positive numbers, and as _DOWN for negatives */ 7204 /* [negative residue cannot occur on 0] */ 7205 if (decNumberIsNegative(dn)) { 7206 if (residue<0) bump=-1; 7207 } 7208 else { 7209 if (residue>0) bump=1; 7210 } 7211 break;} /* r-c */ 7212 7213 case DEC_ROUND_FLOOR: { 7214 /* same as _UP for negative numbers, and as _DOWN for positive */ 7215 /* [negative residue cannot occur on 0] */ 7216 if (!decNumberIsNegative(dn)) { 7217 if (residue<0) bump=-1; 7218 } 7219 else { 7220 if (residue>0) bump=1; 7221 } 7222 break;} /* r-f */ 7223 7224 default: { /* e.g., DEC_ROUND_MAX */ 7225 *status|=DEC_Invalid_context; 7226 #if DECTRACE || (DECCHECK && DECVERB) 7227 printf("Unknown rounding mode: %d\n", set->round); 7228 #endif 7229 break;} 7230 } /* switch */ 7231 7232 /* now bump the number, up or down, if need be */ 7233 if (bump==0) return; /* no action required */ 7234 7235 /* Simply use decUnitAddSub unless bumping up and the number is */ 7236 /* all nines. In this special case set to 100... explicitly */ 7237 /* and adjust the exponent by one (as otherwise could overflow */ 7238 /* the array) */ 7239 /* Similarly handle all-nines result if bumping down. */ 7240 if (bump>0) { 7241 Unit *up; /* work */ 7242 uInt count=dn->digits; /* digits to be checked */ 7243 for (up=dn->lsu; ; up++) { 7244 if (count<=DECDPUN) { 7245 /* this is the last Unit (the msu) */ 7246 if (*up!=powers[count]-1) break; /* not still 9s */ 7247 /* here if it, too, is all nines */ 7248 *up=(Unit)powers[count-1]; /* here 999 -> 100 etc. */ 7249 for (up=up-1; up>=dn->lsu; up--) *up=0; /* others all to 0 */ 7250 dn->exponent++; /* and bump exponent */ 7251 /* [which, very rarely, could cause Overflow...] */ 7252 if ((dn->exponent+dn->digits)>set->emax+1) { 7253 decSetOverflow(dn, set, status); 7254 } 7255 return; /* done */ 7256 } 7257 /* a full unit to check, with more to come */ 7258 if (*up!=DECDPUNMAX) break; /* not still 9s */ 7259 count-=DECDPUN; 7260 } /* up */ 7261 } /* bump>0 */ 7262 else { /* -1 */ 7263 /* here checking for a pre-bump of 1000... (leading 1, all */ 7264 /* other digits zero) */ 7265 Unit *up, *sup; /* work */ 7266 uInt count=dn->digits; /* digits to be checked */ 7267 for (up=dn->lsu; ; up++) { 7268 if (count<=DECDPUN) { 7269 /* this is the last Unit (the msu) */ 7270 if (*up!=powers[count-1]) break; /* not 100.. */ 7271 /* here if have the 1000... case */ 7272 sup=up; /* save msu pointer */ 7273 *up=(Unit)powers[count]-1; /* here 100 in msu -> 999 */ 7274 /* others all to all-nines, too */ 7275 for (up=up-1; up>=dn->lsu; up--) *up=(Unit)powers[DECDPUN]-1; 7276 dn->exponent--; /* and bump exponent */ 7277 7278 /* iff the number was at the subnormal boundary (exponent=etiny) */ 7279 /* then the exponent is now out of range, so it will in fact get */ 7280 /* clamped to etiny and the final 9 dropped. */ 7281 /* printf(">> emin=%d exp=%d sdig=%d\n", set->emin, */ 7282 /* dn->exponent, set->digits); */ 7283 if (dn->exponent+1==set->emin-set->digits+1) { 7284 if (count==1 && dn->digits==1) *sup=0; /* here 9 -> 0[.9] */ 7285 else { 7286 *sup=(Unit)powers[count-1]-1; /* here 999.. in msu -> 99.. */ 7287 dn->digits--; 7288 } 7289 dn->exponent++; 7290 *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded; 7291 } 7292 return; /* done */ 7293 } 7294 7295 /* a full unit to check, with more to come */ 7296 if (*up!=0) break; /* not still 0s */ 7297 count-=DECDPUN; 7298 } /* up */ 7299 7300 } /* bump<0 */ 7301 7302 /* Actual bump needed. Do it. */ 7303 decUnitAddSub(dn->lsu, D2U(dn->digits), uarrone, 1, 0, dn->lsu, bump); 7304 } /* decApplyRound */ 7305 7306 #if DECSUBSET 7307 /* ------------------------------------------------------------------ */ 7308 /* decFinish -- finish processing a number */ 7309 /* */ 7310 /* dn is the number */ 7311 /* set is the context */ 7312 /* residue is the rounding accumulator (as in decApplyRound) */ 7313 /* status is the accumulator */ 7314 /* */ 7315 /* This finishes off the current number by: */ 7316 /* 1. If not extended: */ 7317 /* a. Converting a zero result to clean '0' */ 7318 /* b. Reducing positive exponents to 0, if would fit in digits */ 7319 /* 2. Checking for overflow and subnormals (always) */ 7320 /* Note this is just Finalize when no subset arithmetic. */ 7321 /* All fields are updated as required. */ 7322 /* ------------------------------------------------------------------ */ 7323 static void decFinish(decNumber *dn, decContext *set, Int *residue, 7324 uInt *status) { 7325 if (!set->extended) { 7326 if ISZERO(dn) { /* value is zero */ 7327 dn->exponent=0; /* clean exponent .. */ 7328 dn->bits=0; /* .. and sign */ 7329 return; /* no error possible */ 7330 } 7331 if (dn->exponent>=0) { /* non-negative exponent */ 7332 /* >0; reduce to integer if possible */ 7333 if (set->digits >= (dn->exponent+dn->digits)) { 7334 dn->digits=decShiftToMost(dn->lsu, dn->digits, dn->exponent); 7335 dn->exponent=0; 7336 } 7337 } 7338 } /* !extended */ 7339 7340 decFinalize(dn, set, residue, status); 7341 } /* decFinish */ 7342 #endif 7343 7344 /* ------------------------------------------------------------------ */ 7345 /* decFinalize -- final check, clamp, and round of a number */ 7346 /* */ 7347 /* dn is the number */ 7348 /* set is the context */ 7349 /* residue is the rounding accumulator (as in decApplyRound) */ 7350 /* status is the status accumulator */ 7351 /* */ 7352 /* This finishes off the current number by checking for subnormal */ 7353 /* results, applying any pending rounding, checking for overflow, */ 7354 /* and applying any clamping. */ 7355 /* Underflow and overflow conditions are raised as appropriate. */ 7356 /* All fields are updated as required. */ 7357 /* ------------------------------------------------------------------ */ 7358 static void decFinalize(decNumber *dn, decContext *set, Int *residue, 7359 uInt *status) { 7360 Int shift; /* shift needed if clamping */ 7361 Int tinyexp=set->emin-dn->digits+1; /* precalculate subnormal boundary */ 7362 7363 /* Must be careful, here, when checking the exponent as the */ 7364 /* adjusted exponent could overflow 31 bits [because it may already */ 7365 /* be up to twice the expected]. */ 7366 7367 /* First test for subnormal. This must be done before any final */ 7368 /* round as the result could be rounded to Nmin or 0. */ 7369 if (dn->exponent<=tinyexp) { /* prefilter */ 7370 Int comp; 7371 decNumber nmin; 7372 /* A very nasty case here is dn == Nmin and residue<0 */ 7373 if (dn->exponent<tinyexp) { 7374 /* Go handle subnormals; this will apply round if needed. */ 7375 decSetSubnormal(dn, set, residue, status); 7376 return; 7377 } 7378 /* Equals case: only subnormal if dn=Nmin and negative residue */ 7379 decNumberZero(&nmin); 7380 nmin.lsu[0]=1; 7381 nmin.exponent=set->emin; 7382 comp=decCompare(dn, &nmin, 1); /* (signless compare) */ 7383 if (comp==BADINT) { /* oops */ 7384 *status|=DEC_Insufficient_storage; /* abandon... */ 7385 return; 7386 } 7387 if (*residue<0 && comp==0) { /* neg residue and dn==Nmin */ 7388 decApplyRound(dn, set, *residue, status); /* might force down */ 7389 decSetSubnormal(dn, set, residue, status); 7390 return; 7391 } 7392 } 7393 7394 /* now apply any pending round (this could raise overflow). */ 7395 if (*residue!=0) decApplyRound(dn, set, *residue, status); 7396 7397 /* Check for overflow [redundant in the 'rare' case] or clamp */ 7398 if (dn->exponent<=set->emax-set->digits+1) return; /* neither needed */ 7399 7400 7401 /* here when might have an overflow or clamp to do */ 7402 if (dn->exponent>set->emax-dn->digits+1) { /* too big */ 7403 decSetOverflow(dn, set, status); 7404 return; 7405 } 7406 /* here when the result is normal but in clamp range */ 7407 if (!set->clamp) return; 7408 7409 /* here when need to apply the IEEE exponent clamp (fold-down) */ 7410 shift=dn->exponent-(set->emax-set->digits+1); 7411 7412 /* shift coefficient (if non-zero) */ 7413 if (!ISZERO(dn)) { 7414 dn->digits=decShiftToMost(dn->lsu, dn->digits, shift); 7415 } 7416 dn->exponent-=shift; /* adjust the exponent to match */ 7417 *status|=DEC_Clamped; /* and record the dirty deed */ 7418 return; 7419 } /* decFinalize */ 7420 7421 /* ------------------------------------------------------------------ */ 7422 /* decSetOverflow -- set number to proper overflow value */ 7423 /* */ 7424 /* dn is the number (used for sign [only] and result) */ 7425 /* set is the context [used for the rounding mode, etc.] */ 7426 /* status contains the current status to be updated */ 7427 /* */ 7428 /* This sets the sign of a number and sets its value to either */ 7429 /* Infinity or the maximum finite value, depending on the sign of */ 7430 /* dn and the rounding mode, following IEEE 854 rules. */ 7431 /* ------------------------------------------------------------------ */ 7432 static void decSetOverflow(decNumber *dn, decContext *set, uInt *status) { 7433 Flag needmax=0; /* result is maximum finite value */ 7434 uByte sign=dn->bits&DECNEG; /* clean and save sign bit */ 7435 7436 if (ISZERO(dn)) { /* zero does not overflow magnitude */ 7437 Int emax=set->emax; /* limit value */ 7438 if (set->clamp) emax-=set->digits-1; /* lower if clamping */ 7439 if (dn->exponent>emax) { /* clamp required */ 7440 dn->exponent=emax; 7441 *status|=DEC_Clamped; 7442 } 7443 return; 7444 } 7445 7446 decNumberZero(dn); 7447 switch (set->round) { 7448 case DEC_ROUND_DOWN: { 7449 needmax=1; /* never Infinity */ 7450 break;} /* r-d */ 7451 case DEC_ROUND_05UP: { 7452 needmax=1; /* never Infinity */ 7453 break;} /* r-05 */ 7454 case DEC_ROUND_CEILING: { 7455 if (sign) needmax=1; /* Infinity if non-negative */ 7456 break;} /* r-c */ 7457 case DEC_ROUND_FLOOR: { 7458 if (!sign) needmax=1; /* Infinity if negative */ 7459 break;} /* r-f */ 7460 default: break; /* Infinity in all other cases */ 7461 } 7462 if (needmax) { 7463 decSetMaxValue(dn, set); 7464 dn->bits=sign; /* set sign */ 7465 } 7466 else dn->bits=sign|DECINF; /* Value is +/-Infinity */ 7467 *status|=DEC_Overflow | DEC_Inexact | DEC_Rounded; 7468 } /* decSetOverflow */ 7469 7470 /* ------------------------------------------------------------------ */ 7471 /* decSetMaxValue -- set number to +Nmax (maximum normal value) */ 7472 /* */ 7473 /* dn is the number to set */ 7474 /* set is the context [used for digits and emax] */ 7475 /* */ 7476 /* This sets the number to the maximum positive value. */ 7477 /* ------------------------------------------------------------------ */ 7478 static void decSetMaxValue(decNumber *dn, decContext *set) { 7479 Unit *up; /* work */ 7480 Int count=set->digits; /* nines to add */ 7481 dn->digits=count; 7482 /* fill in all nines to set maximum value */ 7483 for (up=dn->lsu; ; up++) { 7484 if (count>DECDPUN) *up=DECDPUNMAX; /* unit full o'nines */ 7485 else { /* this is the msu */ 7486 *up=(Unit)(powers[count]-1); 7487 break; 7488 } 7489 count-=DECDPUN; /* filled those digits */ 7490 } /* up */ 7491 dn->bits=0; /* + sign */ 7492 dn->exponent=set->emax-set->digits+1; 7493 } /* decSetMaxValue */ 7494 7495 /* ------------------------------------------------------------------ */ 7496 /* decSetSubnormal -- process value whose exponent is <Emin */ 7497 /* */ 7498 /* dn is the number (used as input as well as output; it may have */ 7499 /* an allowed subnormal value, which may need to be rounded) */ 7500 /* set is the context [used for the rounding mode] */ 7501 /* residue is any pending residue */ 7502 /* status contains the current status to be updated */ 7503 /* */ 7504 /* If subset mode, set result to zero and set Underflow flags. */ 7505 /* */ 7506 /* Value may be zero with a low exponent; this does not set Subnormal */ 7507 /* but the exponent will be clamped to Etiny. */ 7508 /* */ 7509 /* Otherwise ensure exponent is not out of range, and round as */ 7510 /* necessary. Underflow is set if the result is Inexact. */ 7511 /* ------------------------------------------------------------------ */ 7512 static void decSetSubnormal(decNumber *dn, decContext *set, Int *residue, 7513 uInt *status) { 7514 decContext workset; /* work */ 7515 Int etiny, adjust; /* .. */ 7516 7517 #if DECSUBSET 7518 /* simple set to zero and 'hard underflow' for subset */ 7519 if (!set->extended) { 7520 decNumberZero(dn); 7521 /* always full overflow */ 7522 *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded; 7523 return; 7524 } 7525 #endif 7526 7527 /* Full arithmetic -- allow subnormals, rounded to minimum exponent */ 7528 /* (Etiny) if needed */ 7529 etiny=set->emin-(set->digits-1); /* smallest allowed exponent */ 7530 7531 if ISZERO(dn) { /* value is zero */ 7532 /* residue can never be non-zero here */ 7533 #if DECCHECK 7534 if (*residue!=0) { 7535 printf("++ Subnormal 0 residue %ld\n", (LI)*residue); 7536 *status|=DEC_Invalid_operation; 7537 } 7538 #endif 7539 if (dn->exponent<etiny) { /* clamp required */ 7540 dn->exponent=etiny; 7541 *status|=DEC_Clamped; 7542 } 7543 return; 7544 } 7545 7546 *status|=DEC_Subnormal; /* have a non-zero subnormal */ 7547 adjust=etiny-dn->exponent; /* calculate digits to remove */ 7548 if (adjust<=0) { /* not out of range; unrounded */ 7549 /* residue can never be non-zero here, except in the Nmin-residue */ 7550 /* case (which is a subnormal result), so can take fast-path here */ 7551 /* it may already be inexact (from setting the coefficient) */ 7552 if (*status&DEC_Inexact) *status|=DEC_Underflow; 7553 return; 7554 } 7555 7556 /* adjust>0, so need to rescale the result so exponent becomes Etiny */ 7557 /* [this code is similar to that in rescale] */ 7558 workset=*set; /* clone rounding, etc. */ 7559 workset.digits=dn->digits-adjust; /* set requested length */ 7560 workset.emin-=adjust; /* and adjust emin to match */ 7561 /* [note that the latter can be <1, here, similar to Rescale case] */ 7562 decSetCoeff(dn, &workset, dn->lsu, dn->digits, residue, status); 7563 decApplyRound(dn, &workset, *residue, status); 7564 7565 /* Use 754R/854 default rule: Underflow is set iff Inexact */ 7566 /* [independent of whether trapped] */ 7567 if (*status&DEC_Inexact) *status|=DEC_Underflow; 7568 7569 /* if rounded up a 999s case, exponent will be off by one; adjust */ 7570 /* back if so [it will fit, because it was shortened earlier] */ 7571 if (dn->exponent>etiny) { 7572 dn->digits=decShiftToMost(dn->lsu, dn->digits, 1); 7573 dn->exponent--; /* (re)adjust the exponent. */ 7574 } 7575 7576 /* if rounded to zero, it is by definition clamped... */ 7577 if (ISZERO(dn)) *status|=DEC_Clamped; 7578 } /* decSetSubnormal */ 7579 7580 /* ------------------------------------------------------------------ */ 7581 /* decCheckMath - check entry conditions for a math function */ 7582 /* */ 7583 /* This checks the context and the operand */ 7584 /* */ 7585 /* rhs is the operand to check */ 7586 /* set is the context to check */ 7587 /* status is unchanged if both are good */ 7588 /* */ 7589 /* returns non-zero if status is changed, 0 otherwise */ 7590 /* */ 7591 /* Restrictions enforced: */ 7592 /* */ 7593 /* digits, emax, and -emin in the context must be less than */ 7594 /* DEC_MAX_MATH (999999), and A must be within these bounds if */ 7595 /* non-zero. Invalid_operation is set in the status if a */ 7596 /* restriction is violated. */ 7597 /* ------------------------------------------------------------------ */ 7598 static uInt decCheckMath(const decNumber *rhs, decContext *set, 7599 uInt *status) { 7600 uInt save=*status; /* record */ 7601 if (set->digits>DEC_MAX_MATH 7602 || set->emax>DEC_MAX_MATH 7603 || -set->emin>DEC_MAX_MATH) *status|=DEC_Invalid_context; 7604 else if ((rhs->digits>DEC_MAX_MATH 7605 || rhs->exponent+rhs->digits>DEC_MAX_MATH+1 7606 || rhs->exponent+rhs->digits<2*(1-DEC_MAX_MATH)) 7607 && !ISZERO(rhs)) *status|=DEC_Invalid_operation; 7608 return (*status!=save); 7609 } /* decCheckMath */ 7610 7611 /* ------------------------------------------------------------------ */ 7612 /* decGetInt -- get integer from a number */ 7613 /* */ 7614 /* dn is the number [which will not be altered] */ 7615 /* */ 7616 /* returns one of: */ 7617 /* BADINT if there is a non-zero fraction */ 7618 /* the converted integer */ 7619 /* BIGEVEN if the integer is even and magnitude > 2*10**9 */ 7620 /* BIGODD if the integer is odd and magnitude > 2*10**9 */ 7621 /* */ 7622 /* This checks and gets a whole number from the input decNumber. */ 7623 /* The sign can be determined from dn by the caller when BIGEVEN or */ 7624 /* BIGODD is returned. */ 7625 /* ------------------------------------------------------------------ */ 7626 static Int decGetInt(const decNumber *dn) { 7627 Int theInt; /* result accumulator */ 7628 const Unit *up; /* work */ 7629 Int got; /* digits (real or not) processed */ 7630 Int ilength=dn->digits+dn->exponent; /* integral length */ 7631 Flag neg=decNumberIsNegative(dn); /* 1 if -ve */ 7632 7633 /* The number must be an integer that fits in 10 digits */ 7634 /* Assert, here, that 10 is enough for any rescale Etiny */ 7635 #if DEC_MAX_EMAX > 999999999 7636 #error GetInt may need updating [for Emax] 7637 #endif 7638 #if DEC_MIN_EMIN < -999999999 7639 #error GetInt may need updating [for Emin] 7640 #endif 7641 if (ISZERO(dn)) return 0; /* zeros are OK, with any exponent */ 7642 7643 up=dn->lsu; /* ready for lsu */ 7644 theInt=0; /* ready to accumulate */ 7645 if (dn->exponent>=0) { /* relatively easy */ 7646 /* no fractional part [usual]; allow for positive exponent */ 7647 got=dn->exponent; 7648 } 7649 else { /* -ve exponent; some fractional part to check and discard */ 7650 Int count=-dn->exponent; /* digits to discard */ 7651 /* spin up whole units until reach the Unit with the unit digit */ 7652 for (; count>=DECDPUN; up++) { 7653 if (*up!=0) return BADINT; /* non-zero Unit to discard */ 7654 count-=DECDPUN; 7655 } 7656 if (count==0) got=0; /* [a multiple of DECDPUN] */ 7657 else { /* [not multiple of DECDPUN] */ 7658 Int rem; /* work */ 7659 /* slice off fraction digits and check for non-zero */ 7660 #if DECDPUN<=4 7661 theInt=QUOT10(*up, count); 7662 rem=*up-theInt*powers[count]; 7663 #else 7664 rem=*up%powers[count]; /* slice off discards */ 7665 theInt=*up/powers[count]; 7666 #endif 7667 if (rem!=0) return BADINT; /* non-zero fraction */ 7668 /* it looks good */ 7669 got=DECDPUN-count; /* number of digits so far */ 7670 up++; /* ready for next */ 7671 } 7672 } 7673 /* now it's known there's no fractional part */ 7674 7675 /* tricky code now, to accumulate up to 9.3 digits */ 7676 if (got==0) {theInt=*up; got+=DECDPUN; up++;} /* ensure lsu is there */ 7677 7678 if (ilength<11) { 7679 Int save=theInt; 7680 /* collect any remaining unit(s) */ 7681 for (; got<ilength; up++) { 7682 theInt+=*up*powers[got]; 7683 got+=DECDPUN; 7684 } 7685 if (ilength==10) { /* need to check for wrap */ 7686 if (theInt/(Int)powers[got-DECDPUN]!=(Int)*(up-1)) ilength=11; 7687 /* [that test also disallows the BADINT result case] */ 7688 else if (neg && theInt>1999999997) ilength=11; 7689 else if (!neg && theInt>999999999) ilength=11; 7690 if (ilength==11) theInt=save; /* restore correct low bit */ 7691 } 7692 } 7693 7694 if (ilength>10) { /* too big */ 7695 if (theInt&1) return BIGODD; /* bottom bit 1 */ 7696 return BIGEVEN; /* bottom bit 0 */ 7697 } 7698 7699 if (neg) theInt=-theInt; /* apply sign */ 7700 return theInt; 7701 } /* decGetInt */ 7702 7703 /* ------------------------------------------------------------------ */ 7704 /* decDecap -- decapitate the coefficient of a number */ 7705 /* */ 7706 /* dn is the number to be decapitated */ 7707 /* drop is the number of digits to be removed from the left of dn; */ 7708 /* this must be <= dn->digits (if equal, the coefficient is */ 7709 /* set to 0) */ 7710 /* */ 7711 /* Returns dn; dn->digits will be <= the initial digits less drop */ 7712 /* (after removing drop digits there may be leading zero digits */ 7713 /* which will also be removed). Only dn->lsu and dn->digits change. */ 7714 /* ------------------------------------------------------------------ */ 7715 static decNumber *decDecap(decNumber *dn, Int drop) { 7716 Unit *msu; /* -> target cut point */ 7717 Int cut; /* work */ 7718 if (drop>=dn->digits) { /* losing the whole thing */ 7719 #if DECCHECK 7720 if (drop>dn->digits) 7721 printf("decDecap called with drop>digits [%ld>%ld]\n", 7722 (LI)drop, (LI)dn->digits); 7723 #endif 7724 dn->lsu[0]=0; 7725 dn->digits=1; 7726 return dn; 7727 } 7728 msu=dn->lsu+D2U(dn->digits-drop)-1; /* -> likely msu */ 7729 cut=MSUDIGITS(dn->digits-drop); /* digits to be in use in msu */ 7730 if (cut!=DECDPUN) *msu%=powers[cut]; /* clear left digits */ 7731 /* that may have left leading zero digits, so do a proper count... */ 7732 dn->digits=decGetDigits(dn->lsu, msu-dn->lsu+1); 7733 return dn; 7734 } /* decDecap */ 7735 7736 /* ------------------------------------------------------------------ */ 7737 /* decBiStr -- compare string with pairwise options */ 7738 /* */ 7739 /* targ is the string to compare */ 7740 /* str1 is one of the strings to compare against (length may be 0) */ 7741 /* str2 is the other; it must be the same length as str1 */ 7742 /* */ 7743 /* returns 1 if strings compare equal, (that is, it is the same */ 7744 /* length as str1 and str2, and each character of targ is in either */ 7745 /* str1 or str2 in the corresponding position), or 0 otherwise */ 7746 /* */ 7747 /* This is used for generic caseless compare, including the awkward */ 7748 /* case of the Turkish dotted and dotless Is. Use as (for example): */ 7749 /* if (decBiStr(test, "mike", "MIKE")) ... */ 7750 /* ------------------------------------------------------------------ */ 7751 static Flag decBiStr(const char *targ, const char *str1, const char *str2) { 7752 for (;;targ++, str1++, str2++) { 7753 if (*targ!=*str1 && *targ!=*str2) return 0; 7754 /* *targ has a match in one (or both, if terminator) */ 7755 if (*targ=='\0') break; 7756 } /* forever */ 7757 return 1; 7758 } /* decBiStr */ 7759 7760 /* ------------------------------------------------------------------ */ 7761 /* decNaNs -- handle NaN operand or operands */ 7762 /* */ 7763 /* res is the result number */ 7764 /* lhs is the first operand */ 7765 /* rhs is the second operand, or NULL if none */ 7766 /* context is used to limit payload length */ 7767 /* status contains the current status */ 7768 /* returns res in case convenient */ 7769 /* */ 7770 /* Called when one or both operands is a NaN, and propagates the */ 7771 /* appropriate result to res. When an sNaN is found, it is changed */ 7772 /* to a qNaN and Invalid operation is set. */ 7773 /* ------------------------------------------------------------------ */ 7774 static decNumber * decNaNs(decNumber *res, const decNumber *lhs, 7775 const decNumber *rhs, decContext *set, 7776 uInt *status) { 7777 /* This decision tree ends up with LHS being the source pointer, */ 7778 /* and status updated if need be */ 7779 if (lhs->bits & DECSNAN) 7780 *status|=DEC_Invalid_operation | DEC_sNaN; 7781 else if (rhs==NULL); 7782 else if (rhs->bits & DECSNAN) { 7783 lhs=rhs; 7784 *status|=DEC_Invalid_operation | DEC_sNaN; 7785 } 7786 else if (lhs->bits & DECNAN); 7787 else lhs=rhs; 7788 7789 /* propagate the payload */ 7790 if (lhs->digits<=set->digits) decNumberCopy(res, lhs); /* easy */ 7791 else { /* too long */ 7792 const Unit *ul; 7793 Unit *ur, *uresp1; 7794 /* copy safe number of units, then decapitate */ 7795 res->bits=lhs->bits; /* need sign etc. */ 7796 uresp1=res->lsu+D2U(set->digits); 7797 for (ur=res->lsu, ul=lhs->lsu; ur<uresp1; ur++, ul++) *ur=*ul; 7798 res->digits=D2U(set->digits)*DECDPUN; 7799 /* maybe still too long */ 7800 if (res->digits>set->digits) decDecap(res, res->digits-set->digits); 7801 } 7802 7803 res->bits&=~DECSNAN; /* convert any sNaN to NaN, while */ 7804 res->bits|=DECNAN; /* .. preserving sign */ 7805 res->exponent=0; /* clean exponent */ 7806 /* [coefficient was copied/decapitated] */ 7807 return res; 7808 } /* decNaNs */ 7809 7810 /* ------------------------------------------------------------------ */ 7811 /* decStatus -- apply non-zero status */ 7812 /* */ 7813 /* dn is the number to set if error */ 7814 /* status contains the current status (not yet in context) */ 7815 /* set is the context */ 7816 /* */ 7817 /* If the status is an error status, the number is set to a NaN, */ 7818 /* unless the error was an overflow, divide-by-zero, or underflow, */ 7819 /* in which case the number will have already been set. */ 7820 /* */ 7821 /* The context status is then updated with the new status. Note that */ 7822 /* this may raise a signal, so control may never return from this */ 7823 /* routine (hence resources must be recovered before it is called). */ 7824 /* ------------------------------------------------------------------ */ 7825 static void decStatus(decNumber *dn, uInt status, decContext *set) { 7826 if (status & DEC_NaNs) { /* error status -> NaN */ 7827 /* if cause was an sNaN, clear and propagate [NaN is already set up] */ 7828 if (status & DEC_sNaN) status&=~DEC_sNaN; 7829 else { 7830 decNumberZero(dn); /* other error: clean throughout */ 7831 dn->bits=DECNAN; /* and make a quiet NaN */ 7832 } 7833 } 7834 decContextSetStatus(set, status); /* [may not return] */ 7835 return; 7836 } /* decStatus */ 7837 7838 /* ------------------------------------------------------------------ */ 7839 /* decGetDigits -- count digits in a Units array */ 7840 /* */ 7841 /* uar is the Unit array holding the number (this is often an */ 7842 /* accumulator of some sort) */ 7843 /* len is the length of the array in units [>=1] */ 7844 /* */ 7845 /* returns the number of (significant) digits in the array */ 7846 /* */ 7847 /* All leading zeros are excluded, except the last if the array has */ 7848 /* only zero Units. */ 7849 /* ------------------------------------------------------------------ */ 7850 /* This may be called twice during some operations. */ 7851 static Int decGetDigits(Unit *uar, Int len) { 7852 Unit *up=uar+(len-1); /* -> msu */ 7853 Int digits=(len-1)*DECDPUN+1; /* possible digits excluding msu */ 7854 #if DECDPUN>4 7855 uInt const *pow; /* work */ 7856 #endif 7857 /* (at least 1 in final msu) */ 7858 #if DECCHECK 7859 if (len<1) printf("decGetDigits called with len<1 [%ld]\n", (LI)len); 7860 #endif 7861 7862 for (; up>=uar; up--) { 7863 if (*up==0) { /* unit is all 0s */ 7864 if (digits==1) break; /* a zero has one digit */ 7865 digits-=DECDPUN; /* adjust for 0 unit */ 7866 continue;} 7867 /* found the first (most significant) non-zero Unit */ 7868 #if DECDPUN>1 /* not done yet */ 7869 if (*up<10) break; /* is 1-9 */ 7870 digits++; 7871 #if DECDPUN>2 /* not done yet */ 7872 if (*up<100) break; /* is 10-99 */ 7873 digits++; 7874 #if DECDPUN>3 /* not done yet */ 7875 if (*up<1000) break; /* is 100-999 */ 7876 digits++; 7877 #if DECDPUN>4 /* count the rest ... */ 7878 for (pow=&powers[4]; *up>=*pow; pow++) digits++; 7879 #endif 7880 #endif 7881 #endif 7882 #endif 7883 break; 7884 } /* up */ 7885 return digits; 7886 } /* decGetDigits */ 7887 7888 #if DECTRACE | DECCHECK 7889 /* ------------------------------------------------------------------ */ 7890 /* decNumberShow -- display a number [debug aid] */ 7891 /* dn is the number to show */ 7892 /* */ 7893 /* Shows: sign, exponent, coefficient (msu first), digits */ 7894 /* or: sign, special-value */ 7895 /* ------------------------------------------------------------------ */ 7896 /* this is public so other modules can use it */ 7897 void decNumberShow(const decNumber *dn) { 7898 const Unit *up; /* work */ 7899 uInt u, d; /* .. */ 7900 Int cut; /* .. */ 7901 char isign='+'; /* main sign */ 7902 if (dn==NULL) { 7903 printf("NULL\n"); 7904 return;} 7905 if (decNumberIsNegative(dn)) isign='-'; 7906 printf(" >> %c ", isign); 7907 if (dn->bits&DECSPECIAL) { /* Is a special value */ 7908 if (decNumberIsInfinite(dn)) printf("Infinity"); 7909 else { /* a NaN */ 7910 if (dn->bits&DECSNAN) printf("sNaN"); /* signalling NaN */ 7911 else printf("NaN"); 7912 } 7913 /* if coefficient and exponent are 0, no more to do */ 7914 if (dn->exponent==0 && dn->digits==1 && *dn->lsu==0) { 7915 printf("\n"); 7916 return;} 7917 /* drop through to report other information */ 7918 printf(" "); 7919 } 7920 7921 /* now carefully display the coefficient */ 7922 up=dn->lsu+D2U(dn->digits)-1; /* msu */ 7923 printf("%ld", (LI)*up); 7924 for (up=up-1; up>=dn->lsu; up--) { 7925 u=*up; 7926 printf(":"); 7927 for (cut=DECDPUN-1; cut>=0; cut--) { 7928 d=u/powers[cut]; 7929 u-=d*powers[cut]; 7930 printf("%ld", (LI)d); 7931 } /* cut */ 7932 } /* up */ 7933 if (dn->exponent!=0) { 7934 char esign='+'; 7935 if (dn->exponent<0) esign='-'; 7936 printf(" E%c%ld", esign, (LI)abs(dn->exponent)); 7937 } 7938 printf(" [%ld]\n", (LI)dn->digits); 7939 } /* decNumberShow */ 7940 #endif 7941 7942 #if DECTRACE || DECCHECK 7943 /* ------------------------------------------------------------------ */ 7944 /* decDumpAr -- display a unit array [debug/check aid] */ 7945 /* name is a single-character tag name */ 7946 /* ar is the array to display */ 7947 /* len is the length of the array in Units */ 7948 /* ------------------------------------------------------------------ */ 7949 static void decDumpAr(char name, const Unit *ar, Int len) { 7950 Int i; 7951 const char *spec; 7952 #if DECDPUN==9 7953 spec="%09d "; 7954 #elif DECDPUN==8 7955 spec="%08d "; 7956 #elif DECDPUN==7 7957 spec="%07d "; 7958 #elif DECDPUN==6 7959 spec="%06d "; 7960 #elif DECDPUN==5 7961 spec="%05d "; 7962 #elif DECDPUN==4 7963 spec="%04d "; 7964 #elif DECDPUN==3 7965 spec="%03d "; 7966 #elif DECDPUN==2 7967 spec="%02d "; 7968 #else 7969 spec="%d "; 7970 #endif 7971 printf(" :%c: ", name); 7972 for (i=len-1; i>=0; i--) { 7973 if (i==len-1) printf("%ld ", (LI)ar[i]); 7974 else printf(spec, ar[i]); 7975 } 7976 printf("\n"); 7977 return;} 7978 #endif 7979 7980 #if DECCHECK 7981 /* ------------------------------------------------------------------ */ 7982 /* decCheckOperands -- check operand(s) to a routine */ 7983 /* res is the result structure (not checked; it will be set to */ 7984 /* quiet NaN if error found (and it is not NULL)) */ 7985 /* lhs is the first operand (may be DECUNRESU) */ 7986 /* rhs is the second (may be DECUNUSED) */ 7987 /* set is the context (may be DECUNCONT) */ 7988 /* returns 0 if both operands, and the context are clean, or 1 */ 7989 /* otherwise (in which case the context will show an error, */ 7990 /* unless NULL). Note that res is not cleaned; caller should */ 7991 /* handle this so res=NULL case is safe. */ 7992 /* The caller is expected to abandon immediately if 1 is returned. */ 7993 /* ------------------------------------------------------------------ */ 7994 static Flag decCheckOperands(decNumber *res, const decNumber *lhs, 7995 const decNumber *rhs, decContext *set) { 7996 Flag bad=0; 7997 if (set==NULL) { /* oops; hopeless */ 7998 #if DECTRACE || DECVERB 7999 printf("Reference to context is NULL.\n"); 8000 #endif 8001 bad=1; 8002 return 1;} 8003 else if (set!=DECUNCONT 8004 && (set->digits<1 || set->round>=DEC_ROUND_MAX)) { 8005 bad=1; 8006 #if DECTRACE || DECVERB 8007 printf("Bad context [digits=%ld round=%ld].\n", 8008 (LI)set->digits, (LI)set->round); 8009 #endif 8010 } 8011 else { 8012 if (res==NULL) { 8013 bad=1; 8014 #if DECTRACE 8015 /* this one not DECVERB as standard tests include NULL */ 8016 printf("Reference to result is NULL.\n"); 8017 #endif 8018 } 8019 if (!bad && lhs!=DECUNUSED) bad=(decCheckNumber(lhs)); 8020 if (!bad && rhs!=DECUNUSED) bad=(decCheckNumber(rhs)); 8021 } 8022 if (bad) { 8023 if (set!=DECUNCONT) decContextSetStatus(set, DEC_Invalid_operation); 8024 if (res!=DECUNRESU && res!=NULL) { 8025 decNumberZero(res); 8026 res->bits=DECNAN; /* qNaN */ 8027 } 8028 } 8029 return bad; 8030 } /* decCheckOperands */ 8031 8032 /* ------------------------------------------------------------------ */ 8033 /* decCheckNumber -- check a number */ 8034 /* dn is the number to check */ 8035 /* returns 0 if the number is clean, or 1 otherwise */ 8036 /* */ 8037 /* The number is considered valid if it could be a result from some */ 8038 /* operation in some valid context. */ 8039 /* ------------------------------------------------------------------ */ 8040 static Flag decCheckNumber(const decNumber *dn) { 8041 const Unit *up; /* work */ 8042 uInt maxuint; /* .. */ 8043 Int ae, d, digits; /* .. */ 8044 Int emin, emax; /* .. */ 8045 8046 if (dn==NULL) { /* hopeless */ 8047 #if DECTRACE 8048 /* this one not DECVERB as standard tests include NULL */ 8049 printf("Reference to decNumber is NULL.\n"); 8050 #endif 8051 return 1;} 8052 8053 /* check special values */ 8054 if (dn->bits & DECSPECIAL) { 8055 if (dn->exponent!=0) { 8056 #if DECTRACE || DECVERB 8057 printf("Exponent %ld (not 0) for a special value [%02x].\n", 8058 (LI)dn->exponent, dn->bits); 8059 #endif 8060 return 1;} 8061 8062 /* 2003.09.08: NaNs may now have coefficients, so next tests Inf only */ 8063 if (decNumberIsInfinite(dn)) { 8064 if (dn->digits!=1) { 8065 #if DECTRACE || DECVERB 8066 printf("Digits %ld (not 1) for an infinity.\n", (LI)dn->digits); 8067 #endif 8068 return 1;} 8069 if (*dn->lsu!=0) { 8070 #if DECTRACE || DECVERB 8071 printf("LSU %ld (not 0) for an infinity.\n", (LI)*dn->lsu); 8072 #endif 8073 decDumpAr('I', dn->lsu, D2U(dn->digits)); 8074 return 1;} 8075 } /* Inf */ 8076 /* 2002.12.26: negative NaNs can now appear through proposed IEEE */ 8077 /* concrete formats (decimal64, etc.). */ 8078 return 0; 8079 } 8080 8081 /* check the coefficient */ 8082 if (dn->digits<1 || dn->digits>DECNUMMAXP) { 8083 #if DECTRACE || DECVERB 8084 printf("Digits %ld in number.\n", (LI)dn->digits); 8085 #endif 8086 return 1;} 8087 8088 d=dn->digits; 8089 8090 for (up=dn->lsu; d>0; up++) { 8091 if (d>DECDPUN) maxuint=DECDPUNMAX; 8092 else { /* reached the msu */ 8093 maxuint=powers[d]-1; 8094 if (dn->digits>1 && *up<powers[d-1]) { 8095 #if DECTRACE || DECVERB 8096 printf("Leading 0 in number.\n"); 8097 decNumberShow(dn); 8098 #endif 8099 return 1;} 8100 } 8101 if (*up>maxuint) { 8102 #if DECTRACE || DECVERB 8103 printf("Bad Unit [%08lx] in %ld-digit number at offset %ld [maxuint %ld].\n", 8104 (LI)*up, (LI)dn->digits, (LI)(up-dn->lsu), (LI)maxuint); 8105 #endif 8106 return 1;} 8107 d-=DECDPUN; 8108 } 8109 8110 /* check the exponent. Note that input operands can have exponents */ 8111 /* which are out of the set->emin/set->emax and set->digits range */ 8112 /* (just as they can have more digits than set->digits). */ 8113 ae=dn->exponent+dn->digits-1; /* adjusted exponent */ 8114 emax=DECNUMMAXE; 8115 emin=DECNUMMINE; 8116 digits=DECNUMMAXP; 8117 if (ae<emin-(digits-1)) { 8118 #if DECTRACE || DECVERB 8119 printf("Adjusted exponent underflow [%ld].\n", (LI)ae); 8120 decNumberShow(dn); 8121 #endif 8122 return 1;} 8123 if (ae>+emax) { 8124 #if DECTRACE || DECVERB 8125 printf("Adjusted exponent overflow [%ld].\n", (LI)ae); 8126 decNumberShow(dn); 8127 #endif 8128 return 1;} 8129 8130 return 0; /* it's OK */ 8131 } /* decCheckNumber */ 8132 8133 /* ------------------------------------------------------------------ */ 8134 /* decCheckInexact -- check a normal finite inexact result has digits */ 8135 /* dn is the number to check */ 8136 /* set is the context (for status and precision) */ 8137 /* sets Invalid operation, etc., if some digits are missing */ 8138 /* [this check is not made for DECSUBSET compilation or when */ 8139 /* subnormal is not set] */ 8140 /* ------------------------------------------------------------------ */ 8141 static void decCheckInexact(const decNumber *dn, decContext *set) { 8142 #if !DECSUBSET && DECEXTFLAG 8143 if ((set->status & (DEC_Inexact|DEC_Subnormal))==DEC_Inexact 8144 && (set->digits!=dn->digits) && !(dn->bits & DECSPECIAL)) { 8145 #if DECTRACE || DECVERB 8146 printf("Insufficient digits [%ld] on normal Inexact result.\n", 8147 (LI)dn->digits); 8148 decNumberShow(dn); 8149 #endif 8150 decContextSetStatus(set, DEC_Invalid_operation); 8151 } 8152 #else 8153 /* next is a noop for quiet compiler */ 8154 if (dn!=NULL && dn->digits==0) set->status|=DEC_Invalid_operation; 8155 #endif 8156 return; 8157 } /* decCheckInexact */ 8158 #endif 8159 8160 #if DECALLOC 8161 #undef malloc 8162 #undef free 8163 /* ------------------------------------------------------------------ */ 8164 /* decMalloc -- accountable allocation routine */ 8165 /* n is the number of bytes to allocate */ 8166 /* */ 8167 /* Semantics is the same as the stdlib malloc routine, but bytes */ 8168 /* allocated are accounted for globally, and corruption fences are */ 8169 /* added before and after the 'actual' storage. */ 8170 /* ------------------------------------------------------------------ */ 8171 /* This routine allocates storage with an extra twelve bytes; 8 are */ 8172 /* at the start and hold: */ 8173 /* 0-3 the original length requested */ 8174 /* 4-7 buffer corruption detection fence (DECFENCE, x4) */ 8175 /* The 4 bytes at the end also hold a corruption fence (DECFENCE, x4) */ 8176 /* ------------------------------------------------------------------ */ 8177 static void *decMalloc(size_t n) { 8178 uInt size=n+12; /* true size */ 8179 void *alloc; /* -> allocated storage */ 8180 uInt *j; /* work */ 8181 uByte *b, *b0; /* .. */ 8182 8183 alloc=malloc(size); /* -> allocated storage */ 8184 if (alloc==NULL) return NULL; /* out of strorage */ 8185 b0=(uByte *)alloc; /* as bytes */ 8186 decAllocBytes+=n; /* account for storage */ 8187 j=(uInt *)alloc; /* -> first four bytes */ 8188 *j=n; /* save n */ 8189 /* printf(" alloc ++ dAB: %ld (%d)\n", decAllocBytes, n); */ 8190 for (b=b0+4; b<b0+8; b++) *b=DECFENCE; 8191 for (b=b0+n+8; b<b0+n+12; b++) *b=DECFENCE; 8192 return b0+8; /* -> play area */ 8193 } /* decMalloc */ 8194 8195 /* ------------------------------------------------------------------ */ 8196 /* decFree -- accountable free routine */ 8197 /* alloc is the storage to free */ 8198 /* */ 8199 /* Semantics is the same as the stdlib malloc routine, except that */ 8200 /* the global storage accounting is updated and the fences are */ 8201 /* checked to ensure that no routine has written 'out of bounds'. */ 8202 /* ------------------------------------------------------------------ */ 8203 /* This routine first checks that the fences have not been corrupted. */ 8204 /* It then frees the storage using the 'truw' storage address (that */ 8205 /* is, offset by 8). */ 8206 /* ------------------------------------------------------------------ */ 8207 static void decFree(void *alloc) { 8208 uInt *j, n; /* pointer, original length */ 8209 uByte *b, *b0; /* work */ 8210 8211 if (alloc==NULL) return; /* allowed; it's a nop */ 8212 b0=(uByte *)alloc; /* as bytes */ 8213 b0-=8; /* -> true start of storage */ 8214 j=(uInt *)b0; /* -> first four bytes */ 8215 n=*j; /* lift */ 8216 for (b=b0+4; b<b0+8; b++) if (*b!=DECFENCE) 8217 printf("=== Corrupt byte [%02x] at offset %d from %ld ===\n", *b, 8218 b-b0-8, (Int)b0); 8219 for (b=b0+n+8; b<b0+n+12; b++) if (*b!=DECFENCE) 8220 printf("=== Corrupt byte [%02x] at offset +%d from %ld, n=%ld ===\n", *b, 8221 b-b0-8, (Int)b0, n); 8222 free(b0); /* drop the storage */ 8223 decAllocBytes-=n; /* account for storage */ 8224 /* printf(" free -- dAB: %d (%d)\n", decAllocBytes, -n); */ 8225 } /* decFree */ 8226 #define malloc(a) decMalloc(a) 8227 #define free(a) decFree(a) 8228 #endif 8229