michael@0: /* ------------------------------------------------------------------ */ michael@0: /* Decimal Number arithmetic module */ michael@0: /* ------------------------------------------------------------------ */ michael@0: /* Copyright (c) IBM Corporation, 2000-2012. All rights reserved. */ michael@0: /* */ michael@0: /* This software is made available under the terms of the */ michael@0: /* ICU License -- ICU 1.8.1 and later. */ michael@0: /* */ michael@0: /* The description and User's Guide ("The decNumber C Library") for */ michael@0: /* this software is called decNumber.pdf. This document is */ michael@0: /* available, together with arithmetic and format specifications, */ michael@0: /* testcases, and Web links, on the General Decimal Arithmetic page. */ michael@0: /* */ michael@0: /* Please send comments, suggestions, and corrections to the author: */ michael@0: /* mfc@uk.ibm.com */ michael@0: /* Mike Cowlishaw, IBM Fellow */ michael@0: /* IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK */ michael@0: /* ------------------------------------------------------------------ */ michael@0: michael@0: /* Modified version, for use from within ICU. michael@0: * Renamed public functions, to avoid an unwanted export of the michael@0: * standard names from the ICU library. michael@0: * michael@0: * Use ICU's uprv_malloc() and uprv_free() michael@0: * michael@0: * Revert comment syntax to plain C michael@0: * michael@0: * Remove a few compiler warnings. michael@0: */ michael@0: michael@0: /* This module comprises the routines for arbitrary-precision General */ michael@0: /* Decimal Arithmetic as defined in the specification which may be */ michael@0: /* found on the General Decimal Arithmetic pages. It implements both */ michael@0: /* the full ('extended') arithmetic and the simpler ('subset') */ michael@0: /* arithmetic. */ michael@0: /* */ michael@0: /* Usage notes: */ michael@0: /* */ michael@0: /* 1. This code is ANSI C89 except: */ michael@0: /* */ michael@0: /* a) C99 line comments (double forward slash) are used. (Most C */ michael@0: /* compilers accept these. If yours does not, a simple script */ michael@0: /* can be used to convert them to ANSI C comments.) */ michael@0: /* */ michael@0: /* b) Types from C99 stdint.h are used. If you do not have this */ michael@0: /* header file, see the User's Guide section of the decNumber */ michael@0: /* documentation; this lists the necessary definitions. */ michael@0: /* */ michael@0: /* c) If DECDPUN>4 or DECUSE64=1, the C99 64-bit int64_t and */ michael@0: /* uint64_t types may be used. To avoid these, set DECUSE64=0 */ michael@0: /* and DECDPUN<=4 (see documentation). */ michael@0: /* */ michael@0: /* The code also conforms to C99 restrictions; in particular, */ michael@0: /* strict aliasing rules are observed. */ michael@0: /* */ michael@0: /* 2. The decNumber format which this library uses is optimized for */ michael@0: /* efficient processing of relatively short numbers; in particular */ michael@0: /* it allows the use of fixed sized structures and minimizes copy */ michael@0: /* and move operations. It does, however, support arbitrary */ michael@0: /* precision (up to 999,999,999 digits) and arbitrary exponent */ michael@0: /* range (Emax in the range 0 through 999,999,999 and Emin in the */ michael@0: /* range -999,999,999 through 0). Mathematical functions (for */ michael@0: /* example decNumberExp) as identified below are restricted more */ michael@0: /* tightly: digits, emax, and -emin in the context must be <= */ michael@0: /* DEC_MAX_MATH (999999), and their operand(s) must be within */ michael@0: /* these bounds. */ michael@0: /* */ michael@0: /* 3. Logical functions are further restricted; their operands must */ michael@0: /* be finite, positive, have an exponent of zero, and all digits */ michael@0: /* must be either 0 or 1. The result will only contain digits */ michael@0: /* which are 0 or 1 (and will have exponent=0 and a sign of 0). */ michael@0: /* */ michael@0: /* 4. Operands to operator functions are never modified unless they */ michael@0: /* are also specified to be the result number (which is always */ michael@0: /* permitted). Other than that case, operands must not overlap. */ michael@0: /* */ michael@0: /* 5. Error handling: the type of the error is ORed into the status */ michael@0: /* flags in the current context (decContext structure). The */ michael@0: /* SIGFPE signal is then raised if the corresponding trap-enabler */ michael@0: /* flag in the decContext is set (is 1). */ michael@0: /* */ michael@0: /* It is the responsibility of the caller to clear the status */ michael@0: /* flags as required. */ michael@0: /* */ michael@0: /* The result of any routine which returns a number will always */ michael@0: /* be a valid number (which may be a special value, such as an */ michael@0: /* Infinity or NaN). */ michael@0: /* */ michael@0: /* 6. The decNumber format is not an exchangeable concrete */ michael@0: /* representation as it comprises fields which may be machine- */ michael@0: /* dependent (packed or unpacked, or special length, for example). */ michael@0: /* Canonical conversions to and from strings are provided; other */ michael@0: /* conversions are available in separate modules. */ michael@0: /* */ michael@0: /* 7. Normally, input operands are assumed to be valid. Set DECCHECK */ michael@0: /* to 1 for extended operand checking (including NULL operands). */ michael@0: /* Results are undefined if a badly-formed structure (or a NULL */ michael@0: /* pointer to a structure) is provided, though with DECCHECK */ michael@0: /* enabled the operator routines are protected against exceptions. */ michael@0: /* (Except if the result pointer is NULL, which is unrecoverable.) */ michael@0: /* */ michael@0: /* However, the routines will never cause exceptions if they are */ michael@0: /* given well-formed operands, even if the value of the operands */ michael@0: /* is inappropriate for the operation and DECCHECK is not set. */ michael@0: /* (Except for SIGFPE, as and where documented.) */ michael@0: /* */ michael@0: /* 8. Subset arithmetic is available only if DECSUBSET is set to 1. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: /* Implementation notes for maintenance of this module: */ michael@0: /* */ michael@0: /* 1. Storage leak protection: Routines which use malloc are not */ michael@0: /* permitted to use return for fastpath or error exits (i.e., */ michael@0: /* they follow strict structured programming conventions). */ michael@0: /* Instead they have a do{}while(0); construct surrounding the */ michael@0: /* code which is protected -- break may be used to exit this. */ michael@0: /* Other routines can safely use the return statement inline. */ michael@0: /* */ michael@0: /* Storage leak accounting can be enabled using DECALLOC. */ michael@0: /* */ michael@0: /* 2. All loops use the for(;;) construct. Any do construct does */ michael@0: /* not loop; it is for allocation protection as just described. */ michael@0: /* */ michael@0: /* 3. Setting status in the context must always be the very last */ michael@0: /* action in a routine, as non-0 status may raise a trap and hence */ michael@0: /* the call to set status may not return (if the handler uses long */ michael@0: /* jump). Therefore all cleanup must be done first. In general, */ michael@0: /* to achieve this status is accumulated and is only applied just */ michael@0: /* before return by calling decContextSetStatus (via decStatus). */ michael@0: /* */ michael@0: /* Routines which allocate storage cannot, in general, use the */ michael@0: /* 'top level' routines which could cause a non-returning */ michael@0: /* transfer of control. The decXxxxOp routines are safe (do not */ michael@0: /* call decStatus even if traps are set in the context) and should */ michael@0: /* be used instead (they are also a little faster). */ michael@0: /* */ michael@0: /* 4. Exponent checking is minimized by allowing the exponent to */ michael@0: /* grow outside its limits during calculations, provided that */ michael@0: /* the decFinalize function is called later. Multiplication and */ michael@0: /* division, and intermediate calculations in exponentiation, */ michael@0: /* require more careful checks because of the risk of 31-bit */ michael@0: /* overflow (the most negative valid exponent is -1999999997, for */ michael@0: /* a 999999999-digit number with adjusted exponent of -999999999). */ michael@0: /* */ michael@0: /* 5. Rounding is deferred until finalization of results, with any */ michael@0: /* 'off to the right' data being represented as a single digit */ michael@0: /* residue (in the range -1 through 9). This avoids any double- */ michael@0: /* rounding when more than one shortening takes place (for */ michael@0: /* example, when a result is subnormal). */ michael@0: /* */ michael@0: /* 6. The digits count is allowed to rise to a multiple of DECDPUN */ michael@0: /* during many operations, so whole Units are handled and exact */ michael@0: /* accounting of digits is not needed. The correct digits value */ michael@0: /* is found by decGetDigits, which accounts for leading zeros. */ michael@0: /* This must be called before any rounding if the number of digits */ michael@0: /* is not known exactly. */ michael@0: /* */ michael@0: /* 7. The multiply-by-reciprocal 'trick' is used for partitioning */ michael@0: /* numbers up to four digits, using appropriate constants. This */ michael@0: /* is not useful for longer numbers because overflow of 32 bits */ michael@0: /* would lead to 4 multiplies, which is almost as expensive as */ michael@0: /* a divide (unless a floating-point or 64-bit multiply is */ michael@0: /* assumed to be available). */ michael@0: /* */ michael@0: /* 8. Unusual abbreviations that may be used in the commentary: */ michael@0: /* lhs -- left hand side (operand, of an operation) */ michael@0: /* lsd -- least significant digit (of coefficient) */ michael@0: /* lsu -- least significant Unit (of coefficient) */ michael@0: /* msd -- most significant digit (of coefficient) */ michael@0: /* msi -- most significant item (in an array) */ michael@0: /* msu -- most significant Unit (of coefficient) */ michael@0: /* rhs -- right hand side (operand, of an operation) */ michael@0: /* +ve -- positive */ michael@0: /* -ve -- negative */ michael@0: /* ** -- raise to the power */ michael@0: /* ------------------------------------------------------------------ */ michael@0: michael@0: #include /* for malloc, free, etc. */ michael@0: /* #include */ /* for printf [if needed] */ michael@0: #include /* for strcpy */ michael@0: #include /* for lower */ michael@0: #include "cmemory.h" /* for uprv_malloc, etc., in ICU */ michael@0: #include "decNumber.h" /* base number library */ michael@0: #include "decNumberLocal.h" /* decNumber local types, etc. */ michael@0: #include "uassert.h" michael@0: michael@0: /* Constants */ michael@0: /* Public lookup table used by the D2U macro */ michael@0: static const uByte d2utable[DECMAXD2U+1]=D2UTABLE; michael@0: michael@0: #define DECVERB 1 /* set to 1 for verbose DECCHECK */ michael@0: #define powers DECPOWERS /* old internal name */ michael@0: michael@0: /* Local constants */ michael@0: #define DIVIDE 0x80 /* Divide operators */ michael@0: #define REMAINDER 0x40 /* .. */ michael@0: #define DIVIDEINT 0x20 /* .. */ michael@0: #define REMNEAR 0x10 /* .. */ michael@0: #define COMPARE 0x01 /* Compare operators */ michael@0: #define COMPMAX 0x02 /* .. */ michael@0: #define COMPMIN 0x03 /* .. */ michael@0: #define COMPTOTAL 0x04 /* .. */ michael@0: #define COMPNAN 0x05 /* .. [NaN processing] */ michael@0: #define COMPSIG 0x06 /* .. [signaling COMPARE] */ michael@0: #define COMPMAXMAG 0x07 /* .. */ michael@0: #define COMPMINMAG 0x08 /* .. */ michael@0: michael@0: #define DEC_sNaN 0x40000000 /* local status: sNaN signal */ michael@0: #define BADINT (Int)0x80000000 /* most-negative Int; error indicator */ michael@0: /* Next two indicate an integer >= 10**6, and its parity (bottom bit) */ michael@0: #define BIGEVEN (Int)0x80000002 michael@0: #define BIGODD (Int)0x80000003 michael@0: michael@0: static const Unit uarrone[1]={1}; /* Unit array of 1, used for incrementing */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* round-for-reround digits */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static const uByte DECSTICKYTAB[10]={1,1,2,3,4,6,6,7,8,9}; /* used if sticky */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* Powers of ten (powers[n]==10**n, 0<=n<=9) */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static const uInt DECPOWERS[10]={1, 10, 100, 1000, 10000, 100000, 1000000, michael@0: 10000000, 100000000, 1000000000}; michael@0: michael@0: michael@0: /* Granularity-dependent code */ michael@0: #if DECDPUN<=4 michael@0: #define eInt Int /* extended integer */ michael@0: #define ueInt uInt /* unsigned extended integer */ michael@0: /* Constant multipliers for divide-by-power-of five using reciprocal */ michael@0: /* multiply, after removing powers of 2 by shifting, and final shift */ michael@0: /* of 17 [we only need up to **4] */ michael@0: static const uInt multies[]={131073, 26215, 5243, 1049, 210}; michael@0: /* QUOT10 -- macro to return the quotient of unit u divided by 10**n */ michael@0: #define QUOT10(u, n) ((((uInt)(u)>>(n))*multies[n])>>17) michael@0: #else michael@0: /* For DECDPUN>4 non-ANSI-89 64-bit types are needed. */ michael@0: #if !DECUSE64 michael@0: #error decNumber.c: DECUSE64 must be 1 when DECDPUN>4 michael@0: #endif michael@0: #define eInt Long /* extended integer */ michael@0: #define ueInt uLong /* unsigned extended integer */ michael@0: #endif michael@0: michael@0: /* Local routines */ michael@0: static decNumber * decAddOp(decNumber *, const decNumber *, const decNumber *, michael@0: decContext *, uByte, uInt *); michael@0: static Flag decBiStr(const char *, const char *, const char *); michael@0: static uInt decCheckMath(const decNumber *, decContext *, uInt *); michael@0: static void decApplyRound(decNumber *, decContext *, Int, uInt *); michael@0: static Int decCompare(const decNumber *lhs, const decNumber *rhs, Flag); michael@0: static decNumber * decCompareOp(decNumber *, const decNumber *, michael@0: const decNumber *, decContext *, michael@0: Flag, uInt *); michael@0: static void decCopyFit(decNumber *, const decNumber *, decContext *, michael@0: Int *, uInt *); michael@0: static decNumber * decDecap(decNumber *, Int); michael@0: static decNumber * decDivideOp(decNumber *, const decNumber *, michael@0: const decNumber *, decContext *, Flag, uInt *); michael@0: static decNumber * decExpOp(decNumber *, const decNumber *, michael@0: decContext *, uInt *); michael@0: static void decFinalize(decNumber *, decContext *, Int *, uInt *); michael@0: static Int decGetDigits(Unit *, Int); michael@0: static Int decGetInt(const decNumber *); michael@0: static decNumber * decLnOp(decNumber *, const decNumber *, michael@0: decContext *, uInt *); michael@0: static decNumber * decMultiplyOp(decNumber *, const decNumber *, michael@0: const decNumber *, decContext *, michael@0: uInt *); michael@0: static decNumber * decNaNs(decNumber *, const decNumber *, michael@0: const decNumber *, decContext *, uInt *); michael@0: static decNumber * decQuantizeOp(decNumber *, const decNumber *, michael@0: const decNumber *, decContext *, Flag, michael@0: uInt *); michael@0: static void decReverse(Unit *, Unit *); michael@0: static void decSetCoeff(decNumber *, decContext *, const Unit *, michael@0: Int, Int *, uInt *); michael@0: static void decSetMaxValue(decNumber *, decContext *); michael@0: static void decSetOverflow(decNumber *, decContext *, uInt *); michael@0: static void decSetSubnormal(decNumber *, decContext *, Int *, uInt *); michael@0: static Int decShiftToLeast(Unit *, Int, Int); michael@0: static Int decShiftToMost(Unit *, Int, Int); michael@0: static void decStatus(decNumber *, uInt, decContext *); michael@0: static void decToString(const decNumber *, char[], Flag); michael@0: static decNumber * decTrim(decNumber *, decContext *, Flag, Flag, Int *); michael@0: static Int decUnitAddSub(const Unit *, Int, const Unit *, Int, Int, michael@0: Unit *, Int); michael@0: static Int decUnitCompare(const Unit *, Int, const Unit *, Int, Int); michael@0: michael@0: #if !DECSUBSET michael@0: /* decFinish == decFinalize when no subset arithmetic needed */ michael@0: #define decFinish(a,b,c,d) decFinalize(a,b,c,d) michael@0: #else michael@0: static void decFinish(decNumber *, decContext *, Int *, uInt *); michael@0: static decNumber * decRoundOperand(const decNumber *, decContext *, uInt *); michael@0: #endif michael@0: michael@0: /* Local macros */ michael@0: /* masked special-values bits */ michael@0: #define SPECIALARG (rhs->bits & DECSPECIAL) michael@0: #define SPECIALARGS ((lhs->bits | rhs->bits) & DECSPECIAL) michael@0: michael@0: /* For use in ICU */ michael@0: #define malloc(a) uprv_malloc(a) michael@0: #define free(a) uprv_free(a) michael@0: michael@0: /* Diagnostic macros, etc. */ michael@0: #if DECALLOC michael@0: /* Handle malloc/free accounting. If enabled, our accountable routines */ michael@0: /* are used; otherwise the code just goes straight to the system malloc */ michael@0: /* and free routines. */ michael@0: #define malloc(a) decMalloc(a) michael@0: #define free(a) decFree(a) michael@0: #define DECFENCE 0x5a /* corruption detector */ michael@0: /* 'Our' malloc and free: */ michael@0: static void *decMalloc(size_t); michael@0: static void decFree(void *); michael@0: uInt decAllocBytes=0; /* count of bytes allocated */ michael@0: /* Note that DECALLOC code only checks for storage buffer overflow. */ michael@0: /* To check for memory leaks, the decAllocBytes variable must be */ michael@0: /* checked to be 0 at appropriate times (e.g., after the test */ michael@0: /* harness completes a set of tests). This checking may be unreliable */ michael@0: /* if the testing is done in a multi-thread environment. */ michael@0: #endif michael@0: michael@0: #if DECCHECK michael@0: /* Optional checking routines. Enabling these means that decNumber */ michael@0: /* and decContext operands to operator routines are checked for */ michael@0: /* correctness. This roughly doubles the execution time of the */ michael@0: /* fastest routines (and adds 600+ bytes), so should not normally be */ michael@0: /* used in 'production'. */ michael@0: /* decCheckInexact is used to check that inexact results have a full */ michael@0: /* complement of digits (where appropriate -- this is not the case */ michael@0: /* for Quantize, for example) */ michael@0: #define DECUNRESU ((decNumber *)(void *)0xffffffff) michael@0: #define DECUNUSED ((const decNumber *)(void *)0xffffffff) michael@0: #define DECUNCONT ((decContext *)(void *)(0xffffffff)) michael@0: static Flag decCheckOperands(decNumber *, const decNumber *, michael@0: const decNumber *, decContext *); michael@0: static Flag decCheckNumber(const decNumber *); michael@0: static void decCheckInexact(const decNumber *, decContext *); michael@0: #endif michael@0: michael@0: #if DECTRACE || DECCHECK michael@0: /* Optional trace/debugging routines (may or may not be used) */ michael@0: void decNumberShow(const decNumber *); /* displays the components of a number */ michael@0: static void decDumpAr(char, const Unit *, Int); michael@0: #endif michael@0: michael@0: /* ================================================================== */ michael@0: /* Conversions */ michael@0: /* ================================================================== */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* from-int32 -- conversion from Int or uInt */ michael@0: /* */ michael@0: /* dn is the decNumber to receive the integer */ michael@0: /* in or uin is the integer to be converted */ michael@0: /* returns dn */ michael@0: /* */ michael@0: /* No error is possible. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberFromInt32(decNumber *dn, Int in) { michael@0: uInt unsig; michael@0: if (in>=0) unsig=in; michael@0: else { /* negative (possibly BADINT) */ michael@0: if (in==BADINT) unsig=(uInt)1073741824*2; /* special case */ michael@0: else unsig=-in; /* invert */ michael@0: } michael@0: /* in is now positive */ michael@0: uprv_decNumberFromUInt32(dn, unsig); michael@0: if (in<0) dn->bits=DECNEG; /* sign needed */ michael@0: return dn; michael@0: } /* decNumberFromInt32 */ michael@0: michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberFromUInt32(decNumber *dn, uInt uin) { michael@0: Unit *up; /* work pointer */ michael@0: uprv_decNumberZero(dn); /* clean */ michael@0: if (uin==0) return dn; /* [or decGetDigits bad call] */ michael@0: for (up=dn->lsu; uin>0; up++) { michael@0: *up=(Unit)(uin%(DECDPUNMAX+1)); michael@0: uin=uin/(DECDPUNMAX+1); michael@0: } michael@0: dn->digits=decGetDigits(dn->lsu, up-dn->lsu); michael@0: return dn; michael@0: } /* decNumberFromUInt32 */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* to-int32 -- conversion to Int or uInt */ michael@0: /* */ michael@0: /* dn is the decNumber to convert */ michael@0: /* set is the context for reporting errors */ michael@0: /* returns the converted decNumber, or 0 if Invalid is set */ michael@0: /* */ michael@0: /* Invalid is set if the decNumber does not have exponent==0 or if */ michael@0: /* it is a NaN, Infinite, or out-of-range. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI Int U_EXPORT2 uprv_decNumberToInt32(const decNumber *dn, decContext *set) { michael@0: #if DECCHECK michael@0: if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0; michael@0: #endif michael@0: michael@0: /* special or too many digits, or bad exponent */ michael@0: if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0) ; /* bad */ michael@0: else { /* is a finite integer with 10 or fewer digits */ michael@0: Int d; /* work */ michael@0: const Unit *up; /* .. */ michael@0: uInt hi=0, lo; /* .. */ michael@0: up=dn->lsu; /* -> lsu */ michael@0: lo=*up; /* get 1 to 9 digits */ michael@0: #if DECDPUN>1 /* split to higher */ michael@0: hi=lo/10; michael@0: lo=lo%10; michael@0: #endif michael@0: up++; michael@0: /* collect remaining Units, if any, into hi */ michael@0: for (d=DECDPUN; ddigits; up++, d+=DECDPUN) hi+=*up*powers[d-1]; michael@0: /* now low has the lsd, hi the remainder */ michael@0: if (hi>214748364 || (hi==214748364 && lo>7)) { /* out of range? */ michael@0: /* most-negative is a reprieve */ michael@0: if (dn->bits&DECNEG && hi==214748364 && lo==8) return 0x80000000; michael@0: /* bad -- drop through */ michael@0: } michael@0: else { /* in-range always */ michael@0: Int i=X10(hi)+lo; michael@0: if (dn->bits&DECNEG) return -i; michael@0: return i; michael@0: } michael@0: } /* integer */ michael@0: uprv_decContextSetStatus(set, DEC_Invalid_operation); /* [may not return] */ michael@0: return 0; michael@0: } /* decNumberToInt32 */ michael@0: michael@0: U_CAPI uInt U_EXPORT2 uprv_decNumberToUInt32(const decNumber *dn, decContext *set) { michael@0: #if DECCHECK michael@0: if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0; michael@0: #endif michael@0: /* special or too many digits, or bad exponent, or negative (<0) */ michael@0: if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0 michael@0: || (dn->bits&DECNEG && !ISZERO(dn))); /* bad */ michael@0: else { /* is a finite integer with 10 or fewer digits */ michael@0: Int d; /* work */ michael@0: const Unit *up; /* .. */ michael@0: uInt hi=0, lo; /* .. */ michael@0: up=dn->lsu; /* -> lsu */ michael@0: lo=*up; /* get 1 to 9 digits */ michael@0: #if DECDPUN>1 /* split to higher */ michael@0: hi=lo/10; michael@0: lo=lo%10; michael@0: #endif michael@0: up++; michael@0: /* collect remaining Units, if any, into hi */ michael@0: for (d=DECDPUN; ddigits; up++, d+=DECDPUN) hi+=*up*powers[d-1]; michael@0: michael@0: /* now low has the lsd, hi the remainder */ michael@0: if (hi>429496729 || (hi==429496729 && lo>5)) ; /* no reprieve possible */ michael@0: else return X10(hi)+lo; michael@0: } /* integer */ michael@0: uprv_decContextSetStatus(set, DEC_Invalid_operation); /* [may not return] */ michael@0: return 0; michael@0: } /* decNumberToUInt32 */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* to-scientific-string -- conversion to numeric string */ michael@0: /* to-engineering-string -- conversion to numeric string */ michael@0: /* */ michael@0: /* decNumberToString(dn, string); */ michael@0: /* decNumberToEngString(dn, string); */ michael@0: /* */ michael@0: /* dn is the decNumber to convert */ michael@0: /* string is the string where the result will be laid out */ michael@0: /* */ michael@0: /* string must be at least dn->digits+14 characters long */ michael@0: /* */ michael@0: /* No error is possible, and no status can be set. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI char * U_EXPORT2 uprv_decNumberToString(const decNumber *dn, char *string){ michael@0: decToString(dn, string, 0); michael@0: return string; michael@0: } /* DecNumberToString */ michael@0: michael@0: U_CAPI char * U_EXPORT2 uprv_decNumberToEngString(const decNumber *dn, char *string){ michael@0: decToString(dn, string, 1); michael@0: return string; michael@0: } /* DecNumberToEngString */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* to-number -- conversion from numeric string */ michael@0: /* */ michael@0: /* decNumberFromString -- convert string to decNumber */ michael@0: /* dn -- the number structure to fill */ michael@0: /* chars[] -- the string to convert ('\0' terminated) */ michael@0: /* set -- the context used for processing any error, */ michael@0: /* determining the maximum precision available */ michael@0: /* (set.digits), determining the maximum and minimum */ michael@0: /* exponent (set.emax and set.emin), determining if */ michael@0: /* extended values are allowed, and checking the */ michael@0: /* rounding mode if overflow occurs or rounding is */ michael@0: /* needed. */ michael@0: /* */ michael@0: /* The length of the coefficient and the size of the exponent are */ michael@0: /* checked by this routine, so the correct error (Underflow or */ michael@0: /* Overflow) can be reported or rounding applied, as necessary. */ michael@0: /* */ michael@0: /* If bad syntax is detected, the result will be a quiet NaN. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberFromString(decNumber *dn, const char chars[], michael@0: decContext *set) { michael@0: Int exponent=0; /* working exponent [assume 0] */ michael@0: uByte bits=0; /* working flags [assume +ve] */ michael@0: Unit *res; /* where result will be built */ michael@0: Unit resbuff[SD2U(DECBUFFER+9)];/* local buffer in case need temporary */ michael@0: /* [+9 allows for ln() constants] */ michael@0: Unit *allocres=NULL; /* -> allocated result, iff allocated */ michael@0: Int d=0; /* count of digits found in decimal part */ michael@0: const char *dotchar=NULL; /* where dot was found */ michael@0: const char *cfirst=chars; /* -> first character of decimal part */ michael@0: const char *last=NULL; /* -> last digit of decimal part */ michael@0: const char *c; /* work */ michael@0: Unit *up; /* .. */ michael@0: #if DECDPUN>1 michael@0: Int cut, out; /* .. */ michael@0: #endif michael@0: Int residue; /* rounding residue */ michael@0: uInt status=0; /* error code */ michael@0: michael@0: #if DECCHECK michael@0: if (decCheckOperands(DECUNRESU, DECUNUSED, DECUNUSED, set)) michael@0: return uprv_decNumberZero(dn); michael@0: #endif michael@0: michael@0: do { /* status & malloc protection */ michael@0: for (c=chars;; c++) { /* -> input character */ michael@0: if (*c>='0' && *c<='9') { /* test for Arabic digit */ michael@0: last=c; michael@0: d++; /* count of real digits */ michael@0: continue; /* still in decimal part */ michael@0: } michael@0: if (*c=='.' && dotchar==NULL) { /* first '.' */ michael@0: dotchar=c; /* record offset into decimal part */ michael@0: if (c==cfirst) cfirst++; /* first digit must follow */ michael@0: continue;} michael@0: if (c==chars) { /* first in string... */ michael@0: if (*c=='-') { /* valid - sign */ michael@0: cfirst++; michael@0: bits=DECNEG; michael@0: continue;} michael@0: if (*c=='+') { /* valid + sign */ michael@0: cfirst++; michael@0: continue;} michael@0: } michael@0: /* *c is not a digit, or a valid +, -, or '.' */ michael@0: break; michael@0: } /* c */ michael@0: michael@0: if (last==NULL) { /* no digits yet */ michael@0: status=DEC_Conversion_syntax;/* assume the worst */ michael@0: if (*c=='\0') break; /* and no more to come... */ michael@0: #if DECSUBSET michael@0: /* if subset then infinities and NaNs are not allowed */ michael@0: if (!set->extended) break; /* hopeless */ michael@0: #endif michael@0: /* Infinities and NaNs are possible, here */ michael@0: if (dotchar!=NULL) break; /* .. unless had a dot */ michael@0: uprv_decNumberZero(dn); /* be optimistic */ michael@0: if (decBiStr(c, "infinity", "INFINITY") michael@0: || decBiStr(c, "inf", "INF")) { michael@0: dn->bits=bits | DECINF; michael@0: status=0; /* is OK */ michael@0: break; /* all done */ michael@0: } michael@0: /* a NaN expected */ michael@0: /* 2003.09.10 NaNs are now permitted to have a sign */ michael@0: dn->bits=bits | DECNAN; /* assume simple NaN */ michael@0: if (*c=='s' || *c=='S') { /* looks like an sNaN */ michael@0: c++; michael@0: dn->bits=bits | DECSNAN; michael@0: } michael@0: if (*c!='n' && *c!='N') break; /* check caseless "NaN" */ michael@0: c++; michael@0: if (*c!='a' && *c!='A') break; /* .. */ michael@0: c++; michael@0: if (*c!='n' && *c!='N') break; /* .. */ michael@0: c++; michael@0: /* now either nothing, or nnnn payload, expected */ michael@0: /* -> start of integer and skip leading 0s [including plain 0] */ michael@0: for (cfirst=c; *cfirst=='0';) cfirst++; michael@0: if (*cfirst=='\0') { /* "NaN" or "sNaN", maybe with all 0s */ michael@0: status=0; /* it's good */ michael@0: break; /* .. */ michael@0: } michael@0: /* something other than 0s; setup last and d as usual [no dots] */ michael@0: for (c=cfirst;; c++, d++) { michael@0: if (*c<'0' || *c>'9') break; /* test for Arabic digit */ michael@0: last=c; michael@0: } michael@0: if (*c!='\0') break; /* not all digits */ michael@0: if (d>set->digits-1) { michael@0: /* [NB: payload in a decNumber can be full length unless */ michael@0: /* clamped, in which case can only be digits-1] */ michael@0: if (set->clamp) break; michael@0: if (d>set->digits) break; michael@0: } /* too many digits? */ michael@0: /* good; drop through to convert the integer to coefficient */ michael@0: status=0; /* syntax is OK */ michael@0: bits=dn->bits; /* for copy-back */ michael@0: } /* last==NULL */ michael@0: michael@0: else if (*c!='\0') { /* more to process... */ michael@0: /* had some digits; exponent is only valid sequence now */ michael@0: Flag nege; /* 1=negative exponent */ michael@0: const char *firstexp; /* -> first significant exponent digit */ michael@0: status=DEC_Conversion_syntax;/* assume the worst */ michael@0: if (*c!='e' && *c!='E') break; michael@0: /* Found 'e' or 'E' -- now process explicit exponent */ michael@0: /* 1998.07.11: sign no longer required */ michael@0: nege=0; michael@0: c++; /* to (possible) sign */ michael@0: if (*c=='-') {nege=1; c++;} michael@0: else if (*c=='+') c++; michael@0: if (*c=='\0') break; michael@0: michael@0: for (; *c=='0' && *(c+1)!='\0';) c++; /* strip insignificant zeros */ michael@0: firstexp=c; /* save exponent digit place */ michael@0: for (; ;c++) { michael@0: if (*c<'0' || *c>'9') break; /* not a digit */ michael@0: exponent=X10(exponent)+(Int)*c-(Int)'0'; michael@0: } /* c */ michael@0: /* if not now on a '\0', *c must not be a digit */ michael@0: if (*c!='\0') break; michael@0: michael@0: /* (this next test must be after the syntax checks) */ michael@0: /* if it was too long the exponent may have wrapped, so check */ michael@0: /* carefully and set it to a certain overflow if wrap possible */ michael@0: if (c>=firstexp+9+1) { michael@0: if (c>firstexp+9+1 || *firstexp>'1') exponent=DECNUMMAXE*2; michael@0: /* [up to 1999999999 is OK, for example 1E-1000000998] */ michael@0: } michael@0: if (nege) exponent=-exponent; /* was negative */ michael@0: status=0; /* is OK */ michael@0: } /* stuff after digits */ michael@0: michael@0: /* Here when whole string has been inspected; syntax is good */ michael@0: /* cfirst->first digit (never dot), last->last digit (ditto) */ michael@0: michael@0: /* strip leading zeros/dot [leave final 0 if all 0's] */ michael@0: if (*cfirst=='0') { /* [cfirst has stepped over .] */ michael@0: for (c=cfirst; cextended) { michael@0: uprv_decNumberZero(dn); /* clean result */ michael@0: break; /* [could be return] */ michael@0: } michael@0: #endif michael@0: } /* at least one leading 0 */ michael@0: michael@0: /* Handle decimal point... */ michael@0: if (dotchar!=NULL && dotchardigits) res=dn->lsu; /* fits into supplied decNumber */ michael@0: else { /* rounding needed */ michael@0: Int needbytes=D2U(d)*sizeof(Unit);/* bytes needed */ michael@0: res=resbuff; /* assume use local buffer */ michael@0: if (needbytes>(Int)sizeof(resbuff)) { /* too big for local */ michael@0: allocres=(Unit *)malloc(needbytes); michael@0: if (allocres==NULL) {status|=DEC_Insufficient_storage; break;} michael@0: res=allocres; michael@0: } michael@0: } michael@0: /* res now -> number lsu, buffer, or allocated storage for Unit array */ michael@0: michael@0: /* Place the coefficient into the selected Unit array */ michael@0: /* [this is often 70% of the cost of this function when DECDPUN>1] */ michael@0: #if DECDPUN>1 michael@0: out=0; /* accumulator */ michael@0: up=res+D2U(d)-1; /* -> msu */ michael@0: cut=d-(up-res)*DECDPUN; /* digits in top unit */ michael@0: for (c=cfirst;; c++) { /* along the digits */ michael@0: if (*c=='.') continue; /* ignore '.' [don't decrement cut] */ michael@0: out=X10(out)+(Int)*c-(Int)'0'; michael@0: if (c==last) break; /* done [never get to trailing '.'] */ michael@0: cut--; michael@0: if (cut>0) continue; /* more for this unit */ michael@0: *up=(Unit)out; /* write unit */ michael@0: up--; /* prepare for unit below.. */ michael@0: cut=DECDPUN; /* .. */ michael@0: out=0; /* .. */ michael@0: } /* c */ michael@0: *up=(Unit)out; /* write lsu */ michael@0: michael@0: #else michael@0: /* DECDPUN==1 */ michael@0: up=res; /* -> lsu */ michael@0: for (c=last; c>=cfirst; c--) { /* over each character, from least */ michael@0: if (*c=='.') continue; /* ignore . [don't step up] */ michael@0: *up=(Unit)((Int)*c-(Int)'0'); michael@0: up++; michael@0: } /* c */ michael@0: #endif michael@0: michael@0: dn->bits=bits; michael@0: dn->exponent=exponent; michael@0: dn->digits=d; michael@0: michael@0: /* if not in number (too long) shorten into the number */ michael@0: if (d>set->digits) { michael@0: residue=0; michael@0: decSetCoeff(dn, set, res, d, &residue, &status); michael@0: /* always check for overflow or subnormal and round as needed */ michael@0: decFinalize(dn, set, &residue, &status); michael@0: } michael@0: else { /* no rounding, but may still have overflow or subnormal */ michael@0: /* [these tests are just for performance; finalize repeats them] */ michael@0: if ((dn->exponent-1emin-dn->digits) michael@0: || (dn->exponent-1>set->emax-set->digits)) { michael@0: residue=0; michael@0: decFinalize(dn, set, &residue, &status); michael@0: } michael@0: } michael@0: /* decNumberShow(dn); */ michael@0: } while(0); /* [for break] */ michael@0: michael@0: if (allocres!=NULL) free(allocres); /* drop any storage used */ michael@0: if (status!=0) decStatus(dn, status, set); michael@0: return dn; michael@0: } /* decNumberFromString */ michael@0: michael@0: /* ================================================================== */ michael@0: /* Operators */ michael@0: /* ================================================================== */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberAbs -- absolute value operator */ michael@0: /* */ michael@0: /* This computes C = abs(A) */ michael@0: /* */ michael@0: /* res is C, the result. C may be A */ michael@0: /* rhs is A */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* See also decNumberCopyAbs for a quiet bitwise version of this. */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: /* This has the same effect as decNumberPlus unless A is negative, */ michael@0: /* in which case it has the same effect as decNumberMinus. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberAbs(decNumber *res, const decNumber *rhs, michael@0: decContext *set) { michael@0: decNumber dzero; /* for 0 */ michael@0: uInt status=0; /* accumulator */ michael@0: michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; michael@0: #endif michael@0: michael@0: uprv_decNumberZero(&dzero); /* set 0 */ michael@0: dzero.exponent=rhs->exponent; /* [no coefficient expansion] */ michael@0: decAddOp(res, &dzero, rhs, set, (uByte)(rhs->bits & DECNEG), &status); michael@0: if (status!=0) decStatus(res, status, set); michael@0: #if DECCHECK michael@0: decCheckInexact(res, set); michael@0: #endif michael@0: return res; michael@0: } /* decNumberAbs */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberAdd -- add two Numbers */ michael@0: /* */ michael@0: /* This computes C = A + B */ michael@0: /* */ michael@0: /* res is C, the result. C may be A and/or B (e.g., X=X+X) */ michael@0: /* lhs is A */ michael@0: /* rhs is B */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: /* This just calls the routine shared with Subtract */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberAdd(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set) { michael@0: uInt status=0; /* accumulator */ michael@0: decAddOp(res, lhs, rhs, set, 0, &status); michael@0: if (status!=0) decStatus(res, status, set); michael@0: #if DECCHECK michael@0: decCheckInexact(res, set); michael@0: #endif michael@0: return res; michael@0: } /* decNumberAdd */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberAnd -- AND two Numbers, digitwise */ michael@0: /* */ michael@0: /* This computes C = A & B */ michael@0: /* */ michael@0: /* res is C, the result. C may be A and/or B (e.g., X=X&X) */ michael@0: /* lhs is A */ michael@0: /* rhs is B */ michael@0: /* set is the context (used for result length and error report) */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* */ michael@0: /* Logical function restrictions apply (see above); a NaN is */ michael@0: /* returned with Invalid_operation if a restriction is violated. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberAnd(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set) { michael@0: const Unit *ua, *ub; /* -> operands */ michael@0: const Unit *msua, *msub; /* -> operand msus */ michael@0: Unit *uc, *msuc; /* -> result and its msu */ michael@0: Int msudigs; /* digits in res msu */ michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, lhs, rhs, set)) return res; michael@0: #endif michael@0: michael@0: if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs) michael@0: || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) { michael@0: decStatus(res, DEC_Invalid_operation, set); michael@0: return res; michael@0: } michael@0: michael@0: /* operands are valid */ michael@0: ua=lhs->lsu; /* bottom-up */ michael@0: ub=rhs->lsu; /* .. */ michael@0: uc=res->lsu; /* .. */ michael@0: msua=ua+D2U(lhs->digits)-1; /* -> msu of lhs */ michael@0: msub=ub+D2U(rhs->digits)-1; /* -> msu of rhs */ michael@0: msuc=uc+D2U(set->digits)-1; /* -> msu of result */ michael@0: msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */ michael@0: for (; uc<=msuc; ua++, ub++, uc++) { /* Unit loop */ michael@0: Unit a, b; /* extract units */ michael@0: if (ua>msua) a=0; michael@0: else a=*ua; michael@0: if (ub>msub) b=0; michael@0: else b=*ub; michael@0: *uc=0; /* can now write back */ michael@0: if (a|b) { /* maybe 1 bits to examine */ michael@0: Int i, j; michael@0: *uc=0; /* can now write back */ michael@0: /* This loop could be unrolled and/or use BIN2BCD tables */ michael@0: for (i=0; i1) { michael@0: decStatus(res, DEC_Invalid_operation, set); michael@0: return res; michael@0: } michael@0: if (uc==msuc && i==msudigs-1) break; /* just did final digit */ michael@0: } /* each digit */ michael@0: } /* both OK */ michael@0: } /* each unit */ michael@0: /* [here uc-1 is the msu of the result] */ michael@0: res->digits=decGetDigits(res->lsu, uc-res->lsu); michael@0: res->exponent=0; /* integer */ michael@0: res->bits=0; /* sign=0 */ michael@0: return res; /* [no status to set] */ michael@0: } /* decNumberAnd */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberCompare -- compare two Numbers */ michael@0: /* */ michael@0: /* This computes C = A ? B */ michael@0: /* */ michael@0: /* res is C, the result. C may be A and/or B (e.g., X=X?X) */ michael@0: /* lhs is A */ michael@0: /* rhs is B */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* C must have space for one digit (or NaN). */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberCompare(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set) { michael@0: uInt status=0; /* accumulator */ michael@0: decCompareOp(res, lhs, rhs, set, COMPARE, &status); michael@0: if (status!=0) decStatus(res, status, set); michael@0: return res; michael@0: } /* decNumberCompare */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberCompareSignal -- compare, signalling on all NaNs */ michael@0: /* */ michael@0: /* This computes C = A ? B */ michael@0: /* */ michael@0: /* res is C, the result. C may be A and/or B (e.g., X=X?X) */ michael@0: /* lhs is A */ michael@0: /* rhs is B */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* C must have space for one digit (or NaN). */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberCompareSignal(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set) { michael@0: uInt status=0; /* accumulator */ michael@0: decCompareOp(res, lhs, rhs, set, COMPSIG, &status); michael@0: if (status!=0) decStatus(res, status, set); michael@0: return res; michael@0: } /* decNumberCompareSignal */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberCompareTotal -- compare two Numbers, using total ordering */ michael@0: /* */ michael@0: /* This computes C = A ? B, under total ordering */ michael@0: /* */ michael@0: /* res is C, the result. C may be A and/or B (e.g., X=X?X) */ michael@0: /* lhs is A */ michael@0: /* rhs is B */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* C must have space for one digit; the result will always be one of */ michael@0: /* -1, 0, or 1. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberCompareTotal(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set) { michael@0: uInt status=0; /* accumulator */ michael@0: decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status); michael@0: if (status!=0) decStatus(res, status, set); michael@0: return res; michael@0: } /* decNumberCompareTotal */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberCompareTotalMag -- compare, total ordering of magnitudes */ michael@0: /* */ michael@0: /* This computes C = |A| ? |B|, under total ordering */ michael@0: /* */ michael@0: /* res is C, the result. C may be A and/or B (e.g., X=X?X) */ michael@0: /* lhs is A */ michael@0: /* rhs is B */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* C must have space for one digit; the result will always be one of */ michael@0: /* -1, 0, or 1. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberCompareTotalMag(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set) { michael@0: uInt status=0; /* accumulator */ michael@0: uInt needbytes; /* for space calculations */ michael@0: decNumber bufa[D2N(DECBUFFER+1)];/* +1 in case DECBUFFER=0 */ michael@0: decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */ michael@0: decNumber bufb[D2N(DECBUFFER+1)]; michael@0: decNumber *allocbufb=NULL; /* -> allocated bufb, iff allocated */ michael@0: decNumber *a, *b; /* temporary pointers */ michael@0: michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, lhs, rhs, set)) return res; michael@0: #endif michael@0: michael@0: do { /* protect allocated storage */ michael@0: /* if either is negative, take a copy and absolute */ michael@0: if (decNumberIsNegative(lhs)) { /* lhs<0 */ michael@0: a=bufa; michael@0: needbytes=sizeof(decNumber)+(D2U(lhs->digits)-1)*sizeof(Unit); michael@0: if (needbytes>sizeof(bufa)) { /* need malloc space */ michael@0: allocbufa=(decNumber *)malloc(needbytes); michael@0: if (allocbufa==NULL) { /* hopeless -- abandon */ michael@0: status|=DEC_Insufficient_storage; michael@0: break;} michael@0: a=allocbufa; /* use the allocated space */ michael@0: } michael@0: uprv_decNumberCopy(a, lhs); /* copy content */ michael@0: a->bits&=~DECNEG; /* .. and clear the sign */ michael@0: lhs=a; /* use copy from here on */ michael@0: } michael@0: if (decNumberIsNegative(rhs)) { /* rhs<0 */ michael@0: b=bufb; michael@0: needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit); michael@0: if (needbytes>sizeof(bufb)) { /* need malloc space */ michael@0: allocbufb=(decNumber *)malloc(needbytes); michael@0: if (allocbufb==NULL) { /* hopeless -- abandon */ michael@0: status|=DEC_Insufficient_storage; michael@0: break;} michael@0: b=allocbufb; /* use the allocated space */ michael@0: } michael@0: uprv_decNumberCopy(b, rhs); /* copy content */ michael@0: b->bits&=~DECNEG; /* .. and clear the sign */ michael@0: rhs=b; /* use copy from here on */ michael@0: } michael@0: decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status); michael@0: } while(0); /* end protected */ michael@0: michael@0: if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */ michael@0: if (allocbufb!=NULL) free(allocbufb); /* .. */ michael@0: if (status!=0) decStatus(res, status, set); michael@0: return res; michael@0: } /* decNumberCompareTotalMag */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberDivide -- divide one number by another */ michael@0: /* */ michael@0: /* This computes C = A / B */ michael@0: /* */ michael@0: /* res is C, the result. C may be A and/or B (e.g., X=X/X) */ michael@0: /* lhs is A */ michael@0: /* rhs is B */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberDivide(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set) { michael@0: uInt status=0; /* accumulator */ michael@0: decDivideOp(res, lhs, rhs, set, DIVIDE, &status); michael@0: if (status!=0) decStatus(res, status, set); michael@0: #if DECCHECK michael@0: decCheckInexact(res, set); michael@0: #endif michael@0: return res; michael@0: } /* decNumberDivide */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberDivideInteger -- divide and return integer quotient */ michael@0: /* */ michael@0: /* This computes C = A # B, where # is the integer divide operator */ michael@0: /* */ michael@0: /* res is C, the result. C may be A and/or B (e.g., X=X#X) */ michael@0: /* lhs is A */ michael@0: /* rhs is B */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberDivideInteger(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set) { michael@0: uInt status=0; /* accumulator */ michael@0: decDivideOp(res, lhs, rhs, set, DIVIDEINT, &status); michael@0: if (status!=0) decStatus(res, status, set); michael@0: return res; michael@0: } /* decNumberDivideInteger */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberExp -- exponentiation */ michael@0: /* */ michael@0: /* This computes C = exp(A) */ michael@0: /* */ michael@0: /* res is C, the result. C may be A */ michael@0: /* rhs is A */ michael@0: /* set is the context; note that rounding mode has no effect */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* */ michael@0: /* Mathematical function restrictions apply (see above); a NaN is */ michael@0: /* returned with Invalid_operation if a restriction is violated. */ michael@0: /* */ michael@0: /* Finite results will always be full precision and Inexact, except */ michael@0: /* when A is a zero or -Infinity (giving 1 or 0 respectively). */ michael@0: /* */ michael@0: /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */ michael@0: /* almost always be correctly rounded, but may be up to 1 ulp in */ michael@0: /* error in rare cases. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: /* This is a wrapper for decExpOp which can handle the slightly wider */ michael@0: /* (double) range needed by Ln (which has to be able to calculate */ michael@0: /* exp(-a) where a can be the tiniest number (Ntiny). */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberExp(decNumber *res, const decNumber *rhs, michael@0: decContext *set) { michael@0: uInt status=0; /* accumulator */ michael@0: #if DECSUBSET michael@0: decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */ michael@0: #endif michael@0: michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; michael@0: #endif michael@0: michael@0: /* Check restrictions; these restrictions ensure that if h=8 (see */ michael@0: /* decExpOp) then the result will either overflow or underflow to 0. */ michael@0: /* Other math functions restrict the input range, too, for inverses. */ michael@0: /* If not violated then carry out the operation. */ michael@0: if (!decCheckMath(rhs, set, &status)) do { /* protect allocation */ michael@0: #if DECSUBSET michael@0: if (!set->extended) { michael@0: /* reduce operand and set lostDigits status, as needed */ michael@0: if (rhs->digits>set->digits) { michael@0: allocrhs=decRoundOperand(rhs, set, &status); michael@0: if (allocrhs==NULL) break; michael@0: rhs=allocrhs; michael@0: } michael@0: } michael@0: #endif michael@0: decExpOp(res, rhs, set, &status); michael@0: } while(0); /* end protected */ michael@0: michael@0: #if DECSUBSET michael@0: if (allocrhs !=NULL) free(allocrhs); /* drop any storage used */ michael@0: #endif michael@0: /* apply significant status */ michael@0: if (status!=0) decStatus(res, status, set); michael@0: #if DECCHECK michael@0: decCheckInexact(res, set); michael@0: #endif michael@0: return res; michael@0: } /* decNumberExp */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberFMA -- fused multiply add */ michael@0: /* */ michael@0: /* This computes D = (A * B) + C with only one rounding */ michael@0: /* */ michael@0: /* res is D, the result. D may be A or B or C (e.g., X=FMA(X,X,X)) */ michael@0: /* lhs is A */ michael@0: /* rhs is B */ michael@0: /* fhs is C [far hand side] */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* Mathematical function restrictions apply (see above); a NaN is */ michael@0: /* returned with Invalid_operation if a restriction is violated. */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberFMA(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, const decNumber *fhs, michael@0: decContext *set) { michael@0: uInt status=0; /* accumulator */ michael@0: decContext dcmul; /* context for the multiplication */ michael@0: uInt needbytes; /* for space calculations */ michael@0: decNumber bufa[D2N(DECBUFFER*2+1)]; michael@0: decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */ michael@0: decNumber *acc; /* accumulator pointer */ michael@0: decNumber dzero; /* work */ michael@0: michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, lhs, rhs, set)) return res; michael@0: if (decCheckOperands(res, fhs, DECUNUSED, set)) return res; michael@0: #endif michael@0: michael@0: do { /* protect allocated storage */ michael@0: #if DECSUBSET michael@0: if (!set->extended) { /* [undefined if subset] */ michael@0: status|=DEC_Invalid_operation; michael@0: break;} michael@0: #endif michael@0: /* Check math restrictions [these ensure no overflow or underflow] */ michael@0: if ((!decNumberIsSpecial(lhs) && decCheckMath(lhs, set, &status)) michael@0: || (!decNumberIsSpecial(rhs) && decCheckMath(rhs, set, &status)) michael@0: || (!decNumberIsSpecial(fhs) && decCheckMath(fhs, set, &status))) break; michael@0: /* set up context for multiply */ michael@0: dcmul=*set; michael@0: dcmul.digits=lhs->digits+rhs->digits; /* just enough */ michael@0: /* [The above may be an over-estimate for subset arithmetic, but that's OK] */ michael@0: dcmul.emax=DEC_MAX_EMAX; /* effectively unbounded .. */ michael@0: dcmul.emin=DEC_MIN_EMIN; /* [thanks to Math restrictions] */ michael@0: /* set up decNumber space to receive the result of the multiply */ michael@0: acc=bufa; /* may fit */ michael@0: needbytes=sizeof(decNumber)+(D2U(dcmul.digits)-1)*sizeof(Unit); michael@0: if (needbytes>sizeof(bufa)) { /* need malloc space */ michael@0: allocbufa=(decNumber *)malloc(needbytes); michael@0: if (allocbufa==NULL) { /* hopeless -- abandon */ michael@0: status|=DEC_Insufficient_storage; michael@0: break;} michael@0: acc=allocbufa; /* use the allocated space */ michael@0: } michael@0: /* multiply with extended range and necessary precision */ michael@0: /*printf("emin=%ld\n", dcmul.emin); */ michael@0: decMultiplyOp(acc, lhs, rhs, &dcmul, &status); michael@0: /* Only Invalid operation (from sNaN or Inf * 0) is possible in */ michael@0: /* status; if either is seen than ignore fhs (in case it is */ michael@0: /* another sNaN) and set acc to NaN unless we had an sNaN */ michael@0: /* [decMultiplyOp leaves that to caller] */ michael@0: /* Note sNaN has to go through addOp to shorten payload if */ michael@0: /* necessary */ michael@0: if ((status&DEC_Invalid_operation)!=0) { michael@0: if (!(status&DEC_sNaN)) { /* but be true invalid */ michael@0: uprv_decNumberZero(res); /* acc not yet set */ michael@0: res->bits=DECNAN; michael@0: break; michael@0: } michael@0: uprv_decNumberZero(&dzero); /* make 0 (any non-NaN would do) */ michael@0: fhs=&dzero; /* use that */ michael@0: } michael@0: #if DECCHECK michael@0: else { /* multiply was OK */ michael@0: if (status!=0) printf("Status=%08lx after FMA multiply\n", (LI)status); michael@0: } michael@0: #endif michael@0: /* add the third operand and result -> res, and all is done */ michael@0: decAddOp(res, acc, fhs, set, 0, &status); michael@0: } while(0); /* end protected */ michael@0: michael@0: if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */ michael@0: if (status!=0) decStatus(res, status, set); michael@0: #if DECCHECK michael@0: decCheckInexact(res, set); michael@0: #endif michael@0: return res; michael@0: } /* decNumberFMA */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberInvert -- invert a Number, digitwise */ michael@0: /* */ michael@0: /* This computes C = ~A */ michael@0: /* */ michael@0: /* res is C, the result. C may be A (e.g., X=~X) */ michael@0: /* rhs is A */ michael@0: /* set is the context (used for result length and error report) */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* */ michael@0: /* Logical function restrictions apply (see above); a NaN is */ michael@0: /* returned with Invalid_operation if a restriction is violated. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberInvert(decNumber *res, const decNumber *rhs, michael@0: decContext *set) { michael@0: const Unit *ua, *msua; /* -> operand and its msu */ michael@0: Unit *uc, *msuc; /* -> result and its msu */ michael@0: Int msudigs; /* digits in res msu */ michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; michael@0: #endif michael@0: michael@0: if (rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) { michael@0: decStatus(res, DEC_Invalid_operation, set); michael@0: return res; michael@0: } michael@0: /* operand is valid */ michael@0: ua=rhs->lsu; /* bottom-up */ michael@0: uc=res->lsu; /* .. */ michael@0: msua=ua+D2U(rhs->digits)-1; /* -> msu of rhs */ michael@0: msuc=uc+D2U(set->digits)-1; /* -> msu of result */ michael@0: msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */ michael@0: for (; uc<=msuc; ua++, uc++) { /* Unit loop */ michael@0: Unit a; /* extract unit */ michael@0: Int i, j; /* work */ michael@0: if (ua>msua) a=0; michael@0: else a=*ua; michael@0: *uc=0; /* can now write back */ michael@0: /* always need to examine all bits in rhs */ michael@0: /* This loop could be unrolled and/or use BIN2BCD tables */ michael@0: for (i=0; i1) { michael@0: decStatus(res, DEC_Invalid_operation, set); michael@0: return res; michael@0: } michael@0: if (uc==msuc && i==msudigs-1) break; /* just did final digit */ michael@0: } /* each digit */ michael@0: } /* each unit */ michael@0: /* [here uc-1 is the msu of the result] */ michael@0: res->digits=decGetDigits(res->lsu, uc-res->lsu); michael@0: res->exponent=0; /* integer */ michael@0: res->bits=0; /* sign=0 */ michael@0: return res; /* [no status to set] */ michael@0: } /* decNumberInvert */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberLn -- natural logarithm */ michael@0: /* */ michael@0: /* This computes C = ln(A) */ michael@0: /* */ michael@0: /* res is C, the result. C may be A */ michael@0: /* rhs is A */ michael@0: /* set is the context; note that rounding mode has no effect */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* */ michael@0: /* Notable cases: */ michael@0: /* A<0 -> Invalid */ michael@0: /* A=0 -> -Infinity (Exact) */ michael@0: /* A=+Infinity -> +Infinity (Exact) */ michael@0: /* A=1 exactly -> 0 (Exact) */ michael@0: /* */ michael@0: /* Mathematical function restrictions apply (see above); a NaN is */ michael@0: /* returned with Invalid_operation if a restriction is violated. */ michael@0: /* */ michael@0: /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */ michael@0: /* almost always be correctly rounded, but may be up to 1 ulp in */ michael@0: /* error in rare cases. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: /* This is a wrapper for decLnOp which can handle the slightly wider */ michael@0: /* (+11) range needed by Ln, Log10, etc. (which may have to be able */ michael@0: /* to calculate at p+e+2). */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberLn(decNumber *res, const decNumber *rhs, michael@0: decContext *set) { michael@0: uInt status=0; /* accumulator */ michael@0: #if DECSUBSET michael@0: decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */ michael@0: #endif michael@0: michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; michael@0: #endif michael@0: michael@0: /* Check restrictions; this is a math function; if not violated */ michael@0: /* then carry out the operation. */ michael@0: if (!decCheckMath(rhs, set, &status)) do { /* protect allocation */ michael@0: #if DECSUBSET michael@0: if (!set->extended) { michael@0: /* reduce operand and set lostDigits status, as needed */ michael@0: if (rhs->digits>set->digits) { michael@0: allocrhs=decRoundOperand(rhs, set, &status); michael@0: if (allocrhs==NULL) break; michael@0: rhs=allocrhs; michael@0: } michael@0: /* special check in subset for rhs=0 */ michael@0: if (ISZERO(rhs)) { /* +/- zeros -> error */ michael@0: status|=DEC_Invalid_operation; michael@0: break;} michael@0: } /* extended=0 */ michael@0: #endif michael@0: decLnOp(res, rhs, set, &status); michael@0: } while(0); /* end protected */ michael@0: michael@0: #if DECSUBSET michael@0: if (allocrhs !=NULL) free(allocrhs); /* drop any storage used */ michael@0: #endif michael@0: /* apply significant status */ michael@0: if (status!=0) decStatus(res, status, set); michael@0: #if DECCHECK michael@0: decCheckInexact(res, set); michael@0: #endif michael@0: return res; michael@0: } /* decNumberLn */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberLogB - get adjusted exponent, by 754 rules */ michael@0: /* */ michael@0: /* This computes C = adjustedexponent(A) */ michael@0: /* */ michael@0: /* res is C, the result. C may be A */ michael@0: /* rhs is A */ michael@0: /* set is the context, used only for digits and status */ michael@0: /* */ michael@0: /* C must have space for 10 digits (A might have 10**9 digits and */ michael@0: /* an exponent of +999999999, or one digit and an exponent of */ michael@0: /* -1999999999). */ michael@0: /* */ michael@0: /* This returns the adjusted exponent of A after (in theory) padding */ michael@0: /* with zeros on the right to set->digits digits while keeping the */ michael@0: /* same value. The exponent is not limited by emin/emax. */ michael@0: /* */ michael@0: /* Notable cases: */ michael@0: /* A<0 -> Use |A| */ michael@0: /* A=0 -> -Infinity (Division by zero) */ michael@0: /* A=Infinite -> +Infinity (Exact) */ michael@0: /* A=1 exactly -> 0 (Exact) */ michael@0: /* NaNs are propagated as usual */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberLogB(decNumber *res, const decNumber *rhs, michael@0: decContext *set) { michael@0: uInt status=0; /* accumulator */ michael@0: michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; michael@0: #endif michael@0: michael@0: /* NaNs as usual; Infinities return +Infinity; 0->oops */ michael@0: if (decNumberIsNaN(rhs)) decNaNs(res, rhs, NULL, set, &status); michael@0: else if (decNumberIsInfinite(rhs)) uprv_decNumberCopyAbs(res, rhs); michael@0: else if (decNumberIsZero(rhs)) { michael@0: uprv_decNumberZero(res); /* prepare for Infinity */ michael@0: res->bits=DECNEG|DECINF; /* -Infinity */ michael@0: status|=DEC_Division_by_zero; /* as per 754 */ michael@0: } michael@0: else { /* finite non-zero */ michael@0: Int ae=rhs->exponent+rhs->digits-1; /* adjusted exponent */ michael@0: uprv_decNumberFromInt32(res, ae); /* lay it out */ michael@0: } michael@0: michael@0: if (status!=0) decStatus(res, status, set); michael@0: return res; michael@0: } /* decNumberLogB */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberLog10 -- logarithm in base 10 */ michael@0: /* */ michael@0: /* This computes C = log10(A) */ michael@0: /* */ michael@0: /* res is C, the result. C may be A */ michael@0: /* rhs is A */ michael@0: /* set is the context; note that rounding mode has no effect */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* */ michael@0: /* Notable cases: */ michael@0: /* A<0 -> Invalid */ michael@0: /* A=0 -> -Infinity (Exact) */ michael@0: /* A=+Infinity -> +Infinity (Exact) */ michael@0: /* A=10**n (if n is an integer) -> n (Exact) */ michael@0: /* */ michael@0: /* Mathematical function restrictions apply (see above); a NaN is */ michael@0: /* returned with Invalid_operation if a restriction is violated. */ michael@0: /* */ michael@0: /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */ michael@0: /* almost always be correctly rounded, but may be up to 1 ulp in */ michael@0: /* error in rare cases. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: /* This calculates ln(A)/ln(10) using appropriate precision. For */ michael@0: /* ln(A) this is the max(p, rhs->digits + t) + 3, where p is the */ michael@0: /* requested digits and t is the number of digits in the exponent */ michael@0: /* (maximum 6). For ln(10) it is p + 3; this is often handled by the */ michael@0: /* fastpath in decLnOp. The final division is done to the requested */ michael@0: /* precision. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: #if defined(__clang__) || U_GCC_MAJOR_MINOR >= 406 michael@0: #pragma GCC diagnostic push michael@0: #pragma GCC diagnostic ignored "-Warray-bounds" michael@0: #endif michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberLog10(decNumber *res, const decNumber *rhs, michael@0: decContext *set) { michael@0: uInt status=0, ignore=0; /* status accumulators */ michael@0: uInt needbytes; /* for space calculations */ michael@0: Int p; /* working precision */ michael@0: Int t; /* digits in exponent of A */ michael@0: michael@0: /* buffers for a and b working decimals */ michael@0: /* (adjustment calculator, same size) */ michael@0: decNumber bufa[D2N(DECBUFFER+2)]; michael@0: decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */ michael@0: decNumber *a=bufa; /* temporary a */ michael@0: decNumber bufb[D2N(DECBUFFER+2)]; michael@0: decNumber *allocbufb=NULL; /* -> allocated bufb, iff allocated */ michael@0: decNumber *b=bufb; /* temporary b */ michael@0: decNumber bufw[D2N(10)]; /* working 2-10 digit number */ michael@0: decNumber *w=bufw; /* .. */ michael@0: #if DECSUBSET michael@0: decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */ michael@0: #endif michael@0: michael@0: decContext aset; /* working context */ michael@0: michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; michael@0: #endif michael@0: michael@0: /* Check restrictions; this is a math function; if not violated */ michael@0: /* then carry out the operation. */ michael@0: if (!decCheckMath(rhs, set, &status)) do { /* protect malloc */ michael@0: #if DECSUBSET michael@0: if (!set->extended) { michael@0: /* reduce operand and set lostDigits status, as needed */ michael@0: if (rhs->digits>set->digits) { michael@0: allocrhs=decRoundOperand(rhs, set, &status); michael@0: if (allocrhs==NULL) break; michael@0: rhs=allocrhs; michael@0: } michael@0: /* special check in subset for rhs=0 */ michael@0: if (ISZERO(rhs)) { /* +/- zeros -> error */ michael@0: status|=DEC_Invalid_operation; michael@0: break;} michael@0: } /* extended=0 */ michael@0: #endif michael@0: michael@0: uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64); /* clean context */ michael@0: michael@0: /* handle exact powers of 10; only check if +ve finite */ michael@0: if (!(rhs->bits&(DECNEG|DECSPECIAL)) && !ISZERO(rhs)) { michael@0: Int residue=0; /* (no residue) */ michael@0: uInt copystat=0; /* clean status */ michael@0: michael@0: /* round to a single digit... */ michael@0: aset.digits=1; michael@0: decCopyFit(w, rhs, &aset, &residue, ©stat); /* copy & shorten */ michael@0: /* if exact and the digit is 1, rhs is a power of 10 */ michael@0: if (!(copystat&DEC_Inexact) && w->lsu[0]==1) { michael@0: /* the exponent, conveniently, is the power of 10; making */ michael@0: /* this the result needs a little care as it might not fit, */ michael@0: /* so first convert it into the working number, and then move */ michael@0: /* to res */ michael@0: uprv_decNumberFromInt32(w, w->exponent); michael@0: residue=0; michael@0: decCopyFit(res, w, set, &residue, &status); /* copy & round */ michael@0: decFinish(res, set, &residue, &status); /* cleanup/set flags */ michael@0: break; michael@0: } /* not a power of 10 */ michael@0: } /* not a candidate for exact */ michael@0: michael@0: /* simplify the information-content calculation to use 'total */ michael@0: /* number of digits in a, including exponent' as compared to the */ michael@0: /* requested digits, as increasing this will only rarely cost an */ michael@0: /* iteration in ln(a) anyway */ michael@0: t=6; /* it can never be >6 */ michael@0: michael@0: /* allocate space when needed... */ michael@0: p=(rhs->digits+t>set->digits?rhs->digits+t:set->digits)+3; michael@0: needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit); michael@0: if (needbytes>sizeof(bufa)) { /* need malloc space */ michael@0: allocbufa=(decNumber *)malloc(needbytes); michael@0: if (allocbufa==NULL) { /* hopeless -- abandon */ michael@0: status|=DEC_Insufficient_storage; michael@0: break;} michael@0: a=allocbufa; /* use the allocated space */ michael@0: } michael@0: aset.digits=p; /* as calculated */ michael@0: aset.emax=DEC_MAX_MATH; /* usual bounds */ michael@0: aset.emin=-DEC_MAX_MATH; /* .. */ michael@0: aset.clamp=0; /* and no concrete format */ michael@0: decLnOp(a, rhs, &aset, &status); /* a=ln(rhs) */ michael@0: michael@0: /* skip the division if the result so far is infinite, NaN, or */ michael@0: /* zero, or there was an error; note NaN from sNaN needs copy */ michael@0: if (status&DEC_NaNs && !(status&DEC_sNaN)) break; michael@0: if (a->bits&DECSPECIAL || ISZERO(a)) { michael@0: uprv_decNumberCopy(res, a); /* [will fit] */ michael@0: break;} michael@0: michael@0: /* for ln(10) an extra 3 digits of precision are needed */ michael@0: p=set->digits+3; michael@0: needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit); michael@0: if (needbytes>sizeof(bufb)) { /* need malloc space */ michael@0: allocbufb=(decNumber *)malloc(needbytes); michael@0: if (allocbufb==NULL) { /* hopeless -- abandon */ michael@0: status|=DEC_Insufficient_storage; michael@0: break;} michael@0: b=allocbufb; /* use the allocated space */ michael@0: } michael@0: uprv_decNumberZero(w); /* set up 10... */ michael@0: #if DECDPUN==1 michael@0: w->lsu[1]=1; w->lsu[0]=0; /* .. */ michael@0: #else michael@0: w->lsu[0]=10; /* .. */ michael@0: #endif michael@0: w->digits=2; /* .. */ michael@0: michael@0: aset.digits=p; michael@0: decLnOp(b, w, &aset, &ignore); /* b=ln(10) */ michael@0: michael@0: aset.digits=set->digits; /* for final divide */ michael@0: decDivideOp(res, a, b, &aset, DIVIDE, &status); /* into result */ michael@0: } while(0); /* [for break] */ michael@0: michael@0: if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */ michael@0: if (allocbufb!=NULL) free(allocbufb); /* .. */ michael@0: #if DECSUBSET michael@0: if (allocrhs !=NULL) free(allocrhs); /* .. */ michael@0: #endif michael@0: /* apply significant status */ michael@0: if (status!=0) decStatus(res, status, set); michael@0: #if DECCHECK michael@0: decCheckInexact(res, set); michael@0: #endif michael@0: return res; michael@0: } /* decNumberLog10 */ michael@0: #if defined(__clang__) || U_GCC_MAJOR_MINOR >= 406 michael@0: #pragma GCC diagnostic pop michael@0: #endif michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberMax -- compare two Numbers and return the maximum */ michael@0: /* */ michael@0: /* This computes C = A ? B, returning the maximum by 754 rules */ michael@0: /* */ michael@0: /* res is C, the result. C may be A and/or B (e.g., X=X?X) */ michael@0: /* lhs is A */ michael@0: /* rhs is B */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberMax(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set) { michael@0: uInt status=0; /* accumulator */ michael@0: decCompareOp(res, lhs, rhs, set, COMPMAX, &status); michael@0: if (status!=0) decStatus(res, status, set); michael@0: #if DECCHECK michael@0: decCheckInexact(res, set); michael@0: #endif michael@0: return res; michael@0: } /* decNumberMax */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberMaxMag -- compare and return the maximum by magnitude */ michael@0: /* */ michael@0: /* This computes C = A ? B, returning the maximum by 754 rules */ michael@0: /* */ michael@0: /* res is C, the result. C may be A and/or B (e.g., X=X?X) */ michael@0: /* lhs is A */ michael@0: /* rhs is B */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberMaxMag(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set) { michael@0: uInt status=0; /* accumulator */ michael@0: decCompareOp(res, lhs, rhs, set, COMPMAXMAG, &status); michael@0: if (status!=0) decStatus(res, status, set); michael@0: #if DECCHECK michael@0: decCheckInexact(res, set); michael@0: #endif michael@0: return res; michael@0: } /* decNumberMaxMag */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberMin -- compare two Numbers and return the minimum */ michael@0: /* */ michael@0: /* This computes C = A ? B, returning the minimum by 754 rules */ michael@0: /* */ michael@0: /* res is C, the result. C may be A and/or B (e.g., X=X?X) */ michael@0: /* lhs is A */ michael@0: /* rhs is B */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberMin(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set) { michael@0: uInt status=0; /* accumulator */ michael@0: decCompareOp(res, lhs, rhs, set, COMPMIN, &status); michael@0: if (status!=0) decStatus(res, status, set); michael@0: #if DECCHECK michael@0: decCheckInexact(res, set); michael@0: #endif michael@0: return res; michael@0: } /* decNumberMin */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberMinMag -- compare and return the minimum by magnitude */ michael@0: /* */ michael@0: /* This computes C = A ? B, returning the minimum by 754 rules */ michael@0: /* */ michael@0: /* res is C, the result. C may be A and/or B (e.g., X=X?X) */ michael@0: /* lhs is A */ michael@0: /* rhs is B */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberMinMag(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set) { michael@0: uInt status=0; /* accumulator */ michael@0: decCompareOp(res, lhs, rhs, set, COMPMINMAG, &status); michael@0: if (status!=0) decStatus(res, status, set); michael@0: #if DECCHECK michael@0: decCheckInexact(res, set); michael@0: #endif michael@0: return res; michael@0: } /* decNumberMinMag */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberMinus -- prefix minus operator */ michael@0: /* */ michael@0: /* This computes C = 0 - A */ michael@0: /* */ michael@0: /* res is C, the result. C may be A */ michael@0: /* rhs is A */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* See also decNumberCopyNegate for a quiet bitwise version of this. */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: /* Simply use AddOp for the subtract, which will do the necessary. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberMinus(decNumber *res, const decNumber *rhs, michael@0: decContext *set) { michael@0: decNumber dzero; michael@0: uInt status=0; /* accumulator */ michael@0: michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; michael@0: #endif michael@0: michael@0: uprv_decNumberZero(&dzero); /* make 0 */ michael@0: dzero.exponent=rhs->exponent; /* [no coefficient expansion] */ michael@0: decAddOp(res, &dzero, rhs, set, DECNEG, &status); michael@0: if (status!=0) decStatus(res, status, set); michael@0: #if DECCHECK michael@0: decCheckInexact(res, set); michael@0: #endif michael@0: return res; michael@0: } /* decNumberMinus */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberNextMinus -- next towards -Infinity */ michael@0: /* */ michael@0: /* This computes C = A - infinitesimal, rounded towards -Infinity */ michael@0: /* */ michael@0: /* res is C, the result. C may be A */ michael@0: /* rhs is A */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* This is a generalization of 754 NextDown. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberNextMinus(decNumber *res, const decNumber *rhs, michael@0: decContext *set) { michael@0: decNumber dtiny; /* constant */ michael@0: decContext workset=*set; /* work */ michael@0: uInt status=0; /* accumulator */ michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; michael@0: #endif michael@0: michael@0: /* +Infinity is the special case */ michael@0: if ((rhs->bits&(DECINF|DECNEG))==DECINF) { michael@0: decSetMaxValue(res, set); /* is +ve */ michael@0: /* there is no status to set */ michael@0: return res; michael@0: } michael@0: uprv_decNumberZero(&dtiny); /* start with 0 */ michael@0: dtiny.lsu[0]=1; /* make number that is .. */ michael@0: dtiny.exponent=DEC_MIN_EMIN-1; /* .. smaller than tiniest */ michael@0: workset.round=DEC_ROUND_FLOOR; michael@0: decAddOp(res, rhs, &dtiny, &workset, DECNEG, &status); michael@0: status&=DEC_Invalid_operation|DEC_sNaN; /* only sNaN Invalid please */ michael@0: if (status!=0) decStatus(res, status, set); michael@0: return res; michael@0: } /* decNumberNextMinus */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberNextPlus -- next towards +Infinity */ michael@0: /* */ michael@0: /* This computes C = A + infinitesimal, rounded towards +Infinity */ michael@0: /* */ michael@0: /* res is C, the result. C may be A */ michael@0: /* rhs is A */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* This is a generalization of 754 NextUp. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberNextPlus(decNumber *res, const decNumber *rhs, michael@0: decContext *set) { michael@0: decNumber dtiny; /* constant */ michael@0: decContext workset=*set; /* work */ michael@0: uInt status=0; /* accumulator */ michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; michael@0: #endif michael@0: michael@0: /* -Infinity is the special case */ michael@0: if ((rhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) { michael@0: decSetMaxValue(res, set); michael@0: res->bits=DECNEG; /* negative */ michael@0: /* there is no status to set */ michael@0: return res; michael@0: } michael@0: uprv_decNumberZero(&dtiny); /* start with 0 */ michael@0: dtiny.lsu[0]=1; /* make number that is .. */ michael@0: dtiny.exponent=DEC_MIN_EMIN-1; /* .. smaller than tiniest */ michael@0: workset.round=DEC_ROUND_CEILING; michael@0: decAddOp(res, rhs, &dtiny, &workset, 0, &status); michael@0: status&=DEC_Invalid_operation|DEC_sNaN; /* only sNaN Invalid please */ michael@0: if (status!=0) decStatus(res, status, set); michael@0: return res; michael@0: } /* decNumberNextPlus */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberNextToward -- next towards rhs */ michael@0: /* */ michael@0: /* This computes C = A +/- infinitesimal, rounded towards */ michael@0: /* +/-Infinity in the direction of B, as per 754-1985 nextafter */ michael@0: /* modified during revision but dropped from 754-2008. */ michael@0: /* */ michael@0: /* res is C, the result. C may be A or B. */ michael@0: /* lhs is A */ michael@0: /* rhs is B */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* This is a generalization of 754-1985 NextAfter. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberNextToward(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set) { michael@0: decNumber dtiny; /* constant */ michael@0: decContext workset=*set; /* work */ michael@0: Int result; /* .. */ michael@0: uInt status=0; /* accumulator */ michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, lhs, rhs, set)) return res; michael@0: #endif michael@0: michael@0: if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) { michael@0: decNaNs(res, lhs, rhs, set, &status); michael@0: } michael@0: else { /* Is numeric, so no chance of sNaN Invalid, etc. */ michael@0: result=decCompare(lhs, rhs, 0); /* sign matters */ michael@0: if (result==BADINT) status|=DEC_Insufficient_storage; /* rare */ michael@0: else { /* valid compare */ michael@0: if (result==0) uprv_decNumberCopySign(res, lhs, rhs); /* easy */ michael@0: else { /* differ: need NextPlus or NextMinus */ michael@0: uByte sub; /* add or subtract */ michael@0: if (result<0) { /* lhsbits&(DECINF|DECNEG))==(DECINF|DECNEG)) { michael@0: decSetMaxValue(res, set); michael@0: res->bits=DECNEG; /* negative */ michael@0: return res; /* there is no status to set */ michael@0: } michael@0: workset.round=DEC_ROUND_CEILING; michael@0: sub=0; /* add, please */ michael@0: } /* plus */ michael@0: else { /* lhs>rhs, do nextminus */ michael@0: /* +Infinity is the special case */ michael@0: if ((lhs->bits&(DECINF|DECNEG))==DECINF) { michael@0: decSetMaxValue(res, set); michael@0: return res; /* there is no status to set */ michael@0: } michael@0: workset.round=DEC_ROUND_FLOOR; michael@0: sub=DECNEG; /* subtract, please */ michael@0: } /* minus */ michael@0: uprv_decNumberZero(&dtiny); /* start with 0 */ michael@0: dtiny.lsu[0]=1; /* make number that is .. */ michael@0: dtiny.exponent=DEC_MIN_EMIN-1; /* .. smaller than tiniest */ michael@0: decAddOp(res, lhs, &dtiny, &workset, sub, &status); /* + or - */ michael@0: /* turn off exceptions if the result is a normal number */ michael@0: /* (including Nmin), otherwise let all status through */ michael@0: if (uprv_decNumberIsNormal(res, set)) status=0; michael@0: } /* unequal */ michael@0: } /* compare OK */ michael@0: } /* numeric */ michael@0: if (status!=0) decStatus(res, status, set); michael@0: return res; michael@0: } /* decNumberNextToward */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberOr -- OR two Numbers, digitwise */ michael@0: /* */ michael@0: /* This computes C = A | B */ michael@0: /* */ michael@0: /* res is C, the result. C may be A and/or B (e.g., X=X|X) */ michael@0: /* lhs is A */ michael@0: /* rhs is B */ michael@0: /* set is the context (used for result length and error report) */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* */ michael@0: /* Logical function restrictions apply (see above); a NaN is */ michael@0: /* returned with Invalid_operation if a restriction is violated. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberOr(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set) { michael@0: const Unit *ua, *ub; /* -> operands */ michael@0: const Unit *msua, *msub; /* -> operand msus */ michael@0: Unit *uc, *msuc; /* -> result and its msu */ michael@0: Int msudigs; /* digits in res msu */ michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, lhs, rhs, set)) return res; michael@0: #endif michael@0: michael@0: if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs) michael@0: || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) { michael@0: decStatus(res, DEC_Invalid_operation, set); michael@0: return res; michael@0: } michael@0: /* operands are valid */ michael@0: ua=lhs->lsu; /* bottom-up */ michael@0: ub=rhs->lsu; /* .. */ michael@0: uc=res->lsu; /* .. */ michael@0: msua=ua+D2U(lhs->digits)-1; /* -> msu of lhs */ michael@0: msub=ub+D2U(rhs->digits)-1; /* -> msu of rhs */ michael@0: msuc=uc+D2U(set->digits)-1; /* -> msu of result */ michael@0: msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */ michael@0: for (; uc<=msuc; ua++, ub++, uc++) { /* Unit loop */ michael@0: Unit a, b; /* extract units */ michael@0: if (ua>msua) a=0; michael@0: else a=*ua; michael@0: if (ub>msub) b=0; michael@0: else b=*ub; michael@0: *uc=0; /* can now write back */ michael@0: if (a|b) { /* maybe 1 bits to examine */ michael@0: Int i, j; michael@0: /* This loop could be unrolled and/or use BIN2BCD tables */ michael@0: for (i=0; i1) { michael@0: decStatus(res, DEC_Invalid_operation, set); michael@0: return res; michael@0: } michael@0: if (uc==msuc && i==msudigs-1) break; /* just did final digit */ michael@0: } /* each digit */ michael@0: } /* non-zero */ michael@0: } /* each unit */ michael@0: /* [here uc-1 is the msu of the result] */ michael@0: res->digits=decGetDigits(res->lsu, uc-res->lsu); michael@0: res->exponent=0; /* integer */ michael@0: res->bits=0; /* sign=0 */ michael@0: return res; /* [no status to set] */ michael@0: } /* decNumberOr */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberPlus -- prefix plus operator */ michael@0: /* */ michael@0: /* This computes C = 0 + A */ michael@0: /* */ michael@0: /* res is C, the result. C may be A */ michael@0: /* rhs is A */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* See also decNumberCopy for a quiet bitwise version of this. */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: /* This simply uses AddOp; Add will take fast path after preparing A. */ michael@0: /* Performance is a concern here, as this routine is often used to */ michael@0: /* check operands and apply rounding and overflow/underflow testing. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberPlus(decNumber *res, const decNumber *rhs, michael@0: decContext *set) { michael@0: decNumber dzero; michael@0: uInt status=0; /* accumulator */ michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; michael@0: #endif michael@0: michael@0: uprv_decNumberZero(&dzero); /* make 0 */ michael@0: dzero.exponent=rhs->exponent; /* [no coefficient expansion] */ michael@0: decAddOp(res, &dzero, rhs, set, 0, &status); michael@0: if (status!=0) decStatus(res, status, set); michael@0: #if DECCHECK michael@0: decCheckInexact(res, set); michael@0: #endif michael@0: return res; michael@0: } /* decNumberPlus */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberMultiply -- multiply two Numbers */ michael@0: /* */ michael@0: /* This computes C = A x B */ michael@0: /* */ michael@0: /* res is C, the result. C may be A and/or B (e.g., X=X+X) */ michael@0: /* lhs is A */ michael@0: /* rhs is B */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberMultiply(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set) { michael@0: uInt status=0; /* accumulator */ michael@0: decMultiplyOp(res, lhs, rhs, set, &status); michael@0: if (status!=0) decStatus(res, status, set); michael@0: #if DECCHECK michael@0: decCheckInexact(res, set); michael@0: #endif michael@0: return res; michael@0: } /* decNumberMultiply */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberPower -- raise a number to a power */ michael@0: /* */ michael@0: /* This computes C = A ** B */ michael@0: /* */ michael@0: /* res is C, the result. C may be A and/or B (e.g., X=X**X) */ michael@0: /* lhs is A */ michael@0: /* rhs is B */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* */ michael@0: /* Mathematical function restrictions apply (see above); a NaN is */ michael@0: /* returned with Invalid_operation if a restriction is violated. */ michael@0: /* */ michael@0: /* However, if 1999999997<=B<=999999999 and B is an integer then the */ michael@0: /* restrictions on A and the context are relaxed to the usual bounds, */ michael@0: /* for compatibility with the earlier (integer power only) version */ michael@0: /* of this function. */ michael@0: /* */ michael@0: /* When B is an integer, the result may be exact, even if rounded. */ michael@0: /* */ michael@0: /* The final result is rounded according to the context; it will */ michael@0: /* almost always be correctly rounded, but may be up to 1 ulp in */ michael@0: /* error in rare cases. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberPower(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set) { michael@0: #if DECSUBSET michael@0: decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */ michael@0: decNumber *allocrhs=NULL; /* .., rhs */ michael@0: #endif michael@0: decNumber *allocdac=NULL; /* -> allocated acc buffer, iff used */ michael@0: decNumber *allocinv=NULL; /* -> allocated 1/x buffer, iff used */ michael@0: Int reqdigits=set->digits; /* requested DIGITS */ michael@0: Int n; /* rhs in binary */ michael@0: Flag rhsint=0; /* 1 if rhs is an integer */ michael@0: Flag useint=0; /* 1 if can use integer calculation */ michael@0: Flag isoddint=0; /* 1 if rhs is an integer and odd */ michael@0: Int i; /* work */ michael@0: #if DECSUBSET michael@0: Int dropped; /* .. */ michael@0: #endif michael@0: uInt needbytes; /* buffer size needed */ michael@0: Flag seenbit; /* seen a bit while powering */ michael@0: Int residue=0; /* rounding residue */ michael@0: uInt status=0; /* accumulators */ michael@0: uByte bits=0; /* result sign if errors */ michael@0: decContext aset; /* working context */ michael@0: decNumber dnOne; /* work value 1... */ michael@0: /* local accumulator buffer [a decNumber, with digits+elength+1 digits] */ michael@0: decNumber dacbuff[D2N(DECBUFFER+9)]; michael@0: decNumber *dac=dacbuff; /* -> result accumulator */ michael@0: /* same again for possible 1/lhs calculation */ michael@0: decNumber invbuff[D2N(DECBUFFER+9)]; michael@0: michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, lhs, rhs, set)) return res; michael@0: #endif michael@0: michael@0: do { /* protect allocated storage */ michael@0: #if DECSUBSET michael@0: if (!set->extended) { /* reduce operands and set status, as needed */ michael@0: if (lhs->digits>reqdigits) { michael@0: alloclhs=decRoundOperand(lhs, set, &status); michael@0: if (alloclhs==NULL) break; michael@0: lhs=alloclhs; michael@0: } michael@0: if (rhs->digits>reqdigits) { michael@0: allocrhs=decRoundOperand(rhs, set, &status); michael@0: if (allocrhs==NULL) break; michael@0: rhs=allocrhs; michael@0: } michael@0: } michael@0: #endif michael@0: /* [following code does not require input rounding] */ michael@0: michael@0: /* handle NaNs and rhs Infinity (lhs infinity is harder) */ michael@0: if (SPECIALARGS) { michael@0: if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) { /* NaNs */ michael@0: decNaNs(res, lhs, rhs, set, &status); michael@0: break;} michael@0: if (decNumberIsInfinite(rhs)) { /* rhs Infinity */ michael@0: Flag rhsneg=rhs->bits&DECNEG; /* save rhs sign */ michael@0: if (decNumberIsNegative(lhs) /* lhs<0 */ michael@0: && !decNumberIsZero(lhs)) /* .. */ michael@0: status|=DEC_Invalid_operation; michael@0: else { /* lhs >=0 */ michael@0: uprv_decNumberZero(&dnOne); /* set up 1 */ michael@0: dnOne.lsu[0]=1; michael@0: uprv_decNumberCompare(dac, lhs, &dnOne, set); /* lhs ? 1 */ michael@0: uprv_decNumberZero(res); /* prepare for 0/1/Infinity */ michael@0: if (decNumberIsNegative(dac)) { /* lhs<1 */ michael@0: if (rhsneg) res->bits|=DECINF; /* +Infinity [else is +0] */ michael@0: } michael@0: else if (dac->lsu[0]==0) { /* lhs=1 */ michael@0: /* 1**Infinity is inexact, so return fully-padded 1.0000 */ michael@0: Int shift=set->digits-1; michael@0: *res->lsu=1; /* was 0, make int 1 */ michael@0: res->digits=decShiftToMost(res->lsu, 1, shift); michael@0: res->exponent=-shift; /* make 1.0000... */ michael@0: status|=DEC_Inexact|DEC_Rounded; /* deemed inexact */ michael@0: } michael@0: else { /* lhs>1 */ michael@0: if (!rhsneg) res->bits|=DECINF; /* +Infinity [else is +0] */ michael@0: } michael@0: } /* lhs>=0 */ michael@0: break;} michael@0: /* [lhs infinity drops through] */ michael@0: } /* specials */ michael@0: michael@0: /* Original rhs may be an integer that fits and is in range */ michael@0: n=decGetInt(rhs); michael@0: if (n!=BADINT) { /* it is an integer */ michael@0: rhsint=1; /* record the fact for 1**n */ michael@0: isoddint=(Flag)n&1; /* [works even if big] */ michael@0: if (n!=BIGEVEN && n!=BIGODD) /* can use integer path? */ michael@0: useint=1; /* looks good */ michael@0: } michael@0: michael@0: if (decNumberIsNegative(lhs) /* -x .. */ michael@0: && isoddint) bits=DECNEG; /* .. to an odd power */ michael@0: michael@0: /* handle LHS infinity */ michael@0: if (decNumberIsInfinite(lhs)) { /* [NaNs already handled] */ michael@0: uByte rbits=rhs->bits; /* save */ michael@0: uprv_decNumberZero(res); /* prepare */ michael@0: if (n==0) *res->lsu=1; /* [-]Inf**0 => 1 */ michael@0: else { michael@0: /* -Inf**nonint -> error */ michael@0: if (!rhsint && decNumberIsNegative(lhs)) { michael@0: status|=DEC_Invalid_operation; /* -Inf**nonint is error */ michael@0: break;} michael@0: if (!(rbits & DECNEG)) bits|=DECINF; /* was not a **-n */ michael@0: /* [otherwise will be 0 or -0] */ michael@0: res->bits=bits; michael@0: } michael@0: break;} michael@0: michael@0: /* similarly handle LHS zero */ michael@0: if (decNumberIsZero(lhs)) { michael@0: if (n==0) { /* 0**0 => Error */ michael@0: #if DECSUBSET michael@0: if (!set->extended) { /* [unless subset] */ michael@0: uprv_decNumberZero(res); michael@0: *res->lsu=1; /* return 1 */ michael@0: break;} michael@0: #endif michael@0: status|=DEC_Invalid_operation; michael@0: } michael@0: else { /* 0**x */ michael@0: uByte rbits=rhs->bits; /* save */ michael@0: if (rbits & DECNEG) { /* was a 0**(-n) */ michael@0: #if DECSUBSET michael@0: if (!set->extended) { /* [bad if subset] */ michael@0: status|=DEC_Invalid_operation; michael@0: break;} michael@0: #endif michael@0: bits|=DECINF; michael@0: } michael@0: uprv_decNumberZero(res); /* prepare */ michael@0: /* [otherwise will be 0 or -0] */ michael@0: res->bits=bits; michael@0: } michael@0: break;} michael@0: michael@0: /* here both lhs and rhs are finite; rhs==0 is handled in the */ michael@0: /* integer path. Next handle the non-integer cases */ michael@0: if (!useint) { /* non-integral rhs */ michael@0: /* any -ve lhs is bad, as is either operand or context out of */ michael@0: /* bounds */ michael@0: if (decNumberIsNegative(lhs)) { michael@0: status|=DEC_Invalid_operation; michael@0: break;} michael@0: if (decCheckMath(lhs, set, &status) michael@0: || decCheckMath(rhs, set, &status)) break; /* variable status */ michael@0: michael@0: uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64); /* clean context */ michael@0: aset.emax=DEC_MAX_MATH; /* usual bounds */ michael@0: aset.emin=-DEC_MAX_MATH; /* .. */ michael@0: aset.clamp=0; /* and no concrete format */ michael@0: michael@0: /* calculate the result using exp(ln(lhs)*rhs), which can */ michael@0: /* all be done into the accumulator, dac. The precision needed */ michael@0: /* is enough to contain the full information in the lhs (which */ michael@0: /* is the total digits, including exponent), or the requested */ michael@0: /* precision, if larger, + 4; 6 is used for the exponent */ michael@0: /* maximum length, and this is also used when it is shorter */ michael@0: /* than the requested digits as it greatly reduces the >0.5 ulp */ michael@0: /* cases at little cost (because Ln doubles digits each */ michael@0: /* iteration so a few extra digits rarely causes an extra */ michael@0: /* iteration) */ michael@0: aset.digits=MAXI(lhs->digits, set->digits)+6+4; michael@0: } /* non-integer rhs */ michael@0: michael@0: else { /* rhs is in-range integer */ michael@0: if (n==0) { /* x**0 = 1 */ michael@0: /* (0**0 was handled above) */ michael@0: uprv_decNumberZero(res); /* result=1 */ michael@0: *res->lsu=1; /* .. */ michael@0: break;} michael@0: /* rhs is a non-zero integer */ michael@0: if (n<0) n=-n; /* use abs(n) */ michael@0: michael@0: aset=*set; /* clone the context */ michael@0: aset.round=DEC_ROUND_HALF_EVEN; /* internally use balanced */ michael@0: /* calculate the working DIGITS */ michael@0: aset.digits=reqdigits+(rhs->digits+rhs->exponent)+2; michael@0: #if DECSUBSET michael@0: if (!set->extended) aset.digits--; /* use classic precision */ michael@0: #endif michael@0: /* it's an error if this is more than can be handled */ michael@0: if (aset.digits>DECNUMMAXP) {status|=DEC_Invalid_operation; break;} michael@0: } /* integer path */ michael@0: michael@0: /* aset.digits is the count of digits for the accumulator needed */ michael@0: /* if accumulator is too long for local storage, then allocate */ michael@0: needbytes=sizeof(decNumber)+(D2U(aset.digits)-1)*sizeof(Unit); michael@0: /* [needbytes also used below if 1/lhs needed] */ michael@0: if (needbytes>sizeof(dacbuff)) { michael@0: allocdac=(decNumber *)malloc(needbytes); michael@0: if (allocdac==NULL) { /* hopeless -- abandon */ michael@0: status|=DEC_Insufficient_storage; michael@0: break;} michael@0: dac=allocdac; /* use the allocated space */ michael@0: } michael@0: /* here, aset is set up and accumulator is ready for use */ michael@0: michael@0: if (!useint) { /* non-integral rhs */ michael@0: /* x ** y; special-case x=1 here as it will otherwise always */ michael@0: /* reduce to integer 1; decLnOp has a fastpath which detects */ michael@0: /* the case of x=1 */ michael@0: decLnOp(dac, lhs, &aset, &status); /* dac=ln(lhs) */ michael@0: /* [no error possible, as lhs 0 already handled] */ michael@0: if (ISZERO(dac)) { /* x==1, 1.0, etc. */ michael@0: /* need to return fully-padded 1.0000 etc., but rhsint->1 */ michael@0: *dac->lsu=1; /* was 0, make int 1 */ michael@0: if (!rhsint) { /* add padding */ michael@0: Int shift=set->digits-1; michael@0: dac->digits=decShiftToMost(dac->lsu, 1, shift); michael@0: dac->exponent=-shift; /* make 1.0000... */ michael@0: status|=DEC_Inexact|DEC_Rounded; /* deemed inexact */ michael@0: } michael@0: } michael@0: else { michael@0: decMultiplyOp(dac, dac, rhs, &aset, &status); /* dac=dac*rhs */ michael@0: decExpOp(dac, dac, &aset, &status); /* dac=exp(dac) */ michael@0: } michael@0: /* and drop through for final rounding */ michael@0: } /* non-integer rhs */ michael@0: michael@0: else { /* carry on with integer */ michael@0: uprv_decNumberZero(dac); /* acc=1 */ michael@0: *dac->lsu=1; /* .. */ michael@0: michael@0: /* if a negative power the constant 1 is needed, and if not subset */ michael@0: /* invert the lhs now rather than inverting the result later */ michael@0: if (decNumberIsNegative(rhs)) { /* was a **-n [hence digits>0] */ michael@0: decNumber *inv=invbuff; /* asssume use fixed buffer */ michael@0: uprv_decNumberCopy(&dnOne, dac); /* dnOne=1; [needed now or later] */ michael@0: #if DECSUBSET michael@0: if (set->extended) { /* need to calculate 1/lhs */ michael@0: #endif michael@0: /* divide lhs into 1, putting result in dac [dac=1/dac] */ michael@0: decDivideOp(dac, &dnOne, lhs, &aset, DIVIDE, &status); michael@0: /* now locate or allocate space for the inverted lhs */ michael@0: if (needbytes>sizeof(invbuff)) { michael@0: allocinv=(decNumber *)malloc(needbytes); michael@0: if (allocinv==NULL) { /* hopeless -- abandon */ michael@0: status|=DEC_Insufficient_storage; michael@0: break;} michael@0: inv=allocinv; /* use the allocated space */ michael@0: } michael@0: /* [inv now points to big-enough buffer or allocated storage] */ michael@0: uprv_decNumberCopy(inv, dac); /* copy the 1/lhs */ michael@0: uprv_decNumberCopy(dac, &dnOne); /* restore acc=1 */ michael@0: lhs=inv; /* .. and go forward with new lhs */ michael@0: #if DECSUBSET michael@0: } michael@0: #endif michael@0: } michael@0: michael@0: /* Raise-to-the-power loop... */ michael@0: seenbit=0; /* set once a 1-bit is encountered */ michael@0: for (i=1;;i++){ /* for each bit [top bit ignored] */ michael@0: /* abandon if had overflow or terminal underflow */ michael@0: if (status & (DEC_Overflow|DEC_Underflow)) { /* interesting? */ michael@0: if (status&DEC_Overflow || ISZERO(dac)) break; michael@0: } michael@0: /* [the following two lines revealed an optimizer bug in a C++ */ michael@0: /* compiler, with symptom: 5**3 -> 25, when n=n+n was used] */ michael@0: n=n<<1; /* move next bit to testable position */ michael@0: if (n<0) { /* top bit is set */ michael@0: seenbit=1; /* OK, significant bit seen */ michael@0: decMultiplyOp(dac, dac, lhs, &aset, &status); /* dac=dac*x */ michael@0: } michael@0: if (i==31) break; /* that was the last bit */ michael@0: if (!seenbit) continue; /* no need to square 1 */ michael@0: decMultiplyOp(dac, dac, dac, &aset, &status); /* dac=dac*dac [square] */ michael@0: } /*i*/ /* 32 bits */ michael@0: michael@0: /* complete internal overflow or underflow processing */ michael@0: if (status & (DEC_Overflow|DEC_Underflow)) { michael@0: #if DECSUBSET michael@0: /* If subset, and power was negative, reverse the kind of -erflow */ michael@0: /* [1/x not yet done] */ michael@0: if (!set->extended && decNumberIsNegative(rhs)) { michael@0: if (status & DEC_Overflow) michael@0: status^=DEC_Overflow | DEC_Underflow | DEC_Subnormal; michael@0: else { /* trickier -- Underflow may or may not be set */ michael@0: status&=~(DEC_Underflow | DEC_Subnormal); /* [one or both] */ michael@0: status|=DEC_Overflow; michael@0: } michael@0: } michael@0: #endif michael@0: dac->bits=(dac->bits & ~DECNEG) | bits; /* force correct sign */ michael@0: /* round subnormals [to set.digits rather than aset.digits] */ michael@0: /* or set overflow result similarly as required */ michael@0: decFinalize(dac, set, &residue, &status); michael@0: uprv_decNumberCopy(res, dac); /* copy to result (is now OK length) */ michael@0: break; michael@0: } michael@0: michael@0: #if DECSUBSET michael@0: if (!set->extended && /* subset math */ michael@0: decNumberIsNegative(rhs)) { /* was a **-n [hence digits>0] */ michael@0: /* so divide result into 1 [dac=1/dac] */ michael@0: decDivideOp(dac, &dnOne, dac, &aset, DIVIDE, &status); michael@0: } michael@0: #endif michael@0: } /* rhs integer path */ michael@0: michael@0: /* reduce result to the requested length and copy to result */ michael@0: decCopyFit(res, dac, set, &residue, &status); michael@0: decFinish(res, set, &residue, &status); /* final cleanup */ michael@0: #if DECSUBSET michael@0: if (!set->extended) decTrim(res, set, 0, 1, &dropped); /* trailing zeros */ michael@0: #endif michael@0: } while(0); /* end protected */ michael@0: michael@0: if (allocdac!=NULL) free(allocdac); /* drop any storage used */ michael@0: if (allocinv!=NULL) free(allocinv); /* .. */ michael@0: #if DECSUBSET michael@0: if (alloclhs!=NULL) free(alloclhs); /* .. */ michael@0: if (allocrhs!=NULL) free(allocrhs); /* .. */ michael@0: #endif michael@0: if (status!=0) decStatus(res, status, set); michael@0: #if DECCHECK michael@0: decCheckInexact(res, set); michael@0: #endif michael@0: return res; michael@0: } /* decNumberPower */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberQuantize -- force exponent to requested value */ michael@0: /* */ michael@0: /* This computes C = op(A, B), where op adjusts the coefficient */ michael@0: /* of C (by rounding or shifting) such that the exponent (-scale) */ michael@0: /* of C has exponent of B. The numerical value of C will equal A, */ michael@0: /* except for the effects of any rounding that occurred. */ michael@0: /* */ michael@0: /* res is C, the result. C may be A or B */ michael@0: /* lhs is A, the number to adjust */ michael@0: /* rhs is B, the number with exponent to match */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* */ michael@0: /* Unless there is an error or the result is infinite, the exponent */ michael@0: /* after the operation is guaranteed to be equal to that of B. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberQuantize(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set) { michael@0: uInt status=0; /* accumulator */ michael@0: decQuantizeOp(res, lhs, rhs, set, 1, &status); michael@0: if (status!=0) decStatus(res, status, set); michael@0: return res; michael@0: } /* decNumberQuantize */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberReduce -- remove trailing zeros */ michael@0: /* */ michael@0: /* This computes C = 0 + A, and normalizes the result */ michael@0: /* */ michael@0: /* res is C, the result. C may be A */ michael@0: /* rhs is A */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: /* Previously known as Normalize */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberNormalize(decNumber *res, const decNumber *rhs, michael@0: decContext *set) { michael@0: return uprv_decNumberReduce(res, rhs, set); michael@0: } /* decNumberNormalize */ michael@0: michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberReduce(decNumber *res, const decNumber *rhs, michael@0: decContext *set) { michael@0: #if DECSUBSET michael@0: decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */ michael@0: #endif michael@0: uInt status=0; /* as usual */ michael@0: Int residue=0; /* as usual */ michael@0: Int dropped; /* work */ michael@0: michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; michael@0: #endif michael@0: michael@0: do { /* protect allocated storage */ michael@0: #if DECSUBSET michael@0: if (!set->extended) { michael@0: /* reduce operand and set lostDigits status, as needed */ michael@0: if (rhs->digits>set->digits) { michael@0: allocrhs=decRoundOperand(rhs, set, &status); michael@0: if (allocrhs==NULL) break; michael@0: rhs=allocrhs; michael@0: } michael@0: } michael@0: #endif michael@0: /* [following code does not require input rounding] */ michael@0: michael@0: /* Infinities copy through; NaNs need usual treatment */ michael@0: if (decNumberIsNaN(rhs)) { michael@0: decNaNs(res, rhs, NULL, set, &status); michael@0: break; michael@0: } michael@0: michael@0: /* reduce result to the requested length and copy to result */ michael@0: decCopyFit(res, rhs, set, &residue, &status); /* copy & round */ michael@0: decFinish(res, set, &residue, &status); /* cleanup/set flags */ michael@0: decTrim(res, set, 1, 0, &dropped); /* normalize in place */ michael@0: /* [may clamp] */ michael@0: } while(0); /* end protected */ michael@0: michael@0: #if DECSUBSET michael@0: if (allocrhs !=NULL) free(allocrhs); /* .. */ michael@0: #endif michael@0: if (status!=0) decStatus(res, status, set);/* then report status */ michael@0: return res; michael@0: } /* decNumberReduce */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberRescale -- force exponent to requested value */ michael@0: /* */ michael@0: /* This computes C = op(A, B), where op adjusts the coefficient */ michael@0: /* of C (by rounding or shifting) such that the exponent (-scale) */ michael@0: /* of C has the value B. The numerical value of C will equal A, */ michael@0: /* except for the effects of any rounding that occurred. */ michael@0: /* */ michael@0: /* res is C, the result. C may be A or B */ michael@0: /* lhs is A, the number to adjust */ michael@0: /* rhs is B, the requested exponent */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* */ michael@0: /* Unless there is an error or the result is infinite, the exponent */ michael@0: /* after the operation is guaranteed to be equal to B. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberRescale(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set) { michael@0: uInt status=0; /* accumulator */ michael@0: decQuantizeOp(res, lhs, rhs, set, 0, &status); michael@0: if (status!=0) decStatus(res, status, set); michael@0: return res; michael@0: } /* decNumberRescale */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberRemainder -- divide and return remainder */ michael@0: /* */ michael@0: /* This computes C = A % B */ michael@0: /* */ michael@0: /* res is C, the result. C may be A and/or B (e.g., X=X%X) */ michael@0: /* lhs is A */ michael@0: /* rhs is B */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberRemainder(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set) { michael@0: uInt status=0; /* accumulator */ michael@0: decDivideOp(res, lhs, rhs, set, REMAINDER, &status); michael@0: if (status!=0) decStatus(res, status, set); michael@0: #if DECCHECK michael@0: decCheckInexact(res, set); michael@0: #endif michael@0: return res; michael@0: } /* decNumberRemainder */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberRemainderNear -- divide and return remainder from nearest */ michael@0: /* */ michael@0: /* This computes C = A % B, where % is the IEEE remainder operator */ michael@0: /* */ michael@0: /* res is C, the result. C may be A and/or B (e.g., X=X%X) */ michael@0: /* lhs is A */ michael@0: /* rhs is B */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberRemainderNear(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set) { michael@0: uInt status=0; /* accumulator */ michael@0: decDivideOp(res, lhs, rhs, set, REMNEAR, &status); michael@0: if (status!=0) decStatus(res, status, set); michael@0: #if DECCHECK michael@0: decCheckInexact(res, set); michael@0: #endif michael@0: return res; michael@0: } /* decNumberRemainderNear */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberRotate -- rotate the coefficient of a Number left/right */ michael@0: /* */ michael@0: /* This computes C = A rot B (in base ten and rotating set->digits */ michael@0: /* digits). */ michael@0: /* */ michael@0: /* res is C, the result. C may be A and/or B (e.g., X=XrotX) */ michael@0: /* lhs is A */ michael@0: /* rhs is B, the number of digits to rotate (-ve to right) */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* The digits of the coefficient of A are rotated to the left (if B */ michael@0: /* is positive) or to the right (if B is negative) without adjusting */ michael@0: /* the exponent or the sign of A. If lhs->digits is less than */ michael@0: /* set->digits the coefficient is padded with zeros on the left */ michael@0: /* before the rotate. Any leading zeros in the result are removed */ michael@0: /* as usual. */ michael@0: /* */ michael@0: /* B must be an integer (q=0) and in the range -set->digits through */ michael@0: /* +set->digits. */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* NaNs are propagated as usual. Infinities are unaffected (but */ michael@0: /* B must be valid). No status is set unless B is invalid or an */ michael@0: /* operand is an sNaN. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberRotate(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set) { michael@0: uInt status=0; /* accumulator */ michael@0: Int rotate; /* rhs as an Int */ michael@0: michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, lhs, rhs, set)) return res; michael@0: #endif michael@0: michael@0: /* NaNs propagate as normal */ michael@0: if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) michael@0: decNaNs(res, lhs, rhs, set, &status); michael@0: /* rhs must be an integer */ michael@0: else if (decNumberIsInfinite(rhs) || rhs->exponent!=0) michael@0: status=DEC_Invalid_operation; michael@0: else { /* both numeric, rhs is an integer */ michael@0: rotate=decGetInt(rhs); /* [cannot fail] */ michael@0: if (rotate==BADINT /* something bad .. */ michael@0: || rotate==BIGODD || rotate==BIGEVEN /* .. very big .. */ michael@0: || abs(rotate)>set->digits) /* .. or out of range */ michael@0: status=DEC_Invalid_operation; michael@0: else { /* rhs is OK */ michael@0: uprv_decNumberCopy(res, lhs); michael@0: /* convert -ve rotate to equivalent positive rotation */ michael@0: if (rotate<0) rotate=set->digits+rotate; michael@0: if (rotate!=0 && rotate!=set->digits /* zero or full rotation */ michael@0: && !decNumberIsInfinite(res)) { /* lhs was infinite */ michael@0: /* left-rotate to do; 0 < rotate < set->digits */ michael@0: uInt units, shift; /* work */ michael@0: uInt msudigits; /* digits in result msu */ michael@0: Unit *msu=res->lsu+D2U(res->digits)-1; /* current msu */ michael@0: Unit *msumax=res->lsu+D2U(set->digits)-1; /* rotation msu */ michael@0: for (msu++; msu<=msumax; msu++) *msu=0; /* ensure high units=0 */ michael@0: res->digits=set->digits; /* now full-length */ michael@0: msudigits=MSUDIGITS(res->digits); /* actual digits in msu */ michael@0: michael@0: /* rotation here is done in-place, in three steps */ michael@0: /* 1. shift all to least up to one unit to unit-align final */ michael@0: /* lsd [any digits shifted out are rotated to the left, */ michael@0: /* abutted to the original msd (which may require split)] */ michael@0: /* */ michael@0: /* [if there are no whole units left to rotate, the */ michael@0: /* rotation is now complete] */ michael@0: /* */ michael@0: /* 2. shift to least, from below the split point only, so that */ michael@0: /* the final msd is in the right place in its Unit [any */ michael@0: /* digits shifted out will fit exactly in the current msu, */ michael@0: /* left aligned, no split required] */ michael@0: /* */ michael@0: /* 3. rotate all the units by reversing left part, right */ michael@0: /* part, and then whole */ michael@0: /* */ michael@0: /* example: rotate right 8 digits (2 units + 2), DECDPUN=3. */ michael@0: /* */ michael@0: /* start: 00a bcd efg hij klm npq */ michael@0: /* */ michael@0: /* 1a 000 0ab cde fgh|ijk lmn [pq saved] */ michael@0: /* 1b 00p qab cde fgh|ijk lmn */ michael@0: /* */ michael@0: /* 2a 00p qab cde fgh|00i jkl [mn saved] */ michael@0: /* 2b mnp qab cde fgh|00i jkl */ michael@0: /* */ michael@0: /* 3a fgh cde qab mnp|00i jkl */ michael@0: /* 3b fgh cde qab mnp|jkl 00i */ michael@0: /* 3c 00i jkl mnp qab cde fgh */ michael@0: michael@0: /* Step 1: amount to shift is the partial right-rotate count */ michael@0: rotate=set->digits-rotate; /* make it right-rotate */ michael@0: units=rotate/DECDPUN; /* whole units to rotate */ michael@0: shift=rotate%DECDPUN; /* left-over digits count */ michael@0: if (shift>0) { /* not an exact number of units */ michael@0: uInt save=res->lsu[0]%powers[shift]; /* save low digit(s) */ michael@0: decShiftToLeast(res->lsu, D2U(res->digits), shift); michael@0: if (shift>msudigits) { /* msumax-1 needs >0 digits */ michael@0: uInt rem=save%powers[shift-msudigits];/* split save */ michael@0: *msumax=(Unit)(save/powers[shift-msudigits]); /* and insert */ michael@0: *(msumax-1)=*(msumax-1) michael@0: +(Unit)(rem*powers[DECDPUN-(shift-msudigits)]); /* .. */ michael@0: } michael@0: else { /* all fits in msumax */ michael@0: *msumax=*msumax+(Unit)(save*powers[msudigits-shift]); /* [maybe *1] */ michael@0: } michael@0: } /* digits shift needed */ michael@0: michael@0: /* If whole units to rotate... */ michael@0: if (units>0) { /* some to do */ michael@0: /* Step 2: the units to touch are the whole ones in rotate, */ michael@0: /* if any, and the shift is DECDPUN-msudigits (which may be */ michael@0: /* 0, again) */ michael@0: shift=DECDPUN-msudigits; michael@0: if (shift>0) { /* not an exact number of units */ michael@0: uInt save=res->lsu[0]%powers[shift]; /* save low digit(s) */ michael@0: decShiftToLeast(res->lsu, units, shift); michael@0: *msumax=*msumax+(Unit)(save*powers[msudigits]); michael@0: } /* partial shift needed */ michael@0: michael@0: /* Step 3: rotate the units array using triple reverse */ michael@0: /* (reversing is easy and fast) */ michael@0: decReverse(res->lsu+units, msumax); /* left part */ michael@0: decReverse(res->lsu, res->lsu+units-1); /* right part */ michael@0: decReverse(res->lsu, msumax); /* whole */ michael@0: } /* whole units to rotate */ michael@0: /* the rotation may have left an undetermined number of zeros */ michael@0: /* on the left, so true length needs to be calculated */ michael@0: res->digits=decGetDigits(res->lsu, msumax-res->lsu+1); michael@0: } /* rotate needed */ michael@0: } /* rhs OK */ michael@0: } /* numerics */ michael@0: if (status!=0) decStatus(res, status, set); michael@0: return res; michael@0: } /* decNumberRotate */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberSameQuantum -- test for equal exponents */ michael@0: /* */ michael@0: /* res is the result number, which will contain either 0 or 1 */ michael@0: /* lhs is a number to test */ michael@0: /* rhs is the second (usually a pattern) */ michael@0: /* */ michael@0: /* No errors are possible and no context is needed. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberSameQuantum(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs) { michael@0: Unit ret=0; /* return value */ michael@0: michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, lhs, rhs, DECUNCONT)) return res; michael@0: #endif michael@0: michael@0: if (SPECIALARGS) { michael@0: if (decNumberIsNaN(lhs) && decNumberIsNaN(rhs)) ret=1; michael@0: else if (decNumberIsInfinite(lhs) && decNumberIsInfinite(rhs)) ret=1; michael@0: /* [anything else with a special gives 0] */ michael@0: } michael@0: else if (lhs->exponent==rhs->exponent) ret=1; michael@0: michael@0: uprv_decNumberZero(res); /* OK to overwrite an operand now */ michael@0: *res->lsu=ret; michael@0: return res; michael@0: } /* decNumberSameQuantum */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberScaleB -- multiply by a power of 10 */ michael@0: /* */ michael@0: /* This computes C = A x 10**B where B is an integer (q=0) with */ michael@0: /* maximum magnitude 2*(emax+digits) */ michael@0: /* */ michael@0: /* res is C, the result. C may be A or B */ michael@0: /* lhs is A, the number to adjust */ michael@0: /* rhs is B, the requested power of ten to use */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* */ michael@0: /* The result may underflow or overflow. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberScaleB(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set) { michael@0: Int reqexp; /* requested exponent change [B] */ michael@0: uInt status=0; /* accumulator */ michael@0: Int residue; /* work */ michael@0: michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, lhs, rhs, set)) return res; michael@0: #endif michael@0: michael@0: /* Handle special values except lhs infinite */ michael@0: if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) michael@0: decNaNs(res, lhs, rhs, set, &status); michael@0: /* rhs must be an integer */ michael@0: else if (decNumberIsInfinite(rhs) || rhs->exponent!=0) michael@0: status=DEC_Invalid_operation; michael@0: else { michael@0: /* lhs is a number; rhs is a finite with q==0 */ michael@0: reqexp=decGetInt(rhs); /* [cannot fail] */ michael@0: if (reqexp==BADINT /* something bad .. */ michael@0: || reqexp==BIGODD || reqexp==BIGEVEN /* .. very big .. */ michael@0: || abs(reqexp)>(2*(set->digits+set->emax))) /* .. or out of range */ michael@0: status=DEC_Invalid_operation; michael@0: else { /* rhs is OK */ michael@0: uprv_decNumberCopy(res, lhs); /* all done if infinite lhs */ michael@0: if (!decNumberIsInfinite(res)) { /* prepare to scale */ michael@0: res->exponent+=reqexp; /* adjust the exponent */ michael@0: residue=0; michael@0: decFinalize(res, set, &residue, &status); /* .. and check */ michael@0: } /* finite LHS */ michael@0: } /* rhs OK */ michael@0: } /* rhs finite */ michael@0: if (status!=0) decStatus(res, status, set); michael@0: return res; michael@0: } /* decNumberScaleB */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberShift -- shift the coefficient of a Number left or right */ michael@0: /* */ michael@0: /* This computes C = A << B or C = A >> -B (in base ten). */ michael@0: /* */ michael@0: /* res is C, the result. C may be A and/or B (e.g., X=X<digits through */ michael@0: /* +set->digits. */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* NaNs are propagated as usual. Infinities are unaffected (but */ michael@0: /* B must be valid). No status is set unless B is invalid or an */ michael@0: /* operand is an sNaN. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberShift(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set) { michael@0: uInt status=0; /* accumulator */ michael@0: Int shift; /* rhs as an Int */ michael@0: michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, lhs, rhs, set)) return res; michael@0: #endif michael@0: michael@0: /* NaNs propagate as normal */ michael@0: if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) michael@0: decNaNs(res, lhs, rhs, set, &status); michael@0: /* rhs must be an integer */ michael@0: else if (decNumberIsInfinite(rhs) || rhs->exponent!=0) michael@0: status=DEC_Invalid_operation; michael@0: else { /* both numeric, rhs is an integer */ michael@0: shift=decGetInt(rhs); /* [cannot fail] */ michael@0: if (shift==BADINT /* something bad .. */ michael@0: || shift==BIGODD || shift==BIGEVEN /* .. very big .. */ michael@0: || abs(shift)>set->digits) /* .. or out of range */ michael@0: status=DEC_Invalid_operation; michael@0: else { /* rhs is OK */ michael@0: uprv_decNumberCopy(res, lhs); michael@0: if (shift!=0 && !decNumberIsInfinite(res)) { /* something to do */ michael@0: if (shift>0) { /* to left */ michael@0: if (shift==set->digits) { /* removing all */ michael@0: *res->lsu=0; /* so place 0 */ michael@0: res->digits=1; /* .. */ michael@0: } michael@0: else { /* */ michael@0: /* first remove leading digits if necessary */ michael@0: if (res->digits+shift>set->digits) { michael@0: decDecap(res, res->digits+shift-set->digits); michael@0: /* that updated res->digits; may have gone to 1 (for a */ michael@0: /* single digit or for zero */ michael@0: } michael@0: if (res->digits>1 || *res->lsu) /* if non-zero.. */ michael@0: res->digits=decShiftToMost(res->lsu, res->digits, shift); michael@0: } /* partial left */ michael@0: } /* left */ michael@0: else { /* to right */ michael@0: if (-shift>=res->digits) { /* discarding all */ michael@0: *res->lsu=0; /* so place 0 */ michael@0: res->digits=1; /* .. */ michael@0: } michael@0: else { michael@0: decShiftToLeast(res->lsu, D2U(res->digits), -shift); michael@0: res->digits-=(-shift); michael@0: } michael@0: } /* to right */ michael@0: } /* non-0 non-Inf shift */ michael@0: } /* rhs OK */ michael@0: } /* numerics */ michael@0: if (status!=0) decStatus(res, status, set); michael@0: return res; michael@0: } /* decNumberShift */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberSquareRoot -- square root operator */ michael@0: /* */ michael@0: /* This computes C = squareroot(A) */ michael@0: /* */ michael@0: /* res is C, the result. C may be A */ michael@0: /* rhs is A */ michael@0: /* set is the context; note that rounding mode has no effect */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: /* This uses the following varying-precision algorithm in: */ michael@0: /* */ michael@0: /* Properly Rounded Variable Precision Square Root, T. E. Hull and */ michael@0: /* A. Abrham, ACM Transactions on Mathematical Software, Vol 11 #3, */ michael@0: /* pp229-237, ACM, September 1985. */ michael@0: /* */ michael@0: /* The square-root is calculated using Newton's method, after which */ michael@0: /* a check is made to ensure the result is correctly rounded. */ michael@0: /* */ michael@0: /* % [Reformatted original Numerical Turing source code follows.] */ michael@0: /* function sqrt(x : real) : real */ michael@0: /* % sqrt(x) returns the properly rounded approximation to the square */ michael@0: /* % root of x, in the precision of the calling environment, or it */ michael@0: /* % fails if x < 0. */ michael@0: /* % t e hull and a abrham, august, 1984 */ michael@0: /* if x <= 0 then */ michael@0: /* if x < 0 then */ michael@0: /* assert false */ michael@0: /* else */ michael@0: /* result 0 */ michael@0: /* end if */ michael@0: /* end if */ michael@0: /* var f := setexp(x, 0) % fraction part of x [0.1 <= x < 1] */ michael@0: /* var e := getexp(x) % exponent part of x */ michael@0: /* var approx : real */ michael@0: /* if e mod 2 = 0 then */ michael@0: /* approx := .259 + .819 * f % approx to root of f */ michael@0: /* else */ michael@0: /* f := f/l0 % adjustments */ michael@0: /* e := e + 1 % for odd */ michael@0: /* approx := .0819 + 2.59 * f % exponent */ michael@0: /* end if */ michael@0: /* */ michael@0: /* var p:= 3 */ michael@0: /* const maxp := currentprecision + 2 */ michael@0: /* loop */ michael@0: /* p := min(2*p - 2, maxp) % p = 4,6,10, . . . , maxp */ michael@0: /* precision p */ michael@0: /* approx := .5 * (approx + f/approx) */ michael@0: /* exit when p = maxp */ michael@0: /* end loop */ michael@0: /* */ michael@0: /* % approx is now within 1 ulp of the properly rounded square root */ michael@0: /* % of f; to ensure proper rounding, compare squares of (approx - */ michael@0: /* % l/2 ulp) and (approx + l/2 ulp) with f. */ michael@0: /* p := currentprecision */ michael@0: /* begin */ michael@0: /* precision p + 2 */ michael@0: /* const approxsubhalf := approx - setexp(.5, -p) */ michael@0: /* if mulru(approxsubhalf, approxsubhalf) > f then */ michael@0: /* approx := approx - setexp(.l, -p + 1) */ michael@0: /* else */ michael@0: /* const approxaddhalf := approx + setexp(.5, -p) */ michael@0: /* if mulrd(approxaddhalf, approxaddhalf) < f then */ michael@0: /* approx := approx + setexp(.l, -p + 1) */ michael@0: /* end if */ michael@0: /* end if */ michael@0: /* end */ michael@0: /* result setexp(approx, e div 2) % fix exponent */ michael@0: /* end sqrt */ michael@0: /* ------------------------------------------------------------------ */ michael@0: #if defined(__clang__) || U_GCC_MAJOR_MINOR >= 406 michael@0: #pragma GCC diagnostic push michael@0: #pragma GCC diagnostic ignored "-Warray-bounds" michael@0: #endif michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberSquareRoot(decNumber *res, const decNumber *rhs, michael@0: decContext *set) { michael@0: decContext workset, approxset; /* work contexts */ michael@0: decNumber dzero; /* used for constant zero */ michael@0: Int maxp; /* largest working precision */ michael@0: Int workp; /* working precision */ michael@0: Int residue=0; /* rounding residue */ michael@0: uInt status=0, ignore=0; /* status accumulators */ michael@0: uInt rstatus; /* .. */ michael@0: Int exp; /* working exponent */ michael@0: Int ideal; /* ideal (preferred) exponent */ michael@0: Int needbytes; /* work */ michael@0: Int dropped; /* .. */ michael@0: michael@0: #if DECSUBSET michael@0: decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */ michael@0: #endif michael@0: /* buffer for f [needs +1 in case DECBUFFER 0] */ michael@0: decNumber buff[D2N(DECBUFFER+1)]; michael@0: /* buffer for a [needs +2 to match likely maxp] */ michael@0: decNumber bufa[D2N(DECBUFFER+2)]; michael@0: /* buffer for temporary, b [must be same size as a] */ michael@0: decNumber bufb[D2N(DECBUFFER+2)]; michael@0: decNumber *allocbuff=NULL; /* -> allocated buff, iff allocated */ michael@0: decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */ michael@0: decNumber *allocbufb=NULL; /* -> allocated bufb, iff allocated */ michael@0: decNumber *f=buff; /* reduced fraction */ michael@0: decNumber *a=bufa; /* approximation to result */ michael@0: decNumber *b=bufb; /* intermediate result */ michael@0: /* buffer for temporary variable, up to 3 digits */ michael@0: decNumber buft[D2N(3)]; michael@0: decNumber *t=buft; /* up-to-3-digit constant or work */ michael@0: michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; michael@0: #endif michael@0: michael@0: do { /* protect allocated storage */ michael@0: #if DECSUBSET michael@0: if (!set->extended) { michael@0: /* reduce operand and set lostDigits status, as needed */ michael@0: if (rhs->digits>set->digits) { michael@0: allocrhs=decRoundOperand(rhs, set, &status); michael@0: if (allocrhs==NULL) break; michael@0: /* [Note: 'f' allocation below could reuse this buffer if */ michael@0: /* used, but as this is rare they are kept separate for clarity.] */ michael@0: rhs=allocrhs; michael@0: } michael@0: } michael@0: #endif michael@0: /* [following code does not require input rounding] */ michael@0: michael@0: /* handle infinities and NaNs */ michael@0: if (SPECIALARG) { michael@0: if (decNumberIsInfinite(rhs)) { /* an infinity */ michael@0: if (decNumberIsNegative(rhs)) status|=DEC_Invalid_operation; michael@0: else uprv_decNumberCopy(res, rhs); /* +Infinity */ michael@0: } michael@0: else decNaNs(res, rhs, NULL, set, &status); /* a NaN */ michael@0: break; michael@0: } michael@0: michael@0: /* calculate the ideal (preferred) exponent [floor(exp/2)] */ michael@0: /* [It would be nicer to write: ideal=rhs->exponent>>1, but this */ michael@0: /* generates a compiler warning. Generated code is the same.] */ michael@0: ideal=(rhs->exponent&~1)/2; /* target */ michael@0: michael@0: /* handle zeros */ michael@0: if (ISZERO(rhs)) { michael@0: uprv_decNumberCopy(res, rhs); /* could be 0 or -0 */ michael@0: res->exponent=ideal; /* use the ideal [safe] */ michael@0: /* use decFinish to clamp any out-of-range exponent, etc. */ michael@0: decFinish(res, set, &residue, &status); michael@0: break; michael@0: } michael@0: michael@0: /* any other -x is an oops */ michael@0: if (decNumberIsNegative(rhs)) { michael@0: status|=DEC_Invalid_operation; michael@0: break; michael@0: } michael@0: michael@0: /* space is needed for three working variables */ michael@0: /* f -- the same precision as the RHS, reduced to 0.01->0.99... */ michael@0: /* a -- Hull's approximation -- precision, when assigned, is */ michael@0: /* currentprecision+1 or the input argument precision, */ michael@0: /* whichever is larger (+2 for use as temporary) */ michael@0: /* b -- intermediate temporary result (same size as a) */ michael@0: /* if any is too long for local storage, then allocate */ michael@0: workp=MAXI(set->digits+1, rhs->digits); /* actual rounding precision */ michael@0: workp=MAXI(workp, 7); /* at least 7 for low cases */ michael@0: maxp=workp+2; /* largest working precision */ michael@0: michael@0: needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit); michael@0: if (needbytes>(Int)sizeof(buff)) { michael@0: allocbuff=(decNumber *)malloc(needbytes); michael@0: if (allocbuff==NULL) { /* hopeless -- abandon */ michael@0: status|=DEC_Insufficient_storage; michael@0: break;} michael@0: f=allocbuff; /* use the allocated space */ michael@0: } michael@0: /* a and b both need to be able to hold a maxp-length number */ michael@0: needbytes=sizeof(decNumber)+(D2U(maxp)-1)*sizeof(Unit); michael@0: if (needbytes>(Int)sizeof(bufa)) { /* [same applies to b] */ michael@0: allocbufa=(decNumber *)malloc(needbytes); michael@0: allocbufb=(decNumber *)malloc(needbytes); michael@0: if (allocbufa==NULL || allocbufb==NULL) { /* hopeless */ michael@0: status|=DEC_Insufficient_storage; michael@0: break;} michael@0: a=allocbufa; /* use the allocated spaces */ michael@0: b=allocbufb; /* .. */ michael@0: } michael@0: michael@0: /* copy rhs -> f, save exponent, and reduce so 0.1 <= f < 1 */ michael@0: uprv_decNumberCopy(f, rhs); michael@0: exp=f->exponent+f->digits; /* adjusted to Hull rules */ michael@0: f->exponent=-(f->digits); /* to range */ michael@0: michael@0: /* set up working context */ michael@0: uprv_decContextDefault(&workset, DEC_INIT_DECIMAL64); michael@0: workset.emax=DEC_MAX_EMAX; michael@0: workset.emin=DEC_MIN_EMIN; michael@0: michael@0: /* [Until further notice, no error is possible and status bits */ michael@0: /* (Rounded, etc.) should be ignored, not accumulated.] */ michael@0: michael@0: /* Calculate initial approximation, and allow for odd exponent */ michael@0: workset.digits=workp; /* p for initial calculation */ michael@0: t->bits=0; t->digits=3; michael@0: a->bits=0; a->digits=3; michael@0: if ((exp & 1)==0) { /* even exponent */ michael@0: /* Set t=0.259, a=0.819 */ michael@0: t->exponent=-3; michael@0: a->exponent=-3; michael@0: #if DECDPUN>=3 michael@0: t->lsu[0]=259; michael@0: a->lsu[0]=819; michael@0: #elif DECDPUN==2 michael@0: t->lsu[0]=59; t->lsu[1]=2; michael@0: a->lsu[0]=19; a->lsu[1]=8; michael@0: #else michael@0: t->lsu[0]=9; t->lsu[1]=5; t->lsu[2]=2; michael@0: a->lsu[0]=9; a->lsu[1]=1; a->lsu[2]=8; michael@0: #endif michael@0: } michael@0: else { /* odd exponent */ michael@0: /* Set t=0.0819, a=2.59 */ michael@0: f->exponent--; /* f=f/10 */ michael@0: exp++; /* e=e+1 */ michael@0: t->exponent=-4; michael@0: a->exponent=-2; michael@0: #if DECDPUN>=3 michael@0: t->lsu[0]=819; michael@0: a->lsu[0]=259; michael@0: #elif DECDPUN==2 michael@0: t->lsu[0]=19; t->lsu[1]=8; michael@0: a->lsu[0]=59; a->lsu[1]=2; michael@0: #else michael@0: t->lsu[0]=9; t->lsu[1]=1; t->lsu[2]=8; michael@0: a->lsu[0]=9; a->lsu[1]=5; a->lsu[2]=2; michael@0: #endif michael@0: } michael@0: michael@0: decMultiplyOp(a, a, f, &workset, &ignore); /* a=a*f */ michael@0: decAddOp(a, a, t, &workset, 0, &ignore); /* ..+t */ michael@0: /* [a is now the initial approximation for sqrt(f), calculated with */ michael@0: /* currentprecision, which is also a's precision.] */ michael@0: michael@0: /* the main calculation loop */ michael@0: uprv_decNumberZero(&dzero); /* make 0 */ michael@0: uprv_decNumberZero(t); /* set t = 0.5 */ michael@0: t->lsu[0]=5; /* .. */ michael@0: t->exponent=-1; /* .. */ michael@0: workset.digits=3; /* initial p */ michael@0: for (; workset.digitsexponent+=exp/2; /* set correct exponent */ michael@0: rstatus=0; /* clear status */ michael@0: residue=0; /* .. and accumulator */ michael@0: decCopyFit(a, a, &approxset, &residue, &rstatus); /* reduce (if needed) */ michael@0: decFinish(a, &approxset, &residue, &rstatus); /* clean and finalize */ michael@0: michael@0: /* Overflow was possible if the input exponent was out-of-range, */ michael@0: /* in which case quit */ michael@0: if (rstatus&DEC_Overflow) { michael@0: status=rstatus; /* use the status as-is */ michael@0: uprv_decNumberCopy(res, a); /* copy to result */ michael@0: break; michael@0: } michael@0: michael@0: /* Preserve status except Inexact/Rounded */ michael@0: status|=(rstatus & ~(DEC_Rounded|DEC_Inexact)); michael@0: michael@0: /* Carry out the Hull correction */ michael@0: a->exponent-=exp/2; /* back to 0.1->1 */ michael@0: michael@0: /* a is now at final precision and within 1 ulp of the properly */ michael@0: /* rounded square root of f; to ensure proper rounding, compare */ michael@0: /* squares of (a - l/2 ulp) and (a + l/2 ulp) with f. */ michael@0: /* Here workset.digits=maxp and t=0.5, and a->digits determines */ michael@0: /* the ulp */ michael@0: workset.digits--; /* maxp-1 is OK now */ michael@0: t->exponent=-a->digits-1; /* make 0.5 ulp */ michael@0: decAddOp(b, a, t, &workset, DECNEG, &ignore); /* b = a - 0.5 ulp */ michael@0: workset.round=DEC_ROUND_UP; michael@0: decMultiplyOp(b, b, b, &workset, &ignore); /* b = mulru(b, b) */ michael@0: decCompareOp(b, f, b, &workset, COMPARE, &ignore); /* b ? f, reversed */ michael@0: if (decNumberIsNegative(b)) { /* f < b [i.e., b > f] */ michael@0: /* this is the more common adjustment, though both are rare */ michael@0: t->exponent++; /* make 1.0 ulp */ michael@0: t->lsu[0]=1; /* .. */ michael@0: decAddOp(a, a, t, &workset, DECNEG, &ignore); /* a = a - 1 ulp */ michael@0: /* assign to approx [round to length] */ michael@0: approxset.emin-=exp/2; /* adjust to match a */ michael@0: approxset.emax-=exp/2; michael@0: decAddOp(a, &dzero, a, &approxset, 0, &ignore); michael@0: } michael@0: else { michael@0: decAddOp(b, a, t, &workset, 0, &ignore); /* b = a + 0.5 ulp */ michael@0: workset.round=DEC_ROUND_DOWN; michael@0: decMultiplyOp(b, b, b, &workset, &ignore); /* b = mulrd(b, b) */ michael@0: decCompareOp(b, b, f, &workset, COMPARE, &ignore); /* b ? f */ michael@0: if (decNumberIsNegative(b)) { /* b < f */ michael@0: t->exponent++; /* make 1.0 ulp */ michael@0: t->lsu[0]=1; /* .. */ michael@0: decAddOp(a, a, t, &workset, 0, &ignore); /* a = a + 1 ulp */ michael@0: /* assign to approx [round to length] */ michael@0: approxset.emin-=exp/2; /* adjust to match a */ michael@0: approxset.emax-=exp/2; michael@0: decAddOp(a, &dzero, a, &approxset, 0, &ignore); michael@0: } michael@0: } michael@0: /* [no errors are possible in the above, and rounding/inexact during */ michael@0: /* estimation are irrelevant, so status was not accumulated] */ michael@0: michael@0: /* Here, 0.1 <= a < 1 (still), so adjust back */ michael@0: a->exponent+=exp/2; /* set correct exponent */ michael@0: michael@0: /* count droppable zeros [after any subnormal rounding] by */ michael@0: /* trimming a copy */ michael@0: uprv_decNumberCopy(b, a); michael@0: decTrim(b, set, 1, 1, &dropped); /* [drops trailing zeros] */ michael@0: michael@0: /* Set Inexact and Rounded. The answer can only be exact if */ michael@0: /* it is short enough so that squaring it could fit in workp */ michael@0: /* digits, so this is the only (relatively rare) condition that */ michael@0: /* a careful check is needed */ michael@0: if (b->digits*2-1 > workp) { /* cannot fit */ michael@0: status|=DEC_Inexact|DEC_Rounded; michael@0: } michael@0: else { /* could be exact/unrounded */ michael@0: uInt mstatus=0; /* local status */ michael@0: decMultiplyOp(b, b, b, &workset, &mstatus); /* try the multiply */ michael@0: if (mstatus&DEC_Overflow) { /* result just won't fit */ michael@0: status|=DEC_Inexact|DEC_Rounded; michael@0: } michael@0: else { /* plausible */ michael@0: decCompareOp(t, b, rhs, &workset, COMPARE, &mstatus); /* b ? rhs */ michael@0: if (!ISZERO(t)) status|=DEC_Inexact|DEC_Rounded; /* not equal */ michael@0: else { /* is Exact */ michael@0: /* here, dropped is the count of trailing zeros in 'a' */ michael@0: /* use closest exponent to ideal... */ michael@0: Int todrop=ideal-a->exponent; /* most that can be dropped */ michael@0: if (todrop<0) status|=DEC_Rounded; /* ideally would add 0s */ michael@0: else { /* unrounded */ michael@0: /* there are some to drop, but emax may not allow all */ michael@0: Int maxexp=set->emax-set->digits+1; michael@0: Int maxdrop=maxexp-a->exponent; michael@0: if (todrop>maxdrop && set->clamp) { /* apply clamping */ michael@0: todrop=maxdrop; michael@0: status|=DEC_Clamped; michael@0: } michael@0: if (dropped0) { /* have some to drop */ michael@0: decShiftToLeast(a->lsu, D2U(a->digits), todrop); michael@0: a->exponent+=todrop; /* maintain numerical value */ michael@0: a->digits-=todrop; /* new length */ michael@0: } michael@0: } michael@0: } michael@0: } michael@0: } michael@0: michael@0: /* double-check Underflow, as perhaps the result could not have */ michael@0: /* been subnormal (initial argument too big), or it is now Exact */ michael@0: if (status&DEC_Underflow) { michael@0: Int ae=rhs->exponent+rhs->digits-1; /* adjusted exponent */ michael@0: /* check if truly subnormal */ michael@0: #if DECEXTFLAG /* DEC_Subnormal too */ michael@0: if (ae>=set->emin*2) status&=~(DEC_Subnormal|DEC_Underflow); michael@0: #else michael@0: if (ae>=set->emin*2) status&=~DEC_Underflow; michael@0: #endif michael@0: /* check if truly inexact */ michael@0: if (!(status&DEC_Inexact)) status&=~DEC_Underflow; michael@0: } michael@0: michael@0: uprv_decNumberCopy(res, a); /* a is now the result */ michael@0: } while(0); /* end protected */ michael@0: michael@0: if (allocbuff!=NULL) free(allocbuff); /* drop any storage used */ michael@0: if (allocbufa!=NULL) free(allocbufa); /* .. */ michael@0: if (allocbufb!=NULL) free(allocbufb); /* .. */ michael@0: #if DECSUBSET michael@0: if (allocrhs !=NULL) free(allocrhs); /* .. */ michael@0: #endif michael@0: if (status!=0) decStatus(res, status, set);/* then report status */ michael@0: #if DECCHECK michael@0: decCheckInexact(res, set); michael@0: #endif michael@0: return res; michael@0: } /* decNumberSquareRoot */ michael@0: #if defined(__clang__) || U_GCC_MAJOR_MINOR >= 406 michael@0: #pragma GCC diagnostic pop michael@0: #endif michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberSubtract -- subtract two Numbers */ michael@0: /* */ michael@0: /* This computes C = A - B */ michael@0: /* */ michael@0: /* res is C, the result. C may be A and/or B (e.g., X=X-X) */ michael@0: /* lhs is A */ michael@0: /* rhs is B */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberSubtract(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set) { michael@0: uInt status=0; /* accumulator */ michael@0: michael@0: decAddOp(res, lhs, rhs, set, DECNEG, &status); michael@0: if (status!=0) decStatus(res, status, set); michael@0: #if DECCHECK michael@0: decCheckInexact(res, set); michael@0: #endif michael@0: return res; michael@0: } /* decNumberSubtract */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberToIntegralExact -- round-to-integral-value with InExact */ michael@0: /* decNumberToIntegralValue -- round-to-integral-value */ michael@0: /* */ michael@0: /* res is the result */ michael@0: /* rhs is input number */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* res must have space for any value of rhs. */ michael@0: /* */ michael@0: /* This implements the IEEE special operators and therefore treats */ michael@0: /* special values as valid. For finite numbers it returns */ michael@0: /* rescale(rhs, 0) if rhs->exponent is <0. */ michael@0: /* Otherwise the result is rhs (so no error is possible, except for */ michael@0: /* sNaN). */ michael@0: /* */ michael@0: /* The context is used for rounding mode and status after sNaN, but */ michael@0: /* the digits setting is ignored. The Exact version will signal */ michael@0: /* Inexact if the result differs numerically from rhs; the other */ michael@0: /* never signals Inexact. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberToIntegralExact(decNumber *res, const decNumber *rhs, michael@0: decContext *set) { michael@0: decNumber dn; michael@0: decContext workset; /* working context */ michael@0: uInt status=0; /* accumulator */ michael@0: michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; michael@0: #endif michael@0: michael@0: /* handle infinities and NaNs */ michael@0: if (SPECIALARG) { michael@0: if (decNumberIsInfinite(rhs)) uprv_decNumberCopy(res, rhs); /* an Infinity */ michael@0: else decNaNs(res, rhs, NULL, set, &status); /* a NaN */ michael@0: } michael@0: else { /* finite */ michael@0: /* have a finite number; no error possible (res must be big enough) */ michael@0: if (rhs->exponent>=0) return uprv_decNumberCopy(res, rhs); michael@0: /* that was easy, but if negative exponent there is work to do... */ michael@0: workset=*set; /* clone rounding, etc. */ michael@0: workset.digits=rhs->digits; /* no length rounding */ michael@0: workset.traps=0; /* no traps */ michael@0: uprv_decNumberZero(&dn); /* make a number with exponent 0 */ michael@0: uprv_decNumberQuantize(res, rhs, &dn, &workset); michael@0: status|=workset.status; michael@0: } michael@0: if (status!=0) decStatus(res, status, set); michael@0: return res; michael@0: } /* decNumberToIntegralExact */ michael@0: michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberToIntegralValue(decNumber *res, const decNumber *rhs, michael@0: decContext *set) { michael@0: decContext workset=*set; /* working context */ michael@0: workset.traps=0; /* no traps */ michael@0: uprv_decNumberToIntegralExact(res, rhs, &workset); michael@0: /* this never affects set, except for sNaNs; NaN will have been set */ michael@0: /* or propagated already, so no need to call decStatus */ michael@0: set->status|=workset.status&DEC_Invalid_operation; michael@0: return res; michael@0: } /* decNumberToIntegralValue */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberXor -- XOR two Numbers, digitwise */ michael@0: /* */ michael@0: /* This computes C = A ^ B */ michael@0: /* */ michael@0: /* res is C, the result. C may be A and/or B (e.g., X=X^X) */ michael@0: /* lhs is A */ michael@0: /* rhs is B */ michael@0: /* set is the context (used for result length and error report) */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* */ michael@0: /* Logical function restrictions apply (see above); a NaN is */ michael@0: /* returned with Invalid_operation if a restriction is violated. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberXor(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set) { michael@0: const Unit *ua, *ub; /* -> operands */ michael@0: const Unit *msua, *msub; /* -> operand msus */ michael@0: Unit *uc, *msuc; /* -> result and its msu */ michael@0: Int msudigs; /* digits in res msu */ michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, lhs, rhs, set)) return res; michael@0: #endif michael@0: michael@0: if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs) michael@0: || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) { michael@0: decStatus(res, DEC_Invalid_operation, set); michael@0: return res; michael@0: } michael@0: /* operands are valid */ michael@0: ua=lhs->lsu; /* bottom-up */ michael@0: ub=rhs->lsu; /* .. */ michael@0: uc=res->lsu; /* .. */ michael@0: msua=ua+D2U(lhs->digits)-1; /* -> msu of lhs */ michael@0: msub=ub+D2U(rhs->digits)-1; /* -> msu of rhs */ michael@0: msuc=uc+D2U(set->digits)-1; /* -> msu of result */ michael@0: msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */ michael@0: for (; uc<=msuc; ua++, ub++, uc++) { /* Unit loop */ michael@0: Unit a, b; /* extract units */ michael@0: if (ua>msua) a=0; michael@0: else a=*ua; michael@0: if (ub>msub) b=0; michael@0: else b=*ub; michael@0: *uc=0; /* can now write back */ michael@0: if (a|b) { /* maybe 1 bits to examine */ michael@0: Int i, j; michael@0: /* This loop could be unrolled and/or use BIN2BCD tables */ michael@0: for (i=0; i1) { michael@0: decStatus(res, DEC_Invalid_operation, set); michael@0: return res; michael@0: } michael@0: if (uc==msuc && i==msudigs-1) break; /* just did final digit */ michael@0: } /* each digit */ michael@0: } /* non-zero */ michael@0: } /* each unit */ michael@0: /* [here uc-1 is the msu of the result] */ michael@0: res->digits=decGetDigits(res->lsu, uc-res->lsu); michael@0: res->exponent=0; /* integer */ michael@0: res->bits=0; /* sign=0 */ michael@0: return res; /* [no status to set] */ michael@0: } /* decNumberXor */ michael@0: michael@0: michael@0: /* ================================================================== */ michael@0: /* Utility routines */ michael@0: /* ================================================================== */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberClass -- return the decClass of a decNumber */ michael@0: /* dn -- the decNumber to test */ michael@0: /* set -- the context to use for Emin */ michael@0: /* returns the decClass enum */ michael@0: /* ------------------------------------------------------------------ */ michael@0: enum decClass uprv_decNumberClass(const decNumber *dn, decContext *set) { michael@0: if (decNumberIsSpecial(dn)) { michael@0: if (decNumberIsQNaN(dn)) return DEC_CLASS_QNAN; michael@0: if (decNumberIsSNaN(dn)) return DEC_CLASS_SNAN; michael@0: /* must be an infinity */ michael@0: if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_INF; michael@0: return DEC_CLASS_POS_INF; michael@0: } michael@0: /* is finite */ michael@0: if (uprv_decNumberIsNormal(dn, set)) { /* most common */ michael@0: if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_NORMAL; michael@0: return DEC_CLASS_POS_NORMAL; michael@0: } michael@0: /* is subnormal or zero */ michael@0: if (decNumberIsZero(dn)) { /* most common */ michael@0: if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_ZERO; michael@0: return DEC_CLASS_POS_ZERO; michael@0: } michael@0: if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_SUBNORMAL; michael@0: return DEC_CLASS_POS_SUBNORMAL; michael@0: } /* decNumberClass */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberClassToString -- convert decClass to a string */ michael@0: /* */ michael@0: /* eclass is a valid decClass */ michael@0: /* returns a constant string describing the class (max 13+1 chars) */ michael@0: /* ------------------------------------------------------------------ */ michael@0: const char *uprv_decNumberClassToString(enum decClass eclass) { michael@0: if (eclass==DEC_CLASS_POS_NORMAL) return DEC_ClassString_PN; michael@0: if (eclass==DEC_CLASS_NEG_NORMAL) return DEC_ClassString_NN; michael@0: if (eclass==DEC_CLASS_POS_ZERO) return DEC_ClassString_PZ; michael@0: if (eclass==DEC_CLASS_NEG_ZERO) return DEC_ClassString_NZ; michael@0: if (eclass==DEC_CLASS_POS_SUBNORMAL) return DEC_ClassString_PS; michael@0: if (eclass==DEC_CLASS_NEG_SUBNORMAL) return DEC_ClassString_NS; michael@0: if (eclass==DEC_CLASS_POS_INF) return DEC_ClassString_PI; michael@0: if (eclass==DEC_CLASS_NEG_INF) return DEC_ClassString_NI; michael@0: if (eclass==DEC_CLASS_QNAN) return DEC_ClassString_QN; michael@0: if (eclass==DEC_CLASS_SNAN) return DEC_ClassString_SN; michael@0: return DEC_ClassString_UN; /* Unknown */ michael@0: } /* decNumberClassToString */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberCopy -- copy a number */ michael@0: /* */ michael@0: /* dest is the target decNumber */ michael@0: /* src is the source decNumber */ michael@0: /* returns dest */ michael@0: /* */ michael@0: /* (dest==src is allowed and is a no-op) */ michael@0: /* All fields are updated as required. This is a utility operation, */ michael@0: /* so special values are unchanged and no error is possible. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopy(decNumber *dest, const decNumber *src) { michael@0: michael@0: #if DECCHECK michael@0: if (src==NULL) return uprv_decNumberZero(dest); michael@0: #endif michael@0: michael@0: if (dest==src) return dest; /* no copy required */ michael@0: michael@0: /* Use explicit assignments here as structure assignment could copy */ michael@0: /* more than just the lsu (for small DECDPUN). This would not affect */ michael@0: /* the value of the results, but could disturb test harness spill */ michael@0: /* checking. */ michael@0: dest->bits=src->bits; michael@0: dest->exponent=src->exponent; michael@0: dest->digits=src->digits; michael@0: dest->lsu[0]=src->lsu[0]; michael@0: if (src->digits>DECDPUN) { /* more Units to come */ michael@0: const Unit *smsup, *s; /* work */ michael@0: Unit *d; /* .. */ michael@0: /* memcpy for the remaining Units would be safe as they cannot */ michael@0: /* overlap. However, this explicit loop is faster in short cases. */ michael@0: d=dest->lsu+1; /* -> first destination */ michael@0: smsup=src->lsu+D2U(src->digits); /* -> source msu+1 */ michael@0: for (s=src->lsu+1; sdigits digits. */ michael@0: /* No exception or error can occur; this is a quiet bitwise operation.*/ michael@0: /* See also decNumberAbs for a checking version of this. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopyAbs(decNumber *res, const decNumber *rhs) { michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res; michael@0: #endif michael@0: uprv_decNumberCopy(res, rhs); michael@0: res->bits&=~DECNEG; /* turn off sign */ michael@0: return res; michael@0: } /* decNumberCopyAbs */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberCopyNegate -- quiet negate value operator */ michael@0: /* */ michael@0: /* This sets C = negate(A) */ michael@0: /* */ michael@0: /* res is C, the result. C may be A */ michael@0: /* rhs is A */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* No exception or error can occur; this is a quiet bitwise operation.*/ michael@0: /* See also decNumberMinus for a checking version of this. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopyNegate(decNumber *res, const decNumber *rhs) { michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res; michael@0: #endif michael@0: uprv_decNumberCopy(res, rhs); michael@0: res->bits^=DECNEG; /* invert the sign */ michael@0: return res; michael@0: } /* decNumberCopyNegate */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberCopySign -- quiet copy and set sign operator */ michael@0: /* */ michael@0: /* This sets C = A with the sign of B */ michael@0: /* */ michael@0: /* res is C, the result. C may be A */ michael@0: /* lhs is A */ michael@0: /* rhs is B */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* No exception or error can occur; this is a quiet bitwise operation.*/ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopySign(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs) { michael@0: uByte sign; /* rhs sign */ michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res; michael@0: #endif michael@0: sign=rhs->bits & DECNEG; /* save sign bit */ michael@0: uprv_decNumberCopy(res, lhs); michael@0: res->bits&=~DECNEG; /* clear the sign */ michael@0: res->bits|=sign; /* set from rhs */ michael@0: return res; michael@0: } /* decNumberCopySign */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberGetBCD -- get the coefficient in BCD8 */ michael@0: /* dn is the source decNumber */ michael@0: /* bcd is the uInt array that will receive dn->digits BCD bytes, */ michael@0: /* most-significant at offset 0 */ michael@0: /* returns bcd */ michael@0: /* */ michael@0: /* bcd must have at least dn->digits bytes. No error is possible; if */ michael@0: /* dn is a NaN or Infinite, digits must be 1 and the coefficient 0. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI uByte * U_EXPORT2 uprv_decNumberGetBCD(const decNumber *dn, uByte *bcd) { michael@0: uByte *ub=bcd+dn->digits-1; /* -> lsd */ michael@0: const Unit *up=dn->lsu; /* Unit pointer, -> lsu */ michael@0: michael@0: #if DECDPUN==1 /* trivial simple copy */ michael@0: for (; ub>=bcd; ub--, up++) *ub=*up; michael@0: #else /* chopping needed */ michael@0: uInt u=*up; /* work */ michael@0: uInt cut=DECDPUN; /* downcounter through unit */ michael@0: for (; ub>=bcd; ub--) { michael@0: *ub=(uByte)(u%10); /* [*6554 trick inhibits, here] */ michael@0: u=u/10; michael@0: cut--; michael@0: if (cut>0) continue; /* more in this unit */ michael@0: up++; michael@0: u=*up; michael@0: cut=DECDPUN; michael@0: } michael@0: #endif michael@0: return bcd; michael@0: } /* decNumberGetBCD */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberSetBCD -- set (replace) the coefficient from BCD8 */ michael@0: /* dn is the target decNumber */ michael@0: /* bcd is the uInt array that will source n BCD bytes, most- */ michael@0: /* significant at offset 0 */ michael@0: /* n is the number of digits in the source BCD array (bcd) */ michael@0: /* returns dn */ michael@0: /* */ michael@0: /* dn must have space for at least n digits. No error is possible; */ michael@0: /* if dn is a NaN, or Infinite, or is to become a zero, n must be 1 */ michael@0: /* and bcd[0] zero. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberSetBCD(decNumber *dn, const uByte *bcd, uInt n) { michael@0: Unit *up=dn->lsu+D2U(dn->digits)-1; /* -> msu [target pointer] */ michael@0: const uByte *ub=bcd; /* -> source msd */ michael@0: michael@0: #if DECDPUN==1 /* trivial simple copy */ michael@0: for (; ub=dn->lsu; up--) { /* each Unit from msu */ michael@0: *up=0; /* will take <=DECDPUN digits */ michael@0: for (; cut>0; ub++, cut--) *up=X10(*up)+*ub; michael@0: cut=DECDPUN; /* next Unit has all digits */ michael@0: } michael@0: #endif michael@0: dn->digits=n; /* set digit count */ michael@0: return dn; michael@0: } /* decNumberSetBCD */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberIsNormal -- test normality of a decNumber */ michael@0: /* dn is the decNumber to test */ michael@0: /* set is the context to use for Emin */ michael@0: /* returns 1 if |dn| is finite and >=Nmin, 0 otherwise */ michael@0: /* ------------------------------------------------------------------ */ michael@0: Int uprv_decNumberIsNormal(const decNumber *dn, decContext *set) { michael@0: Int ae; /* adjusted exponent */ michael@0: #if DECCHECK michael@0: if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0; michael@0: #endif michael@0: michael@0: if (decNumberIsSpecial(dn)) return 0; /* not finite */ michael@0: if (decNumberIsZero(dn)) return 0; /* not non-zero */ michael@0: michael@0: ae=dn->exponent+dn->digits-1; /* adjusted exponent */ michael@0: if (aeemin) return 0; /* is subnormal */ michael@0: return 1; michael@0: } /* decNumberIsNormal */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberIsSubnormal -- test subnormality of a decNumber */ michael@0: /* dn is the decNumber to test */ michael@0: /* set is the context to use for Emin */ michael@0: /* returns 1 if |dn| is finite, non-zero, and exponent+dn->digits-1; /* adjusted exponent */ michael@0: if (aeemin) return 1; /* is subnormal */ michael@0: return 0; michael@0: } /* decNumberIsSubnormal */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberTrim -- remove insignificant zeros */ michael@0: /* */ michael@0: /* dn is the number to trim */ michael@0: /* returns dn */ michael@0: /* */ michael@0: /* All fields are updated as required. This is a utility operation, */ michael@0: /* so special values are unchanged and no error is possible. The */ michael@0: /* zeros are removed unconditionally. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberTrim(decNumber *dn) { michael@0: Int dropped; /* work */ michael@0: decContext set; /* .. */ michael@0: #if DECCHECK michael@0: if (decCheckOperands(DECUNRESU, DECUNUSED, dn, DECUNCONT)) return dn; michael@0: #endif michael@0: uprv_decContextDefault(&set, DEC_INIT_BASE); /* clamp=0 */ michael@0: return decTrim(dn, &set, 0, 1, &dropped); michael@0: } /* decNumberTrim */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberVersion -- return the name and version of this module */ michael@0: /* */ michael@0: /* No error is possible. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: const char * uprv_decNumberVersion(void) { michael@0: return DECVERSION; michael@0: } /* decNumberVersion */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberZero -- set a number to 0 */ michael@0: /* */ michael@0: /* dn is the number to set, with space for one digit */ michael@0: /* returns dn */ michael@0: /* */ michael@0: /* No error is possible. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: /* Memset is not used as it is much slower in some environments. */ michael@0: U_CAPI decNumber * U_EXPORT2 uprv_decNumberZero(decNumber *dn) { michael@0: michael@0: #if DECCHECK michael@0: if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn; michael@0: #endif michael@0: michael@0: dn->bits=0; michael@0: dn->exponent=0; michael@0: dn->digits=1; michael@0: dn->lsu[0]=0; michael@0: return dn; michael@0: } /* decNumberZero */ michael@0: michael@0: /* ================================================================== */ michael@0: /* Local routines */ michael@0: /* ================================================================== */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decToString -- lay out a number into a string */ michael@0: /* */ michael@0: /* dn is the number to lay out */ michael@0: /* string is where to lay out the number */ michael@0: /* eng is 1 if Engineering, 0 if Scientific */ michael@0: /* */ michael@0: /* string must be at least dn->digits+14 characters long */ michael@0: /* No error is possible. */ michael@0: /* */ michael@0: /* Note that this routine can generate a -0 or 0.000. These are */ michael@0: /* never generated in subset to-number or arithmetic, but can occur */ michael@0: /* in non-subset arithmetic (e.g., -1*0 or 1.234-1.234). */ michael@0: /* ------------------------------------------------------------------ */ michael@0: /* If DECCHECK is enabled the string "?" is returned if a number is */ michael@0: /* invalid. */ michael@0: static void decToString(const decNumber *dn, char *string, Flag eng) { michael@0: Int exp=dn->exponent; /* local copy */ michael@0: Int e; /* E-part value */ michael@0: Int pre; /* digits before the '.' */ michael@0: Int cut; /* for counting digits in a Unit */ michael@0: char *c=string; /* work [output pointer] */ michael@0: const Unit *up=dn->lsu+D2U(dn->digits)-1; /* -> msu [input pointer] */ michael@0: uInt u, pow; /* work */ michael@0: michael@0: #if DECCHECK michael@0: if (decCheckOperands(DECUNRESU, dn, DECUNUSED, DECUNCONT)) { michael@0: strcpy(string, "?"); michael@0: return;} michael@0: #endif michael@0: michael@0: if (decNumberIsNegative(dn)) { /* Negatives get a minus */ michael@0: *c='-'; michael@0: c++; michael@0: } michael@0: if (dn->bits&DECSPECIAL) { /* Is a special value */ michael@0: if (decNumberIsInfinite(dn)) { michael@0: strcpy(c, "Inf"); michael@0: strcpy(c+3, "inity"); michael@0: return;} michael@0: /* a NaN */ michael@0: if (dn->bits&DECSNAN) { /* signalling NaN */ michael@0: *c='s'; michael@0: c++; michael@0: } michael@0: strcpy(c, "NaN"); michael@0: c+=3; /* step past */ michael@0: /* if not a clean non-zero coefficient, that's all there is in a */ michael@0: /* NaN string */ michael@0: if (exp!=0 || (*dn->lsu==0 && dn->digits==1)) return; michael@0: /* [drop through to add integer] */ michael@0: } michael@0: michael@0: /* calculate how many digits in msu, and hence first cut */ michael@0: cut=MSUDIGITS(dn->digits); /* [faster than remainder] */ michael@0: cut--; /* power of ten for digit */ michael@0: michael@0: if (exp==0) { /* simple integer [common fastpath] */ michael@0: for (;up>=dn->lsu; up--) { /* each Unit from msu */ michael@0: u=*up; /* contains DECDPUN digits to lay out */ michael@0: for (; cut>=0; c++, cut--) TODIGIT(u, cut, c, pow); michael@0: cut=DECDPUN-1; /* next Unit has all digits */ michael@0: } michael@0: *c='\0'; /* terminate the string */ michael@0: return;} michael@0: michael@0: /* non-0 exponent -- assume plain form */ michael@0: pre=dn->digits+exp; /* digits before '.' */ michael@0: e=0; /* no E */ michael@0: if ((exp>0) || (pre<-5)) { /* need exponential form */ michael@0: e=exp+dn->digits-1; /* calculate E value */ michael@0: pre=1; /* assume one digit before '.' */ michael@0: if (eng && (e!=0)) { /* engineering: may need to adjust */ michael@0: Int adj; /* adjustment */ michael@0: /* The C remainder operator is undefined for negative numbers, so */ michael@0: /* a positive remainder calculation must be used here */ michael@0: if (e<0) { michael@0: adj=(-e)%3; michael@0: if (adj!=0) adj=3-adj; michael@0: } michael@0: else { /* e>0 */ michael@0: adj=e%3; michael@0: } michael@0: e=e-adj; michael@0: /* if dealing with zero still produce an exponent which is a */ michael@0: /* multiple of three, as expected, but there will only be the */ michael@0: /* one zero before the E, still. Otherwise note the padding. */ michael@0: if (!ISZERO(dn)) pre+=adj; michael@0: else { /* is zero */ michael@0: if (adj!=0) { /* 0.00Esnn needed */ michael@0: e=e+3; michael@0: pre=-(2-adj); michael@0: } michael@0: } /* zero */ michael@0: } /* eng */ michael@0: } /* need exponent */ michael@0: michael@0: /* lay out the digits of the coefficient, adding 0s and . as needed */ michael@0: u=*up; michael@0: if (pre>0) { /* xxx.xxx or xx00 (engineering) form */ michael@0: Int n=pre; michael@0: for (; pre>0; pre--, c++, cut--) { michael@0: if (cut<0) { /* need new Unit */ michael@0: if (up==dn->lsu) break; /* out of input digits (pre>digits) */ michael@0: up--; michael@0: cut=DECDPUN-1; michael@0: u=*up; michael@0: } michael@0: TODIGIT(u, cut, c, pow); michael@0: } michael@0: if (ndigits) { /* more to come, after '.' */ michael@0: *c='.'; c++; michael@0: for (;; c++, cut--) { michael@0: if (cut<0) { /* need new Unit */ michael@0: if (up==dn->lsu) break; /* out of input digits */ michael@0: up--; michael@0: cut=DECDPUN-1; michael@0: u=*up; michael@0: } michael@0: TODIGIT(u, cut, c, pow); michael@0: } michael@0: } michael@0: else for (; pre>0; pre--, c++) *c='0'; /* 0 padding (for engineering) needed */ michael@0: } michael@0: else { /* 0.xxx or 0.000xxx form */ michael@0: *c='0'; c++; michael@0: *c='.'; c++; michael@0: for (; pre<0; pre++, c++) *c='0'; /* add any 0's after '.' */ michael@0: for (; ; c++, cut--) { michael@0: if (cut<0) { /* need new Unit */ michael@0: if (up==dn->lsu) break; /* out of input digits */ michael@0: up--; michael@0: cut=DECDPUN-1; michael@0: u=*up; michael@0: } michael@0: TODIGIT(u, cut, c, pow); michael@0: } michael@0: } michael@0: michael@0: /* Finally add the E-part, if needed. It will never be 0, has a michael@0: base maximum and minimum of +999999999 through -999999999, but michael@0: could range down to -1999999998 for anormal numbers */ michael@0: if (e!=0) { michael@0: Flag had=0; /* 1=had non-zero */ michael@0: *c='E'; c++; michael@0: *c='+'; c++; /* assume positive */ michael@0: u=e; /* .. */ michael@0: if (e<0) { michael@0: *(c-1)='-'; /* oops, need - */ michael@0: u=-e; /* uInt, please */ michael@0: } michael@0: /* lay out the exponent [_itoa or equivalent is not ANSI C] */ michael@0: for (cut=9; cut>=0; cut--) { michael@0: TODIGIT(u, cut, c, pow); michael@0: if (*c=='0' && !had) continue; /* skip leading zeros */ michael@0: had=1; /* had non-0 */ michael@0: c++; /* step for next */ michael@0: } /* cut */ michael@0: } michael@0: *c='\0'; /* terminate the string (all paths) */ michael@0: return; michael@0: } /* decToString */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decAddOp -- add/subtract operation */ michael@0: /* */ michael@0: /* This computes C = A + B */ michael@0: /* */ michael@0: /* res is C, the result. C may be A and/or B (e.g., X=X+X) */ michael@0: /* lhs is A */ michael@0: /* rhs is B */ michael@0: /* set is the context */ michael@0: /* negate is DECNEG if rhs should be negated, or 0 otherwise */ michael@0: /* status accumulates status for the caller */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* Inexact in status must be 0 for correct Exact zero sign in result */ michael@0: /* ------------------------------------------------------------------ */ michael@0: /* If possible, the coefficient is calculated directly into C. */ michael@0: /* However, if: */ michael@0: /* -- a digits+1 calculation is needed because the numbers are */ michael@0: /* unaligned and span more than set->digits digits */ michael@0: /* -- a carry to digits+1 digits looks possible */ michael@0: /* -- C is the same as A or B, and the result would destructively */ michael@0: /* overlap the A or B coefficient */ michael@0: /* then the result must be calculated into a temporary buffer. In */ michael@0: /* this case a local (stack) buffer is used if possible, and only if */ michael@0: /* too long for that does malloc become the final resort. */ michael@0: /* */ michael@0: /* Misalignment is handled as follows: */ michael@0: /* Apad: (AExp>BExp) Swap operands and proceed as for BExp>AExp. */ michael@0: /* BPad: Apply the padding by a combination of shifting (whole */ michael@0: /* units) and multiplication (part units). */ michael@0: /* */ michael@0: /* Addition, especially x=x+1, is speed-critical. */ michael@0: /* The static buffer is larger than might be expected to allow for */ michael@0: /* calls from higher-level funtions (notable exp). */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static decNumber * decAddOp(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set, michael@0: uByte negate, uInt *status) { michael@0: #if DECSUBSET michael@0: decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */ michael@0: decNumber *allocrhs=NULL; /* .., rhs */ michael@0: #endif michael@0: Int rhsshift; /* working shift (in Units) */ michael@0: Int maxdigits; /* longest logical length */ michael@0: Int mult; /* multiplier */ michael@0: Int residue; /* rounding accumulator */ michael@0: uByte bits; /* result bits */ michael@0: Flag diffsign; /* non-0 if arguments have different sign */ michael@0: Unit *acc; /* accumulator for result */ michael@0: Unit accbuff[SD2U(DECBUFFER*2+20)]; /* local buffer [*2+20 reduces many */ michael@0: /* allocations when called from */ michael@0: /* other operations, notable exp] */ michael@0: Unit *allocacc=NULL; /* -> allocated acc buffer, iff allocated */ michael@0: Int reqdigits=set->digits; /* local copy; requested DIGITS */ michael@0: Int padding; /* work */ michael@0: michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, lhs, rhs, set)) return res; michael@0: #endif michael@0: michael@0: do { /* protect allocated storage */ michael@0: #if DECSUBSET michael@0: if (!set->extended) { michael@0: /* reduce operands and set lostDigits status, as needed */ michael@0: if (lhs->digits>reqdigits) { michael@0: alloclhs=decRoundOperand(lhs, set, status); michael@0: if (alloclhs==NULL) break; michael@0: lhs=alloclhs; michael@0: } michael@0: if (rhs->digits>reqdigits) { michael@0: allocrhs=decRoundOperand(rhs, set, status); michael@0: if (allocrhs==NULL) break; michael@0: rhs=allocrhs; michael@0: } michael@0: } michael@0: #endif michael@0: /* [following code does not require input rounding] */ michael@0: michael@0: /* note whether signs differ [used all paths] */ michael@0: diffsign=(Flag)((lhs->bits^rhs->bits^negate)&DECNEG); michael@0: michael@0: /* handle infinities and NaNs */ michael@0: if (SPECIALARGS) { /* a special bit set */ michael@0: if (SPECIALARGS & (DECSNAN | DECNAN)) /* a NaN */ michael@0: decNaNs(res, lhs, rhs, set, status); michael@0: else { /* one or two infinities */ michael@0: if (decNumberIsInfinite(lhs)) { /* LHS is infinity */ michael@0: /* two infinities with different signs is invalid */ michael@0: if (decNumberIsInfinite(rhs) && diffsign) { michael@0: *status|=DEC_Invalid_operation; michael@0: break; michael@0: } michael@0: bits=lhs->bits & DECNEG; /* get sign from LHS */ michael@0: } michael@0: else bits=(rhs->bits^negate) & DECNEG;/* RHS must be Infinity */ michael@0: bits|=DECINF; michael@0: uprv_decNumberZero(res); michael@0: res->bits=bits; /* set +/- infinity */ michael@0: } /* an infinity */ michael@0: break; michael@0: } michael@0: michael@0: /* Quick exit for add 0s; return the non-0, modified as need be */ michael@0: if (ISZERO(lhs)) { michael@0: Int adjust; /* work */ michael@0: Int lexp=lhs->exponent; /* save in case LHS==RES */ michael@0: bits=lhs->bits; /* .. */ michael@0: residue=0; /* clear accumulator */ michael@0: decCopyFit(res, rhs, set, &residue, status); /* copy (as needed) */ michael@0: res->bits^=negate; /* flip if rhs was negated */ michael@0: #if DECSUBSET michael@0: if (set->extended) { /* exponents on zeros count */ michael@0: #endif michael@0: /* exponent will be the lower of the two */ michael@0: adjust=lexp-res->exponent; /* adjustment needed [if -ve] */ michael@0: if (ISZERO(res)) { /* both 0: special IEEE 754 rules */ michael@0: if (adjust<0) res->exponent=lexp; /* set exponent */ michael@0: /* 0-0 gives +0 unless rounding to -infinity, and -0-0 gives -0 */ michael@0: if (diffsign) { michael@0: if (set->round!=DEC_ROUND_FLOOR) res->bits=0; michael@0: else res->bits=DECNEG; /* preserve 0 sign */ michael@0: } michael@0: } michael@0: else { /* non-0 res */ michael@0: if (adjust<0) { /* 0-padding needed */ michael@0: if ((res->digits-adjust)>set->digits) { michael@0: adjust=res->digits-set->digits; /* to fit exactly */ michael@0: *status|=DEC_Rounded; /* [but exact] */ michael@0: } michael@0: res->digits=decShiftToMost(res->lsu, res->digits, -adjust); michael@0: res->exponent+=adjust; /* set the exponent. */ michael@0: } michael@0: } /* non-0 res */ michael@0: #if DECSUBSET michael@0: } /* extended */ michael@0: #endif michael@0: decFinish(res, set, &residue, status); /* clean and finalize */ michael@0: break;} michael@0: michael@0: if (ISZERO(rhs)) { /* [lhs is non-zero] */ michael@0: Int adjust; /* work */ michael@0: Int rexp=rhs->exponent; /* save in case RHS==RES */ michael@0: bits=rhs->bits; /* be clean */ michael@0: residue=0; /* clear accumulator */ michael@0: decCopyFit(res, lhs, set, &residue, status); /* copy (as needed) */ michael@0: #if DECSUBSET michael@0: if (set->extended) { /* exponents on zeros count */ michael@0: #endif michael@0: /* exponent will be the lower of the two */ michael@0: /* [0-0 case handled above] */ michael@0: adjust=rexp-res->exponent; /* adjustment needed [if -ve] */ michael@0: if (adjust<0) { /* 0-padding needed */ michael@0: if ((res->digits-adjust)>set->digits) { michael@0: adjust=res->digits-set->digits; /* to fit exactly */ michael@0: *status|=DEC_Rounded; /* [but exact] */ michael@0: } michael@0: res->digits=decShiftToMost(res->lsu, res->digits, -adjust); michael@0: res->exponent+=adjust; /* set the exponent. */ michael@0: } michael@0: #if DECSUBSET michael@0: } /* extended */ michael@0: #endif michael@0: decFinish(res, set, &residue, status); /* clean and finalize */ michael@0: break;} michael@0: michael@0: /* [NB: both fastpath and mainpath code below assume these cases */ michael@0: /* (notably 0-0) have already been handled] */ michael@0: michael@0: /* calculate the padding needed to align the operands */ michael@0: padding=rhs->exponent-lhs->exponent; michael@0: michael@0: /* Fastpath cases where the numbers are aligned and normal, the RHS */ michael@0: /* is all in one unit, no operand rounding is needed, and no carry, */ michael@0: /* lengthening, or borrow is needed */ michael@0: if (padding==0 michael@0: && rhs->digits<=DECDPUN michael@0: && rhs->exponent>=set->emin /* [some normals drop through] */ michael@0: && rhs->exponent<=set->emax-set->digits+1 /* [could clamp] */ michael@0: && rhs->digits<=reqdigits michael@0: && lhs->digits<=reqdigits) { michael@0: Int partial=*lhs->lsu; michael@0: if (!diffsign) { /* adding */ michael@0: partial+=*rhs->lsu; michael@0: if ((partial<=DECDPUNMAX) /* result fits in unit */ michael@0: && (lhs->digits>=DECDPUN || /* .. and no digits-count change */ michael@0: partial<(Int)powers[lhs->digits])) { /* .. */ michael@0: if (res!=lhs) uprv_decNumberCopy(res, lhs); /* not in place */ michael@0: *res->lsu=(Unit)partial; /* [copy could have overwritten RHS] */ michael@0: break; michael@0: } michael@0: /* else drop out for careful add */ michael@0: } michael@0: else { /* signs differ */ michael@0: partial-=*rhs->lsu; michael@0: if (partial>0) { /* no borrow needed, and non-0 result */ michael@0: if (res!=lhs) uprv_decNumberCopy(res, lhs); /* not in place */ michael@0: *res->lsu=(Unit)partial; michael@0: /* this could have reduced digits [but result>0] */ michael@0: res->digits=decGetDigits(res->lsu, D2U(res->digits)); michael@0: break; michael@0: } michael@0: /* else drop out for careful subtract */ michael@0: } michael@0: } michael@0: michael@0: /* Now align (pad) the lhs or rhs so they can be added or */ michael@0: /* subtracted, as necessary. If one number is much larger than */ michael@0: /* the other (that is, if in plain form there is a least one */ michael@0: /* digit between the lowest digit of one and the highest of the */ michael@0: /* other) padding with up to DIGITS-1 trailing zeros may be */ michael@0: /* needed; then apply rounding (as exotic rounding modes may be */ michael@0: /* affected by the residue). */ michael@0: rhsshift=0; /* rhs shift to left (padding) in Units */ michael@0: bits=lhs->bits; /* assume sign is that of LHS */ michael@0: mult=1; /* likely multiplier */ michael@0: michael@0: /* [if padding==0 the operands are aligned; no padding is needed] */ michael@0: if (padding!=0) { michael@0: /* some padding needed; always pad the RHS, as any required */ michael@0: /* padding can then be effected by a simple combination of */ michael@0: /* shifts and a multiply */ michael@0: Flag swapped=0; michael@0: if (padding<0) { /* LHS needs the padding */ michael@0: const decNumber *t; michael@0: padding=-padding; /* will be +ve */ michael@0: bits=(uByte)(rhs->bits^negate); /* assumed sign is now that of RHS */ michael@0: t=lhs; lhs=rhs; rhs=t; michael@0: swapped=1; michael@0: } michael@0: michael@0: /* If, after pad, rhs would be longer than lhs by digits+1 or */ michael@0: /* more then lhs cannot affect the answer, except as a residue, */ michael@0: /* so only need to pad up to a length of DIGITS+1. */ michael@0: if (rhs->digits+padding > lhs->digits+reqdigits+1) { michael@0: /* The RHS is sufficient */ michael@0: /* for residue use the relative sign indication... */ michael@0: Int shift=reqdigits-rhs->digits; /* left shift needed */ michael@0: residue=1; /* residue for rounding */ michael@0: if (diffsign) residue=-residue; /* signs differ */ michael@0: /* copy, shortening if necessary */ michael@0: decCopyFit(res, rhs, set, &residue, status); michael@0: /* if it was already shorter, then need to pad with zeros */ michael@0: if (shift>0) { michael@0: res->digits=decShiftToMost(res->lsu, res->digits, shift); michael@0: res->exponent-=shift; /* adjust the exponent. */ michael@0: } michael@0: /* flip the result sign if unswapped and rhs was negated */ michael@0: if (!swapped) res->bits^=negate; michael@0: decFinish(res, set, &residue, status); /* done */ michael@0: break;} michael@0: michael@0: /* LHS digits may affect result */ michael@0: rhsshift=D2U(padding+1)-1; /* this much by Unit shift .. */ michael@0: mult=powers[padding-(rhsshift*DECDPUN)]; /* .. this by multiplication */ michael@0: } /* padding needed */ michael@0: michael@0: if (diffsign) mult=-mult; /* signs differ */ michael@0: michael@0: /* determine the longer operand */ michael@0: maxdigits=rhs->digits+padding; /* virtual length of RHS */ michael@0: if (lhs->digits>maxdigits) maxdigits=lhs->digits; michael@0: michael@0: /* Decide on the result buffer to use; if possible place directly */ michael@0: /* into result. */ michael@0: acc=res->lsu; /* assume add direct to result */ michael@0: /* If destructive overlap, or the number is too long, or a carry or */ michael@0: /* borrow to DIGITS+1 might be possible, a buffer must be used. */ michael@0: /* [Might be worth more sophisticated tests when maxdigits==reqdigits] */ michael@0: if ((maxdigits>=reqdigits) /* is, or could be, too large */ michael@0: || (res==rhs && rhsshift>0)) { /* destructive overlap */ michael@0: /* buffer needed, choose it; units for maxdigits digits will be */ michael@0: /* needed, +1 Unit for carry or borrow */ michael@0: Int need=D2U(maxdigits)+1; michael@0: acc=accbuff; /* assume use local buffer */ michael@0: if (need*sizeof(Unit)>sizeof(accbuff)) { michael@0: /* printf("malloc add %ld %ld\n", need, sizeof(accbuff)); */ michael@0: allocacc=(Unit *)malloc(need*sizeof(Unit)); michael@0: if (allocacc==NULL) { /* hopeless -- abandon */ michael@0: *status|=DEC_Insufficient_storage; michael@0: break;} michael@0: acc=allocacc; michael@0: } michael@0: } michael@0: michael@0: res->bits=(uByte)(bits&DECNEG); /* it's now safe to overwrite.. */ michael@0: res->exponent=lhs->exponent; /* .. operands (even if aliased) */ michael@0: michael@0: #if DECTRACE michael@0: decDumpAr('A', lhs->lsu, D2U(lhs->digits)); michael@0: decDumpAr('B', rhs->lsu, D2U(rhs->digits)); michael@0: printf(" :h: %ld %ld\n", rhsshift, mult); michael@0: #endif michael@0: michael@0: /* add [A+B*m] or subtract [A+B*(-m)] */ michael@0: U_ASSERT(rhs->digits > 0); michael@0: U_ASSERT(lhs->digits > 0); michael@0: res->digits=decUnitAddSub(lhs->lsu, D2U(lhs->digits), michael@0: rhs->lsu, D2U(rhs->digits), michael@0: rhsshift, acc, mult) michael@0: *DECDPUN; /* [units -> digits] */ michael@0: if (res->digits<0) { /* borrowed... */ michael@0: res->digits=-res->digits; michael@0: res->bits^=DECNEG; /* flip the sign */ michael@0: } michael@0: #if DECTRACE michael@0: decDumpAr('+', acc, D2U(res->digits)); michael@0: #endif michael@0: michael@0: /* If a buffer was used the result must be copied back, possibly */ michael@0: /* shortening. (If no buffer was used then the result must have */ michael@0: /* fit, so can't need rounding and residue must be 0.) */ michael@0: residue=0; /* clear accumulator */ michael@0: if (acc!=res->lsu) { michael@0: #if DECSUBSET michael@0: if (set->extended) { /* round from first significant digit */ michael@0: #endif michael@0: /* remove leading zeros that were added due to rounding up to */ michael@0: /* integral Units -- before the test for rounding. */ michael@0: if (res->digits>reqdigits) michael@0: res->digits=decGetDigits(acc, D2U(res->digits)); michael@0: decSetCoeff(res, set, acc, res->digits, &residue, status); michael@0: #if DECSUBSET michael@0: } michael@0: else { /* subset arithmetic rounds from original significant digit */ michael@0: /* May have an underestimate. This only occurs when both */ michael@0: /* numbers fit in DECDPUN digits and are padding with a */ michael@0: /* negative multiple (-10, -100...) and the top digit(s) become */ michael@0: /* 0. (This only matters when using X3.274 rules where the */ michael@0: /* leading zero could be included in the rounding.) */ michael@0: if (res->digitsdigits))=0; /* ensure leading 0 is there */ michael@0: res->digits=maxdigits; michael@0: } michael@0: else { michael@0: /* remove leading zeros that added due to rounding up to */ michael@0: /* integral Units (but only those in excess of the original */ michael@0: /* maxdigits length, unless extended) before test for rounding. */ michael@0: if (res->digits>reqdigits) { michael@0: res->digits=decGetDigits(acc, D2U(res->digits)); michael@0: if (res->digitsdigits=maxdigits; michael@0: } michael@0: } michael@0: decSetCoeff(res, set, acc, res->digits, &residue, status); michael@0: /* Now apply rounding if needed before removing leading zeros. */ michael@0: /* This is safe because subnormals are not a possibility */ michael@0: if (residue!=0) { michael@0: decApplyRound(res, set, residue, status); michael@0: residue=0; /* did what needed to be done */ michael@0: } michael@0: } /* subset */ michael@0: #endif michael@0: } /* used buffer */ michael@0: michael@0: /* strip leading zeros [these were left on in case of subset subtract] */ michael@0: res->digits=decGetDigits(res->lsu, D2U(res->digits)); michael@0: michael@0: /* apply checks and rounding */ michael@0: decFinish(res, set, &residue, status); michael@0: michael@0: /* "When the sum of two operands with opposite signs is exactly */ michael@0: /* zero, the sign of that sum shall be '+' in all rounding modes */ michael@0: /* except round toward -Infinity, in which mode that sign shall be */ michael@0: /* '-'." [Subset zeros also never have '-', set by decFinish.] */ michael@0: if (ISZERO(res) && diffsign michael@0: #if DECSUBSET michael@0: && set->extended michael@0: #endif michael@0: && (*status&DEC_Inexact)==0) { michael@0: if (set->round==DEC_ROUND_FLOOR) res->bits|=DECNEG; /* sign - */ michael@0: else res->bits&=~DECNEG; /* sign + */ michael@0: } michael@0: } while(0); /* end protected */ michael@0: michael@0: if (allocacc!=NULL) free(allocacc); /* drop any storage used */ michael@0: #if DECSUBSET michael@0: if (allocrhs!=NULL) free(allocrhs); /* .. */ michael@0: if (alloclhs!=NULL) free(alloclhs); /* .. */ michael@0: #endif michael@0: return res; michael@0: } /* decAddOp */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decDivideOp -- division operation */ michael@0: /* */ michael@0: /* This routine performs the calculations for all four division */ michael@0: /* operators (divide, divideInteger, remainder, remainderNear). */ michael@0: /* */ michael@0: /* C=A op B */ michael@0: /* */ michael@0: /* res is C, the result. C may be A and/or B (e.g., X=X/X) */ michael@0: /* lhs is A */ michael@0: /* rhs is B */ michael@0: /* set is the context */ michael@0: /* op is DIVIDE, DIVIDEINT, REMAINDER, or REMNEAR respectively. */ michael@0: /* status is the usual accumulator */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* */ michael@0: /* ------------------------------------------------------------------ */ michael@0: /* The underlying algorithm of this routine is the same as in the */ michael@0: /* 1981 S/370 implementation, that is, non-restoring long division */ michael@0: /* with bi-unit (rather than bi-digit) estimation for each unit */ michael@0: /* multiplier. In this pseudocode overview, complications for the */ michael@0: /* Remainder operators and division residues for exact rounding are */ michael@0: /* omitted for clarity. */ michael@0: /* */ michael@0: /* Prepare operands and handle special values */ michael@0: /* Test for x/0 and then 0/x */ michael@0: /* Exp =Exp1 - Exp2 */ michael@0: /* Exp =Exp +len(var1) -len(var2) */ michael@0: /* Sign=Sign1 * Sign2 */ michael@0: /* Pad accumulator (Var1) to double-length with 0's (pad1) */ michael@0: /* Pad Var2 to same length as Var1 */ michael@0: /* msu2pair/plus=1st 2 or 1 units of var2, +1 to allow for round */ michael@0: /* have=0 */ michael@0: /* Do until (have=digits+1 OR residue=0) */ michael@0: /* if exp<0 then if integer divide/residue then leave */ michael@0: /* this_unit=0 */ michael@0: /* Do forever */ michael@0: /* compare numbers */ michael@0: /* if <0 then leave inner_loop */ michael@0: /* if =0 then (* quick exit without subtract *) do */ michael@0: /* this_unit=this_unit+1; output this_unit */ michael@0: /* leave outer_loop; end */ michael@0: /* Compare lengths of numbers (mantissae): */ michael@0: /* If same then tops2=msu2pair -- {units 1&2 of var2} */ michael@0: /* else tops2=msu2plus -- {0, unit 1 of var2} */ michael@0: /* tops1=first_unit_of_Var1*10**DECDPUN +second_unit_of_var1 */ michael@0: /* mult=tops1/tops2 -- Good and safe guess at divisor */ michael@0: /* if mult=0 then mult=1 */ michael@0: /* this_unit=this_unit+mult */ michael@0: /* subtract */ michael@0: /* end inner_loop */ michael@0: /* if have\=0 | this_unit\=0 then do */ michael@0: /* output this_unit */ michael@0: /* have=have+1; end */ michael@0: /* var2=var2/10 */ michael@0: /* exp=exp-1 */ michael@0: /* end outer_loop */ michael@0: /* exp=exp+1 -- set the proper exponent */ michael@0: /* if have=0 then generate answer=0 */ michael@0: /* Return (Result is defined by Var1) */ michael@0: /* */ michael@0: /* ------------------------------------------------------------------ */ michael@0: /* Two working buffers are needed during the division; one (digits+ */ michael@0: /* 1) to accumulate the result, and the other (up to 2*digits+1) for */ michael@0: /* long subtractions. These are acc and var1 respectively. */ michael@0: /* var1 is a copy of the lhs coefficient, var2 is the rhs coefficient.*/ michael@0: /* The static buffers may be larger than might be expected to allow */ michael@0: /* for calls from higher-level funtions (notable exp). */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static decNumber * decDivideOp(decNumber *res, michael@0: const decNumber *lhs, const decNumber *rhs, michael@0: decContext *set, Flag op, uInt *status) { michael@0: #if DECSUBSET michael@0: decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */ michael@0: decNumber *allocrhs=NULL; /* .., rhs */ michael@0: #endif michael@0: Unit accbuff[SD2U(DECBUFFER+DECDPUN+10)]; /* local buffer */ michael@0: Unit *acc=accbuff; /* -> accumulator array for result */ michael@0: Unit *allocacc=NULL; /* -> allocated buffer, iff allocated */ michael@0: Unit *accnext; /* -> where next digit will go */ michael@0: Int acclength; /* length of acc needed [Units] */ michael@0: Int accunits; /* count of units accumulated */ michael@0: Int accdigits; /* count of digits accumulated */ michael@0: michael@0: Unit varbuff[SD2U(DECBUFFER*2+DECDPUN)]; /* buffer for var1 */ michael@0: Unit *var1=varbuff; /* -> var1 array for long subtraction */ michael@0: Unit *varalloc=NULL; /* -> allocated buffer, iff used */ michael@0: Unit *msu1; /* -> msu of var1 */ michael@0: michael@0: const Unit *var2; /* -> var2 array */ michael@0: const Unit *msu2; /* -> msu of var2 */ michael@0: Int msu2plus; /* msu2 plus one [does not vary] */ michael@0: eInt msu2pair; /* msu2 pair plus one [does not vary] */ michael@0: michael@0: Int var1units, var2units; /* actual lengths */ michael@0: Int var2ulen; /* logical length (units) */ michael@0: Int var1initpad=0; /* var1 initial padding (digits) */ michael@0: Int maxdigits; /* longest LHS or required acc length */ michael@0: Int mult; /* multiplier for subtraction */ michael@0: Unit thisunit; /* current unit being accumulated */ michael@0: Int residue; /* for rounding */ michael@0: Int reqdigits=set->digits; /* requested DIGITS */ michael@0: Int exponent; /* working exponent */ michael@0: Int maxexponent=0; /* DIVIDE maximum exponent if unrounded */ michael@0: uByte bits; /* working sign */ michael@0: Unit *target; /* work */ michael@0: const Unit *source; /* .. */ michael@0: uInt const *pow; /* .. */ michael@0: Int shift, cut; /* .. */ michael@0: #if DECSUBSET michael@0: Int dropped; /* work */ michael@0: #endif michael@0: michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, lhs, rhs, set)) return res; michael@0: #endif michael@0: michael@0: do { /* protect allocated storage */ michael@0: #if DECSUBSET michael@0: if (!set->extended) { michael@0: /* reduce operands and set lostDigits status, as needed */ michael@0: if (lhs->digits>reqdigits) { michael@0: alloclhs=decRoundOperand(lhs, set, status); michael@0: if (alloclhs==NULL) break; michael@0: lhs=alloclhs; michael@0: } michael@0: if (rhs->digits>reqdigits) { michael@0: allocrhs=decRoundOperand(rhs, set, status); michael@0: if (allocrhs==NULL) break; michael@0: rhs=allocrhs; michael@0: } michael@0: } michael@0: #endif michael@0: /* [following code does not require input rounding] */ michael@0: michael@0: bits=(lhs->bits^rhs->bits)&DECNEG; /* assumed sign for divisions */ michael@0: michael@0: /* handle infinities and NaNs */ michael@0: if (SPECIALARGS) { /* a special bit set */ michael@0: if (SPECIALARGS & (DECSNAN | DECNAN)) { /* one or two NaNs */ michael@0: decNaNs(res, lhs, rhs, set, status); michael@0: break; michael@0: } michael@0: /* one or two infinities */ michael@0: if (decNumberIsInfinite(lhs)) { /* LHS (dividend) is infinite */ michael@0: if (decNumberIsInfinite(rhs) || /* two infinities are invalid .. */ michael@0: op & (REMAINDER | REMNEAR)) { /* as is remainder of infinity */ michael@0: *status|=DEC_Invalid_operation; michael@0: break; michael@0: } michael@0: /* [Note that infinity/0 raises no exceptions] */ michael@0: uprv_decNumberZero(res); michael@0: res->bits=bits|DECINF; /* set +/- infinity */ michael@0: break; michael@0: } michael@0: else { /* RHS (divisor) is infinite */ michael@0: residue=0; michael@0: if (op&(REMAINDER|REMNEAR)) { michael@0: /* result is [finished clone of] lhs */ michael@0: decCopyFit(res, lhs, set, &residue, status); michael@0: } michael@0: else { /* a division */ michael@0: uprv_decNumberZero(res); michael@0: res->bits=bits; /* set +/- zero */ michael@0: /* for DIVIDEINT the exponent is always 0. For DIVIDE, result */ michael@0: /* is a 0 with infinitely negative exponent, clamped to minimum */ michael@0: if (op&DIVIDE) { michael@0: res->exponent=set->emin-set->digits+1; michael@0: *status|=DEC_Clamped; michael@0: } michael@0: } michael@0: decFinish(res, set, &residue, status); michael@0: break; michael@0: } michael@0: } michael@0: michael@0: /* handle 0 rhs (x/0) */ michael@0: if (ISZERO(rhs)) { /* x/0 is always exceptional */ michael@0: if (ISZERO(lhs)) { michael@0: uprv_decNumberZero(res); /* [after lhs test] */ michael@0: *status|=DEC_Division_undefined;/* 0/0 will become NaN */ michael@0: } michael@0: else { michael@0: uprv_decNumberZero(res); michael@0: if (op&(REMAINDER|REMNEAR)) *status|=DEC_Invalid_operation; michael@0: else { michael@0: *status|=DEC_Division_by_zero; /* x/0 */ michael@0: res->bits=bits|DECINF; /* .. is +/- Infinity */ michael@0: } michael@0: } michael@0: break;} michael@0: michael@0: /* handle 0 lhs (0/x) */ michael@0: if (ISZERO(lhs)) { /* 0/x [x!=0] */ michael@0: #if DECSUBSET michael@0: if (!set->extended) uprv_decNumberZero(res); michael@0: else { michael@0: #endif michael@0: if (op&DIVIDE) { michael@0: residue=0; michael@0: exponent=lhs->exponent-rhs->exponent; /* ideal exponent */ michael@0: uprv_decNumberCopy(res, lhs); /* [zeros always fit] */ michael@0: res->bits=bits; /* sign as computed */ michael@0: res->exponent=exponent; /* exponent, too */ michael@0: decFinalize(res, set, &residue, status); /* check exponent */ michael@0: } michael@0: else if (op&DIVIDEINT) { michael@0: uprv_decNumberZero(res); /* integer 0 */ michael@0: res->bits=bits; /* sign as computed */ michael@0: } michael@0: else { /* a remainder */ michael@0: exponent=rhs->exponent; /* [save in case overwrite] */ michael@0: uprv_decNumberCopy(res, lhs); /* [zeros always fit] */ michael@0: if (exponentexponent) res->exponent=exponent; /* use lower */ michael@0: } michael@0: #if DECSUBSET michael@0: } michael@0: #endif michael@0: break;} michael@0: michael@0: /* Precalculate exponent. This starts off adjusted (and hence fits */ michael@0: /* in 31 bits) and becomes the usual unadjusted exponent as the */ michael@0: /* division proceeds. The order of evaluation is important, here, */ michael@0: /* to avoid wrap. */ michael@0: exponent=(lhs->exponent+lhs->digits)-(rhs->exponent+rhs->digits); michael@0: michael@0: /* If the working exponent is -ve, then some quick exits are */ michael@0: /* possible because the quotient is known to be <1 */ michael@0: /* [for REMNEAR, it needs to be < -1, as -0.5 could need work] */ michael@0: if (exponent<0 && !(op==DIVIDE)) { michael@0: if (op&DIVIDEINT) { michael@0: uprv_decNumberZero(res); /* integer part is 0 */ michael@0: #if DECSUBSET michael@0: if (set->extended) michael@0: #endif michael@0: res->bits=bits; /* set +/- zero */ michael@0: break;} michael@0: /* fastpath remainders so long as the lhs has the smaller */ michael@0: /* (or equal) exponent */ michael@0: if (lhs->exponent<=rhs->exponent) { michael@0: if (op&REMAINDER || exponent<-1) { michael@0: /* It is REMAINDER or safe REMNEAR; result is [finished */ michael@0: /* clone of] lhs (r = x - 0*y) */ michael@0: residue=0; michael@0: decCopyFit(res, lhs, set, &residue, status); michael@0: decFinish(res, set, &residue, status); michael@0: break; michael@0: } michael@0: /* [unsafe REMNEAR drops through] */ michael@0: } michael@0: } /* fastpaths */ michael@0: michael@0: /* Long (slow) division is needed; roll up the sleeves... */ michael@0: michael@0: /* The accumulator will hold the quotient of the division. */ michael@0: /* If it needs to be too long for stack storage, then allocate. */ michael@0: acclength=D2U(reqdigits+DECDPUN); /* in Units */ michael@0: if (acclength*sizeof(Unit)>sizeof(accbuff)) { michael@0: /* printf("malloc dvacc %ld units\n", acclength); */ michael@0: allocacc=(Unit *)malloc(acclength*sizeof(Unit)); michael@0: if (allocacc==NULL) { /* hopeless -- abandon */ michael@0: *status|=DEC_Insufficient_storage; michael@0: break;} michael@0: acc=allocacc; /* use the allocated space */ michael@0: } michael@0: michael@0: /* var1 is the padded LHS ready for subtractions. */ michael@0: /* If it needs to be too long for stack storage, then allocate. */ michael@0: /* The maximum units needed for var1 (long subtraction) is: */ michael@0: /* Enough for */ michael@0: /* (rhs->digits+reqdigits-1) -- to allow full slide to right */ michael@0: /* or (lhs->digits) -- to allow for long lhs */ michael@0: /* whichever is larger */ michael@0: /* +1 -- for rounding of slide to right */ michael@0: /* +1 -- for leading 0s */ michael@0: /* +1 -- for pre-adjust if a remainder or DIVIDEINT */ michael@0: /* [Note: unused units do not participate in decUnitAddSub data] */ michael@0: maxdigits=rhs->digits+reqdigits-1; michael@0: if (lhs->digits>maxdigits) maxdigits=lhs->digits; michael@0: var1units=D2U(maxdigits)+2; michael@0: /* allocate a guard unit above msu1 for REMAINDERNEAR */ michael@0: if (!(op&DIVIDE)) var1units++; michael@0: if ((var1units+1)*sizeof(Unit)>sizeof(varbuff)) { michael@0: /* printf("malloc dvvar %ld units\n", var1units+1); */ michael@0: varalloc=(Unit *)malloc((var1units+1)*sizeof(Unit)); michael@0: if (varalloc==NULL) { /* hopeless -- abandon */ michael@0: *status|=DEC_Insufficient_storage; michael@0: break;} michael@0: var1=varalloc; /* use the allocated space */ michael@0: } michael@0: michael@0: /* Extend the lhs and rhs to full long subtraction length. The lhs */ michael@0: /* is truly extended into the var1 buffer, with 0 padding, so a */ michael@0: /* subtract in place is always possible. The rhs (var2) has */ michael@0: /* virtual padding (implemented by decUnitAddSub). */ michael@0: /* One guard unit was allocated above msu1 for rem=rem+rem in */ michael@0: /* REMAINDERNEAR. */ michael@0: msu1=var1+var1units-1; /* msu of var1 */ michael@0: source=lhs->lsu+D2U(lhs->digits)-1; /* msu of input array */ michael@0: for (target=msu1; source>=lhs->lsu; source--, target--) *target=*source; michael@0: for (; target>=var1; target--) *target=0; michael@0: michael@0: /* rhs (var2) is left-aligned with var1 at the start */ michael@0: var2ulen=var1units; /* rhs logical length (units) */ michael@0: var2units=D2U(rhs->digits); /* rhs actual length (units) */ michael@0: var2=rhs->lsu; /* -> rhs array */ michael@0: msu2=var2+var2units-1; /* -> msu of var2 [never changes] */ michael@0: /* now set up the variables which will be used for estimating the */ michael@0: /* multiplication factor. If these variables are not exact, add */ michael@0: /* 1 to make sure that the multiplier is never overestimated. */ michael@0: msu2plus=*msu2; /* it's value .. */ michael@0: if (var2units>1) msu2plus++; /* .. +1 if any more */ michael@0: msu2pair=(eInt)*msu2*(DECDPUNMAX+1);/* top two pair .. */ michael@0: if (var2units>1) { /* .. [else treat 2nd as 0] */ michael@0: msu2pair+=*(msu2-1); /* .. */ michael@0: if (var2units>2) msu2pair++; /* .. +1 if any more */ michael@0: } michael@0: michael@0: /* The calculation is working in units, which may have leading zeros, */ michael@0: /* but the exponent was calculated on the assumption that they are */ michael@0: /* both left-aligned. Adjust the exponent to compensate: add the */ michael@0: /* number of leading zeros in var1 msu and subtract those in var2 msu. */ michael@0: /* [This is actually done by counting the digits and negating, as */ michael@0: /* lead1=DECDPUN-digits1, and similarly for lead2.] */ michael@0: for (pow=&powers[1]; *msu1>=*pow; pow++) exponent--; michael@0: for (pow=&powers[1]; *msu2>=*pow; pow++) exponent++; michael@0: michael@0: /* Now, if doing an integer divide or remainder, ensure that */ michael@0: /* the result will be Unit-aligned. To do this, shift the var1 */ michael@0: /* accumulator towards least if need be. (It's much easier to */ michael@0: /* do this now than to reassemble the residue afterwards, if */ michael@0: /* doing a remainder.) Also ensure the exponent is not negative. */ michael@0: if (!(op&DIVIDE)) { michael@0: Unit *u; /* work */ michael@0: /* save the initial 'false' padding of var1, in digits */ michael@0: var1initpad=(var1units-D2U(lhs->digits))*DECDPUN; michael@0: /* Determine the shift to do. */ michael@0: if (exponent<0) cut=-exponent; michael@0: else cut=DECDPUN-exponent%DECDPUN; michael@0: decShiftToLeast(var1, var1units, cut); michael@0: exponent+=cut; /* maintain numerical value */ michael@0: var1initpad-=cut; /* .. and reduce padding */ michael@0: /* clean any most-significant units which were just emptied */ michael@0: for (u=msu1; cut>=DECDPUN; cut-=DECDPUN, u--) *u=0; michael@0: } /* align */ michael@0: else { /* is DIVIDE */ michael@0: maxexponent=lhs->exponent-rhs->exponent; /* save */ michael@0: /* optimization: if the first iteration will just produce 0, */ michael@0: /* preadjust to skip it [valid for DIVIDE only] */ michael@0: if (*msu1<*msu2) { michael@0: var2ulen--; /* shift down */ michael@0: exponent-=DECDPUN; /* update the exponent */ michael@0: } michael@0: } michael@0: michael@0: /* ---- start the long-division loops ------------------------------ */ michael@0: accunits=0; /* no units accumulated yet */ michael@0: accdigits=0; /* .. or digits */ michael@0: accnext=acc+acclength-1; /* -> msu of acc [NB: allows digits+1] */ michael@0: for (;;) { /* outer forever loop */ michael@0: thisunit=0; /* current unit assumed 0 */ michael@0: /* find the next unit */ michael@0: for (;;) { /* inner forever loop */ michael@0: /* strip leading zero units [from either pre-adjust or from */ michael@0: /* subtract last time around]. Leave at least one unit. */ michael@0: for (; *msu1==0 && msu1>var1; msu1--) var1units--; michael@0: michael@0: if (var1units msu */ michael@0: for (pv1=msu1; ; pv1--, pv2--) { michael@0: /* v1=*pv1 -- always OK */ michael@0: v2=0; /* assume in padding */ michael@0: if (pv2>=var2) v2=*pv2; /* in range */ michael@0: if (*pv1!=v2) break; /* no longer the same */ michael@0: if (pv1==var1) break; /* done; leave pv1 as is */ michael@0: } michael@0: /* here when all inspected or a difference seen */ michael@0: if (*pv1v2. Prepare for real subtraction; the lengths are equal */ michael@0: /* Estimate the multiplier (there's always a msu1-1)... */ michael@0: /* Bring in two units of var2 to provide a good estimate. */ michael@0: mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2pair); michael@0: } /* lengths the same */ michael@0: else { /* var1units > var2ulen, so subtraction is safe */ michael@0: /* The var2 msu is one unit towards the lsu of the var1 msu, */ michael@0: /* so only one unit for var2 can be used. */ michael@0: mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2plus); michael@0: } michael@0: if (mult==0) mult=1; /* must always be at least 1 */ michael@0: /* subtraction needed; var1 is > var2 */ michael@0: thisunit=(Unit)(thisunit+mult); /* accumulate */ michael@0: /* subtract var1-var2, into var1; only the overlap needs */ michael@0: /* processing, as this is an in-place calculation */ michael@0: shift=var2ulen-var2units; michael@0: #if DECTRACE michael@0: decDumpAr('1', &var1[shift], var1units-shift); michael@0: decDumpAr('2', var2, var2units); michael@0: printf("m=%ld\n", -mult); michael@0: #endif michael@0: decUnitAddSub(&var1[shift], var1units-shift, michael@0: var2, var2units, 0, michael@0: &var1[shift], -mult); michael@0: #if DECTRACE michael@0: decDumpAr('#', &var1[shift], var1units-shift); michael@0: #endif michael@0: /* var1 now probably has leading zeros; these are removed at the */ michael@0: /* top of the inner loop. */ michael@0: } /* inner loop */ michael@0: michael@0: /* The next unit has been calculated in full; unless it's a */ michael@0: /* leading zero, add to acc */ michael@0: if (accunits!=0 || thisunit!=0) { /* is first or non-zero */ michael@0: *accnext=thisunit; /* store in accumulator */ michael@0: /* account exactly for the new digits */ michael@0: if (accunits==0) { michael@0: accdigits++; /* at least one */ michael@0: for (pow=&powers[1]; thisunit>=*pow; pow++) accdigits++; michael@0: } michael@0: else accdigits+=DECDPUN; michael@0: accunits++; /* update count */ michael@0: accnext--; /* ready for next */ michael@0: if (accdigits>reqdigits) break; /* have enough digits */ michael@0: } michael@0: michael@0: /* if the residue is zero, the operation is done (unless divide */ michael@0: /* or divideInteger and still not enough digits yet) */ michael@0: if (*var1==0 && var1units==1) { /* residue is 0 */ michael@0: if (op&(REMAINDER|REMNEAR)) break; michael@0: if ((op&DIVIDE) && (exponent<=maxexponent)) break; michael@0: /* [drop through if divideInteger] */ michael@0: } michael@0: /* also done enough if calculating remainder or integer */ michael@0: /* divide and just did the last ('units') unit */ michael@0: if (exponent==0 && !(op&DIVIDE)) break; michael@0: michael@0: /* to get here, var1 is less than var2, so divide var2 by the per- */ michael@0: /* Unit power of ten and go for the next digit */ michael@0: var2ulen--; /* shift down */ michael@0: exponent-=DECDPUN; /* update the exponent */ michael@0: } /* outer loop */ michael@0: michael@0: /* ---- division is complete --------------------------------------- */ michael@0: /* here: acc has at least reqdigits+1 of good results (or fewer */ michael@0: /* if early stop), starting at accnext+1 (its lsu) */ michael@0: /* var1 has any residue at the stopping point */ michael@0: /* accunits is the number of digits collected in acc */ michael@0: if (accunits==0) { /* acc is 0 */ michael@0: accunits=1; /* show have a unit .. */ michael@0: accdigits=1; /* .. */ michael@0: *accnext=0; /* .. whose value is 0 */ michael@0: } michael@0: else accnext++; /* back to last placed */ michael@0: /* accnext now -> lowest unit of result */ michael@0: michael@0: residue=0; /* assume no residue */ michael@0: if (op&DIVIDE) { michael@0: /* record the presence of any residue, for rounding */ michael@0: if (*var1!=0 || var1units>1) residue=1; michael@0: else { /* no residue */ michael@0: /* Had an exact division; clean up spurious trailing 0s. */ michael@0: /* There will be at most DECDPUN-1, from the final multiply, */ michael@0: /* and then only if the result is non-0 (and even) and the */ michael@0: /* exponent is 'loose'. */ michael@0: #if DECDPUN>1 michael@0: Unit lsu=*accnext; michael@0: if (!(lsu&0x01) && (lsu!=0)) { michael@0: /* count the trailing zeros */ michael@0: Int drop=0; michael@0: for (;; drop++) { /* [will terminate because lsu!=0] */ michael@0: if (exponent>=maxexponent) break; /* don't chop real 0s */ michael@0: #if DECDPUN<=4 michael@0: if ((lsu-QUOT10(lsu, drop+1) michael@0: *powers[drop+1])!=0) break; /* found non-0 digit */ michael@0: #else michael@0: if (lsu%powers[drop+1]!=0) break; /* found non-0 digit */ michael@0: #endif michael@0: exponent++; michael@0: } michael@0: if (drop>0) { michael@0: accunits=decShiftToLeast(accnext, accunits, drop); michael@0: accdigits=decGetDigits(accnext, accunits); michael@0: accunits=D2U(accdigits); michael@0: /* [exponent was adjusted in the loop] */ michael@0: } michael@0: } /* neither odd nor 0 */ michael@0: #endif michael@0: } /* exact divide */ michael@0: } /* divide */ michael@0: else /* op!=DIVIDE */ { michael@0: /* check for coefficient overflow */ michael@0: if (accdigits+exponent>reqdigits) { michael@0: *status|=DEC_Division_impossible; michael@0: break; michael@0: } michael@0: if (op & (REMAINDER|REMNEAR)) { michael@0: /* [Here, the exponent will be 0, because var1 was adjusted */ michael@0: /* appropriately.] */ michael@0: Int postshift; /* work */ michael@0: Flag wasodd=0; /* integer was odd */ michael@0: Unit *quotlsu; /* for save */ michael@0: Int quotdigits; /* .. */ michael@0: michael@0: bits=lhs->bits; /* remainder sign is always as lhs */ michael@0: michael@0: /* Fastpath when residue is truly 0 is worthwhile [and */ michael@0: /* simplifies the code below] */ michael@0: if (*var1==0 && var1units==1) { /* residue is 0 */ michael@0: Int exp=lhs->exponent; /* save min(exponents) */ michael@0: if (rhs->exponentexponent; michael@0: uprv_decNumberZero(res); /* 0 coefficient */ michael@0: #if DECSUBSET michael@0: if (set->extended) michael@0: #endif michael@0: res->exponent=exp; /* .. with proper exponent */ michael@0: res->bits=(uByte)(bits&DECNEG); /* [cleaned] */ michael@0: decFinish(res, set, &residue, status); /* might clamp */ michael@0: break; michael@0: } michael@0: /* note if the quotient was odd */ michael@0: if (*accnext & 0x01) wasodd=1; /* acc is odd */ michael@0: quotlsu=accnext; /* save in case need to reinspect */ michael@0: quotdigits=accdigits; /* .. */ michael@0: michael@0: /* treat the residue, in var1, as the value to return, via acc */ michael@0: /* calculate the unused zero digits. This is the smaller of: */ michael@0: /* var1 initial padding (saved above) */ michael@0: /* var2 residual padding, which happens to be given by: */ michael@0: postshift=var1initpad+exponent-lhs->exponent+rhs->exponent; michael@0: /* [the 'exponent' term accounts for the shifts during divide] */ michael@0: if (var1initpadexponent; /* exponent is smaller of lhs & rhs */ michael@0: if (rhs->exponentexponent; michael@0: michael@0: /* Now correct the result if doing remainderNear; if it */ michael@0: /* (looking just at coefficients) is > rhs/2, or == rhs/2 and */ michael@0: /* the integer was odd then the result should be rem-rhs. */ michael@0: if (op&REMNEAR) { michael@0: Int compare, tarunits; /* work */ michael@0: Unit *up; /* .. */ michael@0: /* calculate remainder*2 into the var1 buffer (which has */ michael@0: /* 'headroom' of an extra unit and hence enough space) */ michael@0: /* [a dedicated 'double' loop would be faster, here] */ michael@0: tarunits=decUnitAddSub(accnext, accunits, accnext, accunits, michael@0: 0, accnext, 1); michael@0: /* decDumpAr('r', accnext, tarunits); */ michael@0: michael@0: /* Here, accnext (var1) holds tarunits Units with twice the */ michael@0: /* remainder's coefficient, which must now be compared to the */ michael@0: /* RHS. The remainder's exponent may be smaller than the RHS's. */ michael@0: compare=decUnitCompare(accnext, tarunits, rhs->lsu, D2U(rhs->digits), michael@0: rhs->exponent-exponent); michael@0: if (compare==BADINT) { /* deep trouble */ michael@0: *status|=DEC_Insufficient_storage; michael@0: break;} michael@0: michael@0: /* now restore the remainder by dividing by two; the lsu */ michael@0: /* is known to be even. */ michael@0: for (up=accnext; up0 || (compare==0 && wasodd)) { /* adjustment needed */ michael@0: Int exp, expunits, exprem; /* work */ michael@0: /* This is effectively causing round-up of the quotient, */ michael@0: /* so if it was the rare case where it was full and all */ michael@0: /* nines, it would overflow and hence division-impossible */ michael@0: /* should be raised */ michael@0: Flag allnines=0; /* 1 if quotient all nines */ michael@0: if (quotdigits==reqdigits) { /* could be borderline */ michael@0: for (up=quotlsu; ; up++) { michael@0: if (quotdigits>DECDPUN) { michael@0: if (*up!=DECDPUNMAX) break;/* non-nines */ michael@0: } michael@0: else { /* this is the last Unit */ michael@0: if (*up==powers[quotdigits]-1) allnines=1; michael@0: break; michael@0: } michael@0: quotdigits-=DECDPUN; /* checked those digits */ michael@0: } /* up */ michael@0: } /* borderline check */ michael@0: if (allnines) { michael@0: *status|=DEC_Division_impossible; michael@0: break;} michael@0: michael@0: /* rem-rhs is needed; the sign will invert. Again, var1 */ michael@0: /* can safely be used for the working Units array. */ michael@0: exp=rhs->exponent-exponent; /* RHS padding needed */ michael@0: /* Calculate units and remainder from exponent. */ michael@0: expunits=exp/DECDPUN; michael@0: exprem=exp%DECDPUN; michael@0: /* subtract [A+B*(-m)]; the result will always be negative */ michael@0: accunits=-decUnitAddSub(accnext, accunits, michael@0: rhs->lsu, D2U(rhs->digits), michael@0: expunits, accnext, -(Int)powers[exprem]); michael@0: accdigits=decGetDigits(accnext, accunits); /* count digits exactly */ michael@0: accunits=D2U(accdigits); /* and recalculate the units for copy */ michael@0: /* [exponent is as for original remainder] */ michael@0: bits^=DECNEG; /* flip the sign */ michael@0: } michael@0: } /* REMNEAR */ michael@0: } /* REMAINDER or REMNEAR */ michael@0: } /* not DIVIDE */ michael@0: michael@0: /* Set exponent and bits */ michael@0: res->exponent=exponent; michael@0: res->bits=(uByte)(bits&DECNEG); /* [cleaned] */ michael@0: michael@0: /* Now the coefficient. */ michael@0: decSetCoeff(res, set, accnext, accdigits, &residue, status); michael@0: michael@0: decFinish(res, set, &residue, status); /* final cleanup */ michael@0: michael@0: #if DECSUBSET michael@0: /* If a divide then strip trailing zeros if subset [after round] */ michael@0: if (!set->extended && (op==DIVIDE)) decTrim(res, set, 0, 1, &dropped); michael@0: #endif michael@0: } while(0); /* end protected */ michael@0: michael@0: if (varalloc!=NULL) free(varalloc); /* drop any storage used */ michael@0: if (allocacc!=NULL) free(allocacc); /* .. */ michael@0: #if DECSUBSET michael@0: if (allocrhs!=NULL) free(allocrhs); /* .. */ michael@0: if (alloclhs!=NULL) free(alloclhs); /* .. */ michael@0: #endif michael@0: return res; michael@0: } /* decDivideOp */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decMultiplyOp -- multiplication operation */ michael@0: /* */ michael@0: /* This routine performs the multiplication C=A x B. */ michael@0: /* */ michael@0: /* res is C, the result. C may be A and/or B (e.g., X=X*X) */ michael@0: /* lhs is A */ michael@0: /* rhs is B */ michael@0: /* set is the context */ michael@0: /* status is the usual accumulator */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* */ michael@0: /* ------------------------------------------------------------------ */ michael@0: /* 'Classic' multiplication is used rather than Karatsuba, as the */ michael@0: /* latter would give only a minor improvement for the short numbers */ michael@0: /* expected to be handled most (and uses much more memory). */ michael@0: /* */ michael@0: /* There are two major paths here: the general-purpose ('old code') */ michael@0: /* path which handles all DECDPUN values, and a fastpath version */ michael@0: /* which is used if 64-bit ints are available, DECDPUN<=4, and more */ michael@0: /* than two calls to decUnitAddSub would be made. */ michael@0: /* */ michael@0: /* The fastpath version lumps units together into 8-digit or 9-digit */ michael@0: /* chunks, and also uses a lazy carry strategy to minimise expensive */ michael@0: /* 64-bit divisions. The chunks are then broken apart again into */ michael@0: /* units for continuing processing. Despite this overhead, the */ michael@0: /* fastpath can speed up some 16-digit operations by 10x (and much */ michael@0: /* more for higher-precision calculations). */ michael@0: /* */ michael@0: /* A buffer always has to be used for the accumulator; in the */ michael@0: /* fastpath, buffers are also always needed for the chunked copies of */ michael@0: /* of the operand coefficients. */ michael@0: /* Static buffers are larger than needed just for multiply, to allow */ michael@0: /* for calls from other operations (notably exp). */ michael@0: /* ------------------------------------------------------------------ */ michael@0: #define FASTMUL (DECUSE64 && DECDPUN<5) michael@0: static decNumber * decMultiplyOp(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set, michael@0: uInt *status) { michael@0: Int accunits; /* Units of accumulator in use */ michael@0: Int exponent; /* work */ michael@0: Int residue=0; /* rounding residue */ michael@0: uByte bits; /* result sign */ michael@0: Unit *acc; /* -> accumulator Unit array */ michael@0: Int needbytes; /* size calculator */ michael@0: void *allocacc=NULL; /* -> allocated accumulator, iff allocated */ michael@0: Unit accbuff[SD2U(DECBUFFER*4+1)]; /* buffer (+1 for DECBUFFER==0, */ michael@0: /* *4 for calls from other operations) */ michael@0: const Unit *mer, *mermsup; /* work */ michael@0: Int madlength; /* Units in multiplicand */ michael@0: Int shift; /* Units to shift multiplicand by */ michael@0: michael@0: #if FASTMUL michael@0: /* if DECDPUN is 1 or 3 work in base 10**9, otherwise */ michael@0: /* (DECDPUN is 2 or 4) then work in base 10**8 */ michael@0: #if DECDPUN & 1 /* odd */ michael@0: #define FASTBASE 1000000000 /* base */ michael@0: #define FASTDIGS 9 /* digits in base */ michael@0: #define FASTLAZY 18 /* carry resolution point [1->18] */ michael@0: #else michael@0: #define FASTBASE 100000000 michael@0: #define FASTDIGS 8 michael@0: #define FASTLAZY 1844 /* carry resolution point [1->1844] */ michael@0: #endif michael@0: /* three buffers are used, two for chunked copies of the operands */ michael@0: /* (base 10**8 or base 10**9) and one base 2**64 accumulator with */ michael@0: /* lazy carry evaluation */ michael@0: uInt zlhibuff[(DECBUFFER*2+1)/8+1]; /* buffer (+1 for DECBUFFER==0) */ michael@0: uInt *zlhi=zlhibuff; /* -> lhs array */ michael@0: uInt *alloclhi=NULL; /* -> allocated buffer, iff allocated */ michael@0: uInt zrhibuff[(DECBUFFER*2+1)/8+1]; /* buffer (+1 for DECBUFFER==0) */ michael@0: uInt *zrhi=zrhibuff; /* -> rhs array */ michael@0: uInt *allocrhi=NULL; /* -> allocated buffer, iff allocated */ michael@0: uLong zaccbuff[(DECBUFFER*2+1)/4+2]; /* buffer (+1 for DECBUFFER==0) */ michael@0: /* [allocacc is shared for both paths, as only one will run] */ michael@0: uLong *zacc=zaccbuff; /* -> accumulator array for exact result */ michael@0: #if DECDPUN==1 michael@0: Int zoff; /* accumulator offset */ michael@0: #endif michael@0: uInt *lip, *rip; /* item pointers */ michael@0: uInt *lmsi, *rmsi; /* most significant items */ michael@0: Int ilhs, irhs, iacc; /* item counts in the arrays */ michael@0: Int lazy; /* lazy carry counter */ michael@0: uLong lcarry; /* uLong carry */ michael@0: uInt carry; /* carry (NB not uLong) */ michael@0: Int count; /* work */ michael@0: const Unit *cup; /* .. */ michael@0: Unit *up; /* .. */ michael@0: uLong *lp; /* .. */ michael@0: Int p; /* .. */ michael@0: #endif michael@0: michael@0: #if DECSUBSET michael@0: decNumber *alloclhs=NULL; /* -> allocated buffer, iff allocated */ michael@0: decNumber *allocrhs=NULL; /* -> allocated buffer, iff allocated */ michael@0: #endif michael@0: michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, lhs, rhs, set)) return res; michael@0: #endif michael@0: michael@0: /* precalculate result sign */ michael@0: bits=(uByte)((lhs->bits^rhs->bits)&DECNEG); michael@0: michael@0: /* handle infinities and NaNs */ michael@0: if (SPECIALARGS) { /* a special bit set */ michael@0: if (SPECIALARGS & (DECSNAN | DECNAN)) { /* one or two NaNs */ michael@0: decNaNs(res, lhs, rhs, set, status); michael@0: return res;} michael@0: /* one or two infinities; Infinity * 0 is invalid */ michael@0: if (((lhs->bits & DECINF)==0 && ISZERO(lhs)) michael@0: ||((rhs->bits & DECINF)==0 && ISZERO(rhs))) { michael@0: *status|=DEC_Invalid_operation; michael@0: return res;} michael@0: uprv_decNumberZero(res); michael@0: res->bits=bits|DECINF; /* infinity */ michael@0: return res;} michael@0: michael@0: /* For best speed, as in DMSRCN [the original Rexx numerics */ michael@0: /* module], use the shorter number as the multiplier (rhs) and */ michael@0: /* the longer as the multiplicand (lhs) to minimise the number of */ michael@0: /* adds (partial products) */ michael@0: if (lhs->digitsdigits) { /* swap... */ michael@0: const decNumber *hold=lhs; michael@0: lhs=rhs; michael@0: rhs=hold; michael@0: } michael@0: michael@0: do { /* protect allocated storage */ michael@0: #if DECSUBSET michael@0: if (!set->extended) { michael@0: /* reduce operands and set lostDigits status, as needed */ michael@0: if (lhs->digits>set->digits) { michael@0: alloclhs=decRoundOperand(lhs, set, status); michael@0: if (alloclhs==NULL) break; michael@0: lhs=alloclhs; michael@0: } michael@0: if (rhs->digits>set->digits) { michael@0: allocrhs=decRoundOperand(rhs, set, status); michael@0: if (allocrhs==NULL) break; michael@0: rhs=allocrhs; michael@0: } michael@0: } michael@0: #endif michael@0: /* [following code does not require input rounding] */ michael@0: michael@0: #if FASTMUL /* fastpath can be used */ michael@0: /* use the fast path if there are enough digits in the shorter */ michael@0: /* operand to make the setup and takedown worthwhile */ michael@0: #define NEEDTWO (DECDPUN*2) /* within two decUnitAddSub calls */ michael@0: if (rhs->digits>NEEDTWO) { /* use fastpath... */ michael@0: /* calculate the number of elements in each array */ michael@0: ilhs=(lhs->digits+FASTDIGS-1)/FASTDIGS; /* [ceiling] */ michael@0: irhs=(rhs->digits+FASTDIGS-1)/FASTDIGS; /* .. */ michael@0: iacc=ilhs+irhs; michael@0: michael@0: /* allocate buffers if required, as usual */ michael@0: needbytes=ilhs*sizeof(uInt); michael@0: if (needbytes>(Int)sizeof(zlhibuff)) { michael@0: alloclhi=(uInt *)malloc(needbytes); michael@0: zlhi=alloclhi;} michael@0: needbytes=irhs*sizeof(uInt); michael@0: if (needbytes>(Int)sizeof(zrhibuff)) { michael@0: allocrhi=(uInt *)malloc(needbytes); michael@0: zrhi=allocrhi;} michael@0: michael@0: /* Allocating the accumulator space needs a special case when */ michael@0: /* DECDPUN=1 because when converting the accumulator to Units */ michael@0: /* after the multiplication each 8-byte item becomes 9 1-byte */ michael@0: /* units. Therefore iacc extra bytes are needed at the front */ michael@0: /* (rounded up to a multiple of 8 bytes), and the uLong */ michael@0: /* accumulator starts offset the appropriate number of units */ michael@0: /* to the right to avoid overwrite during the unchunking. */ michael@0: michael@0: /* Make sure no signed int overflow below. This is always true */ michael@0: /* if the given numbers have less digits than DEC_MAX_DIGITS. */ michael@0: U_ASSERT(iacc <= INT32_MAX/sizeof(uLong)); michael@0: needbytes=iacc*sizeof(uLong); michael@0: #if DECDPUN==1 michael@0: zoff=(iacc+7)/8; /* items to offset by */ michael@0: needbytes+=zoff*8; michael@0: #endif michael@0: if (needbytes>(Int)sizeof(zaccbuff)) { michael@0: allocacc=(uLong *)malloc(needbytes); michael@0: zacc=(uLong *)allocacc;} michael@0: if (zlhi==NULL||zrhi==NULL||zacc==NULL) { michael@0: *status|=DEC_Insufficient_storage; michael@0: break;} michael@0: michael@0: acc=(Unit *)zacc; /* -> target Unit array */ michael@0: #if DECDPUN==1 michael@0: zacc+=zoff; /* start uLong accumulator to right */ michael@0: #endif michael@0: michael@0: /* assemble the chunked copies of the left and right sides */ michael@0: for (count=lhs->digits, cup=lhs->lsu, lip=zlhi; count>0; lip++) michael@0: for (p=0, *lip=0; p0; michael@0: p+=DECDPUN, cup++, count-=DECDPUN) michael@0: *lip+=*cup*powers[p]; michael@0: lmsi=lip-1; /* save -> msi */ michael@0: for (count=rhs->digits, cup=rhs->lsu, rip=zrhi; count>0; rip++) michael@0: for (p=0, *rip=0; p0; michael@0: p+=DECDPUN, cup++, count-=DECDPUN) michael@0: *rip+=*cup*powers[p]; michael@0: rmsi=rip-1; /* save -> msi */ michael@0: michael@0: /* zero the accumulator */ michael@0: for (lp=zacc; lp0 && rip!=rmsi) continue; michael@0: lazy=FASTLAZY; /* reset delay count */ michael@0: /* spin up the accumulator resolving overflows */ michael@0: for (lp=zacc; lp assume buffer for accumulator */ michael@0: needbytes=(D2U(lhs->digits)+D2U(rhs->digits))*sizeof(Unit); michael@0: if (needbytes>(Int)sizeof(accbuff)) { michael@0: allocacc=(Unit *)malloc(needbytes); michael@0: if (allocacc==NULL) {*status|=DEC_Insufficient_storage; break;} michael@0: acc=(Unit *)allocacc; /* use the allocated space */ michael@0: } michael@0: michael@0: /* Now the main long multiplication loop */ michael@0: /* Unlike the equivalent in the IBM Java implementation, there */ michael@0: /* is no advantage in calculating from msu to lsu. So, do it */ michael@0: /* by the book, as it were. */ michael@0: /* Each iteration calculates ACC=ACC+MULTAND*MULT */ michael@0: accunits=1; /* accumulator starts at '0' */ michael@0: *acc=0; /* .. (lsu=0) */ michael@0: shift=0; /* no multiplicand shift at first */ michael@0: madlength=D2U(lhs->digits); /* this won't change */ michael@0: mermsup=rhs->lsu+D2U(rhs->digits); /* -> msu+1 of multiplier */ michael@0: michael@0: for (mer=rhs->lsu; merlsu, madlength, 0, michael@0: &acc[shift], *mer) michael@0: + shift; michael@0: else { /* extend acc with a 0; it will be used shortly */ michael@0: *(acc+accunits)=0; /* [this avoids length of <=0 later] */ michael@0: accunits++; michael@0: } michael@0: /* multiply multiplicand by 10**DECDPUN for next Unit to left */ michael@0: shift++; /* add this for 'logical length' */ michael@0: } /* n */ michael@0: #if FASTMUL michael@0: } /* unchunked units */ michael@0: #endif michael@0: /* common end-path */ michael@0: #if DECTRACE michael@0: decDumpAr('*', acc, accunits); /* Show exact result */ michael@0: #endif michael@0: michael@0: /* acc now contains the exact result of the multiplication, */ michael@0: /* possibly with a leading zero unit; build the decNumber from */ michael@0: /* it, noting if any residue */ michael@0: res->bits=bits; /* set sign */ michael@0: res->digits=decGetDigits(acc, accunits); /* count digits exactly */ michael@0: michael@0: /* There can be a 31-bit wrap in calculating the exponent. */ michael@0: /* This can only happen if both input exponents are negative and */ michael@0: /* both their magnitudes are large. If there was a wrap, set a */ michael@0: /* safe very negative exponent, from which decFinalize() will */ michael@0: /* raise a hard underflow shortly. */ michael@0: exponent=lhs->exponent+rhs->exponent; /* calculate exponent */ michael@0: if (lhs->exponent<0 && rhs->exponent<0 && exponent>0) michael@0: exponent=-2*DECNUMMAXE; /* force underflow */ michael@0: res->exponent=exponent; /* OK to overwrite now */ michael@0: michael@0: michael@0: /* Set the coefficient. If any rounding, residue records */ michael@0: decSetCoeff(res, set, acc, res->digits, &residue, status); michael@0: decFinish(res, set, &residue, status); /* final cleanup */ michael@0: } while(0); /* end protected */ michael@0: michael@0: if (allocacc!=NULL) free(allocacc); /* drop any storage used */ michael@0: #if DECSUBSET michael@0: if (allocrhs!=NULL) free(allocrhs); /* .. */ michael@0: if (alloclhs!=NULL) free(alloclhs); /* .. */ michael@0: #endif michael@0: #if FASTMUL michael@0: if (allocrhi!=NULL) free(allocrhi); /* .. */ michael@0: if (alloclhi!=NULL) free(alloclhi); /* .. */ michael@0: #endif michael@0: return res; michael@0: } /* decMultiplyOp */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decExpOp -- effect exponentiation */ michael@0: /* */ michael@0: /* This computes C = exp(A) */ michael@0: /* */ michael@0: /* res is C, the result. C may be A */ michael@0: /* rhs is A */ michael@0: /* set is the context; note that rounding mode has no effect */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. status is updated but */ michael@0: /* not set. */ michael@0: /* */ michael@0: /* Restrictions: */ michael@0: /* */ michael@0: /* digits, emax, and -emin in the context must be less than */ michael@0: /* 2*DEC_MAX_MATH (1999998), and the rhs must be within these */ michael@0: /* bounds or a zero. This is an internal routine, so these */ michael@0: /* restrictions are contractual and not enforced. */ michael@0: /* */ michael@0: /* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will */ michael@0: /* almost always be correctly rounded, but may be up to 1 ulp in */ michael@0: /* error in rare cases. */ michael@0: /* */ michael@0: /* Finite results will always be full precision and Inexact, except */ michael@0: /* when A is a zero or -Infinity (giving 1 or 0 respectively). */ michael@0: /* ------------------------------------------------------------------ */ michael@0: /* This approach used here is similar to the algorithm described in */ michael@0: /* */ michael@0: /* Variable Precision Exponential Function, T. E. Hull and */ michael@0: /* A. Abrham, ACM Transactions on Mathematical Software, Vol 12 #2, */ michael@0: /* pp79-91, ACM, June 1986. */ michael@0: /* */ michael@0: /* with the main difference being that the iterations in the series */ michael@0: /* evaluation are terminated dynamically (which does not require the */ michael@0: /* extra variable-precision variables which are expensive in this */ michael@0: /* context). */ michael@0: /* */ michael@0: /* The error analysis in Hull & Abrham's paper applies except for the */ michael@0: /* round-off error accumulation during the series evaluation. This */ michael@0: /* code does not precalculate the number of iterations and so cannot */ michael@0: /* use Horner's scheme. Instead, the accumulation is done at double- */ michael@0: /* precision, which ensures that the additions of the terms are exact */ michael@0: /* and do not accumulate round-off (and any round-off errors in the */ michael@0: /* terms themselves move 'to the right' faster than they can */ michael@0: /* accumulate). This code also extends the calculation by allowing, */ michael@0: /* in the spirit of other decNumber operators, the input to be more */ michael@0: /* precise than the result (the precision used is based on the more */ michael@0: /* precise of the input or requested result). */ michael@0: /* */ michael@0: /* Implementation notes: */ michael@0: /* */ michael@0: /* 1. This is separated out as decExpOp so it can be called from */ michael@0: /* other Mathematical functions (notably Ln) with a wider range */ michael@0: /* than normal. In particular, it can handle the slightly wider */ michael@0: /* (double) range needed by Ln (which has to be able to calculate */ michael@0: /* exp(-x) where x can be the tiniest number (Ntiny). */ michael@0: /* */ michael@0: /* 2. Normalizing x to be <=0.1 (instead of <=1) reduces loop */ michael@0: /* iterations by appoximately a third with additional (although */ michael@0: /* diminishing) returns as the range is reduced to even smaller */ michael@0: /* fractions. However, h (the power of 10 used to correct the */ michael@0: /* result at the end, see below) must be kept <=8 as otherwise */ michael@0: /* the final result cannot be computed. Hence the leverage is a */ michael@0: /* sliding value (8-h), where potentially the range is reduced */ michael@0: /* more for smaller values. */ michael@0: /* */ michael@0: /* The leverage that can be applied in this way is severely */ michael@0: /* limited by the cost of the raise-to-the power at the end, */ michael@0: /* which dominates when the number of iterations is small (less */ michael@0: /* than ten) or when rhs is short. As an example, the adjustment */ michael@0: /* x**10,000,000 needs 31 multiplications, all but one full-width. */ michael@0: /* */ michael@0: /* 3. The restrictions (especially precision) could be raised with */ michael@0: /* care, but the full decNumber range seems very hard within the */ michael@0: /* 32-bit limits. */ michael@0: /* */ michael@0: /* 4. The working precisions for the static buffers are twice the */ michael@0: /* obvious size to allow for calls from decNumberPower. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: decNumber * decExpOp(decNumber *res, const decNumber *rhs, michael@0: decContext *set, uInt *status) { michael@0: uInt ignore=0; /* working status */ michael@0: Int h; /* adjusted exponent for 0.xxxx */ michael@0: Int p; /* working precision */ michael@0: Int residue; /* rounding residue */ michael@0: uInt needbytes; /* for space calculations */ michael@0: const decNumber *x=rhs; /* (may point to safe copy later) */ michael@0: decContext aset, tset, dset; /* working contexts */ michael@0: Int comp; /* work */ michael@0: michael@0: /* the argument is often copied to normalize it, so (unusually) it */ michael@0: /* is treated like other buffers, using DECBUFFER, +1 in case */ michael@0: /* DECBUFFER is 0 */ michael@0: decNumber bufr[D2N(DECBUFFER*2+1)]; michael@0: decNumber *allocrhs=NULL; /* non-NULL if rhs buffer allocated */ michael@0: michael@0: /* the working precision will be no more than set->digits+8+1 */ michael@0: /* so for on-stack buffers DECBUFFER+9 is used, +1 in case DECBUFFER */ michael@0: /* is 0 (and twice that for the accumulator) */ michael@0: michael@0: /* buffer for t, term (working precision plus) */ michael@0: decNumber buft[D2N(DECBUFFER*2+9+1)]; michael@0: decNumber *allocbuft=NULL; /* -> allocated buft, iff allocated */ michael@0: decNumber *t=buft; /* term */ michael@0: /* buffer for a, accumulator (working precision * 2), at least 9 */ michael@0: decNumber bufa[D2N(DECBUFFER*4+18+1)]; michael@0: decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */ michael@0: decNumber *a=bufa; /* accumulator */ michael@0: /* decNumber for the divisor term; this needs at most 9 digits */ michael@0: /* and so can be fixed size [16 so can use standard context] */ michael@0: decNumber bufd[D2N(16)]; michael@0: decNumber *d=bufd; /* divisor */ michael@0: decNumber numone; /* constant 1 */ michael@0: michael@0: #if DECCHECK michael@0: Int iterations=0; /* for later sanity check */ michael@0: if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; michael@0: #endif michael@0: michael@0: do { /* protect allocated storage */ michael@0: if (SPECIALARG) { /* handle infinities and NaNs */ michael@0: if (decNumberIsInfinite(rhs)) { /* an infinity */ michael@0: if (decNumberIsNegative(rhs)) /* -Infinity -> +0 */ michael@0: uprv_decNumberZero(res); michael@0: else uprv_decNumberCopy(res, rhs); /* +Infinity -> self */ michael@0: } michael@0: else decNaNs(res, rhs, NULL, set, status); /* a NaN */ michael@0: break;} michael@0: michael@0: if (ISZERO(rhs)) { /* zeros -> exact 1 */ michael@0: uprv_decNumberZero(res); /* make clean 1 */ michael@0: *res->lsu=1; /* .. */ michael@0: break;} /* [no status to set] */ michael@0: michael@0: /* e**x when 0 < x < 0.66 is < 1+3x/2, hence can fast-path */ michael@0: /* positive and negative tiny cases which will result in inexact */ michael@0: /* 1. This also allows the later add-accumulate to always be */ michael@0: /* exact (because its length will never be more than twice the */ michael@0: /* working precision). */ michael@0: /* The comparator (tiny) needs just one digit, so use the */ michael@0: /* decNumber d for it (reused as the divisor, etc., below); its */ michael@0: /* exponent is such that if x is positive it will have */ michael@0: /* set->digits-1 zeros between the decimal point and the digit, */ michael@0: /* which is 4, and if x is negative one more zero there as the */ michael@0: /* more precise result will be of the form 0.9999999 rather than */ michael@0: /* 1.0000001. Hence, tiny will be 0.0000004 if digits=7 and x>0 */ michael@0: /* or 0.00000004 if digits=7 and x<0. If RHS not larger than */ michael@0: /* this then the result will be 1.000000 */ michael@0: uprv_decNumberZero(d); /* clean */ michael@0: *d->lsu=4; /* set 4 .. */ michael@0: d->exponent=-set->digits; /* * 10**(-d) */ michael@0: if (decNumberIsNegative(rhs)) d->exponent--; /* negative case */ michael@0: comp=decCompare(d, rhs, 1); /* signless compare */ michael@0: if (comp==BADINT) { michael@0: *status|=DEC_Insufficient_storage; michael@0: break;} michael@0: if (comp>=0) { /* rhs < d */ michael@0: Int shift=set->digits-1; michael@0: uprv_decNumberZero(res); /* set 1 */ michael@0: *res->lsu=1; /* .. */ michael@0: res->digits=decShiftToMost(res->lsu, 1, shift); michael@0: res->exponent=-shift; /* make 1.0000... */ michael@0: *status|=DEC_Inexact | DEC_Rounded; /* .. inexactly */ michael@0: break;} /* tiny */ michael@0: michael@0: /* set up the context to be used for calculating a, as this is */ michael@0: /* used on both paths below */ michael@0: uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64); michael@0: /* accumulator bounds are as requested (could underflow) */ michael@0: aset.emax=set->emax; /* usual bounds */ michael@0: aset.emin=set->emin; /* .. */ michael@0: aset.clamp=0; /* and no concrete format */ michael@0: michael@0: /* calculate the adjusted (Hull & Abrham) exponent (where the */ michael@0: /* decimal point is just to the left of the coefficient msd) */ michael@0: h=rhs->exponent+rhs->digits; michael@0: /* if h>8 then 10**h cannot be calculated safely; however, when */ michael@0: /* h=8 then exp(|rhs|) will be at least exp(1E+7) which is at */ michael@0: /* least 6.59E+4342944, so (due to the restriction on Emax/Emin) */ michael@0: /* overflow (or underflow to 0) is guaranteed -- so this case can */ michael@0: /* be handled by simply forcing the appropriate excess */ michael@0: if (h>8) { /* overflow/underflow */ michael@0: /* set up here so Power call below will over or underflow to */ michael@0: /* zero; set accumulator to either 2 or 0.02 */ michael@0: /* [stack buffer for a is always big enough for this] */ michael@0: uprv_decNumberZero(a); michael@0: *a->lsu=2; /* not 1 but < exp(1) */ michael@0: if (decNumberIsNegative(rhs)) a->exponent=-2; /* make 0.02 */ michael@0: h=8; /* clamp so 10**h computable */ michael@0: p=9; /* set a working precision */ michael@0: } michael@0: else { /* h<=8 */ michael@0: Int maxlever=(rhs->digits>8?1:0); michael@0: /* [could/should increase this for precisions >40 or so, too] */ michael@0: michael@0: /* if h is 8, cannot normalize to a lower upper limit because */ michael@0: /* the final result will not be computable (see notes above), */ michael@0: /* but leverage can be applied whenever h is less than 8. */ michael@0: /* Apply as much as possible, up to a MAXLEVER digits, which */ michael@0: /* sets the tradeoff against the cost of the later a**(10**h). */ michael@0: /* As h is increased, the working precision below also */ michael@0: /* increases to compensate for the "constant digits at the */ michael@0: /* front" effect. */ michael@0: Int lever=MINI(8-h, maxlever); /* leverage attainable */ michael@0: Int use=-rhs->digits-lever; /* exponent to use for RHS */ michael@0: h+=lever; /* apply leverage selected */ michael@0: if (h<0) { /* clamp */ michael@0: use+=h; /* [may end up subnormal] */ michael@0: h=0; michael@0: } michael@0: /* Take a copy of RHS if it needs normalization (true whenever x>=1) */ michael@0: if (rhs->exponent!=use) { michael@0: decNumber *newrhs=bufr; /* assume will fit on stack */ michael@0: needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit); michael@0: if (needbytes>sizeof(bufr)) { /* need malloc space */ michael@0: allocrhs=(decNumber *)malloc(needbytes); michael@0: if (allocrhs==NULL) { /* hopeless -- abandon */ michael@0: *status|=DEC_Insufficient_storage; michael@0: break;} michael@0: newrhs=allocrhs; /* use the allocated space */ michael@0: } michael@0: uprv_decNumberCopy(newrhs, rhs); /* copy to safe space */ michael@0: newrhs->exponent=use; /* normalize; now <1 */ michael@0: x=newrhs; /* ready for use */ michael@0: /* decNumberShow(x); */ michael@0: } michael@0: michael@0: /* Now use the usual power series to evaluate exp(x). The */ michael@0: /* series starts as 1 + x + x^2/2 ... so prime ready for the */ michael@0: /* third term by setting the term variable t=x, the accumulator */ michael@0: /* a=1, and the divisor d=2. */ michael@0: michael@0: /* First determine the working precision. From Hull & Abrham */ michael@0: /* this is set->digits+h+2. However, if x is 'over-precise' we */ michael@0: /* need to allow for all its digits to potentially participate */ michael@0: /* (consider an x where all the excess digits are 9s) so in */ michael@0: /* this case use x->digits+h+2 */ michael@0: p=MAXI(x->digits, set->digits)+h+2; /* [h<=8] */ michael@0: michael@0: /* a and t are variable precision, and depend on p, so space */ michael@0: /* must be allocated for them if necessary */ michael@0: michael@0: /* the accumulator needs to be able to hold 2p digits so that */ michael@0: /* the additions on the second and subsequent iterations are */ michael@0: /* sufficiently exact. */ michael@0: needbytes=sizeof(decNumber)+(D2U(p*2)-1)*sizeof(Unit); michael@0: if (needbytes>sizeof(bufa)) { /* need malloc space */ michael@0: allocbufa=(decNumber *)malloc(needbytes); michael@0: if (allocbufa==NULL) { /* hopeless -- abandon */ michael@0: *status|=DEC_Insufficient_storage; michael@0: break;} michael@0: a=allocbufa; /* use the allocated space */ michael@0: } michael@0: /* the term needs to be able to hold p digits (which is */ michael@0: /* guaranteed to be larger than x->digits, so the initial copy */ michael@0: /* is safe); it may also be used for the raise-to-power */ michael@0: /* calculation below, which needs an extra two digits */ michael@0: needbytes=sizeof(decNumber)+(D2U(p+2)-1)*sizeof(Unit); michael@0: if (needbytes>sizeof(buft)) { /* need malloc space */ michael@0: allocbuft=(decNumber *)malloc(needbytes); michael@0: if (allocbuft==NULL) { /* hopeless -- abandon */ michael@0: *status|=DEC_Insufficient_storage; michael@0: break;} michael@0: t=allocbuft; /* use the allocated space */ michael@0: } michael@0: michael@0: uprv_decNumberCopy(t, x); /* term=x */ michael@0: uprv_decNumberZero(a); *a->lsu=1; /* accumulator=1 */ michael@0: uprv_decNumberZero(d); *d->lsu=2; /* divisor=2 */ michael@0: uprv_decNumberZero(&numone); *numone.lsu=1; /* constant 1 for increment */ michael@0: michael@0: /* set up the contexts for calculating a, t, and d */ michael@0: uprv_decContextDefault(&tset, DEC_INIT_DECIMAL64); michael@0: dset=tset; michael@0: /* accumulator bounds are set above, set precision now */ michael@0: aset.digits=p*2; /* double */ michael@0: /* term bounds avoid any underflow or overflow */ michael@0: tset.digits=p; michael@0: tset.emin=DEC_MIN_EMIN; /* [emax is plenty] */ michael@0: /* [dset.digits=16, etc., are sufficient] */ michael@0: michael@0: /* finally ready to roll */ michael@0: for (;;) { michael@0: #if DECCHECK michael@0: iterations++; michael@0: #endif michael@0: /* only the status from the accumulation is interesting */ michael@0: /* [but it should remain unchanged after first add] */ michael@0: decAddOp(a, a, t, &aset, 0, status); /* a=a+t */ michael@0: decMultiplyOp(t, t, x, &tset, &ignore); /* t=t*x */ michael@0: decDivideOp(t, t, d, &tset, DIVIDE, &ignore); /* t=t/d */ michael@0: /* the iteration ends when the term cannot affect the result, */ michael@0: /* if rounded to p digits, which is when its value is smaller */ michael@0: /* than the accumulator by p+1 digits. There must also be */ michael@0: /* full precision in a. */ michael@0: if (((a->digits+a->exponent)>=(t->digits+t->exponent+p+1)) michael@0: && (a->digits>=p)) break; michael@0: decAddOp(d, d, &numone, &dset, 0, &ignore); /* d=d+1 */ michael@0: } /* iterate */ michael@0: michael@0: #if DECCHECK michael@0: /* just a sanity check; comment out test to show always */ michael@0: if (iterations>p+3) michael@0: printf("Exp iterations=%ld, status=%08lx, p=%ld, d=%ld\n", michael@0: (LI)iterations, (LI)*status, (LI)p, (LI)x->digits); michael@0: #endif michael@0: } /* h<=8 */ michael@0: michael@0: /* apply postconditioning: a=a**(10**h) -- this is calculated */ michael@0: /* at a slightly higher precision than Hull & Abrham suggest */ michael@0: if (h>0) { michael@0: Int seenbit=0; /* set once a 1-bit is seen */ michael@0: Int i; /* counter */ michael@0: Int n=powers[h]; /* always positive */ michael@0: aset.digits=p+2; /* sufficient precision */ michael@0: /* avoid the overhead and many extra digits of decNumberPower */ michael@0: /* as all that is needed is the short 'multipliers' loop; here */ michael@0: /* accumulate the answer into t */ michael@0: uprv_decNumberZero(t); *t->lsu=1; /* acc=1 */ michael@0: for (i=1;;i++){ /* for each bit [top bit ignored] */ michael@0: /* abandon if have had overflow or terminal underflow */ michael@0: if (*status & (DEC_Overflow|DEC_Underflow)) { /* interesting? */ michael@0: if (*status&DEC_Overflow || ISZERO(t)) break;} michael@0: n=n<<1; /* move next bit to testable position */ michael@0: if (n<0) { /* top bit is set */ michael@0: seenbit=1; /* OK, have a significant bit */ michael@0: decMultiplyOp(t, t, a, &aset, status); /* acc=acc*x */ michael@0: } michael@0: if (i==31) break; /* that was the last bit */ michael@0: if (!seenbit) continue; /* no need to square 1 */ michael@0: decMultiplyOp(t, t, t, &aset, status); /* acc=acc*acc [square] */ michael@0: } /*i*/ /* 32 bits */ michael@0: /* decNumberShow(t); */ michael@0: a=t; /* and carry on using t instead of a */ michael@0: } michael@0: michael@0: /* Copy and round the result to res */ michael@0: residue=1; /* indicate dirt to right .. */ michael@0: if (ISZERO(a)) residue=0; /* .. unless underflowed to 0 */ michael@0: aset.digits=set->digits; /* [use default rounding] */ michael@0: decCopyFit(res, a, &aset, &residue, status); /* copy & shorten */ michael@0: decFinish(res, set, &residue, status); /* cleanup/set flags */ michael@0: } while(0); /* end protected */ michael@0: michael@0: if (allocrhs !=NULL) free(allocrhs); /* drop any storage used */ michael@0: if (allocbufa!=NULL) free(allocbufa); /* .. */ michael@0: if (allocbuft!=NULL) free(allocbuft); /* .. */ michael@0: /* [status is handled by caller] */ michael@0: return res; michael@0: } /* decExpOp */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* Initial-estimate natural logarithm table */ michael@0: /* */ michael@0: /* LNnn -- 90-entry 16-bit table for values from .10 through .99. */ michael@0: /* The result is a 4-digit encode of the coefficient (c=the */ michael@0: /* top 14 bits encoding 0-9999) and a 2-digit encode of the */ michael@0: /* exponent (e=the bottom 2 bits encoding 0-3) */ michael@0: /* */ michael@0: /* The resulting value is given by: */ michael@0: /* */ michael@0: /* v = -c * 10**(-e-3) */ michael@0: /* */ michael@0: /* where e and c are extracted from entry k = LNnn[x-10] */ michael@0: /* where x is truncated (NB) into the range 10 through 99, */ michael@0: /* and then c = k>>2 and e = k&3. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static const uShort LNnn[90]={9016, 8652, 8316, 8008, 7724, 7456, 7208, michael@0: 6972, 6748, 6540, 6340, 6148, 5968, 5792, 5628, 5464, 5312, michael@0: 5164, 5020, 4884, 4748, 4620, 4496, 4376, 4256, 4144, 4032, michael@0: 39233, 38181, 37157, 36157, 35181, 34229, 33297, 32389, 31501, 30629, michael@0: 29777, 28945, 28129, 27329, 26545, 25777, 25021, 24281, 23553, 22837, michael@0: 22137, 21445, 20769, 20101, 19445, 18801, 18165, 17541, 16925, 16321, michael@0: 15721, 15133, 14553, 13985, 13421, 12865, 12317, 11777, 11241, 10717, michael@0: 10197, 9685, 9177, 8677, 8185, 7697, 7213, 6737, 6269, 5801, michael@0: 5341, 4889, 4437, 39930, 35534, 31186, 26886, 22630, 18418, 14254, michael@0: 10130, 6046, 20055}; michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decLnOp -- effect natural logarithm */ michael@0: /* */ michael@0: /* This computes C = ln(A) */ michael@0: /* */ michael@0: /* res is C, the result. C may be A */ michael@0: /* rhs is A */ michael@0: /* set is the context; note that rounding mode has no effect */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* */ michael@0: /* Notable cases: */ michael@0: /* A<0 -> Invalid */ michael@0: /* A=0 -> -Infinity (Exact) */ michael@0: /* A=+Infinity -> +Infinity (Exact) */ michael@0: /* A=1 exactly -> 0 (Exact) */ michael@0: /* */ michael@0: /* Restrictions (as for Exp): */ michael@0: /* */ michael@0: /* digits, emax, and -emin in the context must be less than */ michael@0: /* DEC_MAX_MATH+11 (1000010), and the rhs must be within these */ michael@0: /* bounds or a zero. This is an internal routine, so these */ michael@0: /* restrictions are contractual and not enforced. */ michael@0: /* */ michael@0: /* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will */ michael@0: /* almost always be correctly rounded, but may be up to 1 ulp in */ michael@0: /* error in rare cases. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: /* The result is calculated using Newton's method, with each */ michael@0: /* iteration calculating a' = a + x * exp(-a) - 1. See, for example, */ michael@0: /* Epperson 1989. */ michael@0: /* */ michael@0: /* The iteration ends when the adjustment x*exp(-a)-1 is tiny enough. */ michael@0: /* This has to be calculated at the sum of the precision of x and the */ michael@0: /* working precision. */ michael@0: /* */ michael@0: /* Implementation notes: */ michael@0: /* */ michael@0: /* 1. This is separated out as decLnOp so it can be called from */ michael@0: /* other Mathematical functions (e.g., Log 10) with a wider range */ michael@0: /* than normal. In particular, it can handle the slightly wider */ michael@0: /* (+9+2) range needed by a power function. */ michael@0: /* */ michael@0: /* 2. The speed of this function is about 10x slower than exp, as */ michael@0: /* it typically needs 4-6 iterations for short numbers, and the */ michael@0: /* extra precision needed adds a squaring effect, twice. */ michael@0: /* */ michael@0: /* 3. Fastpaths are included for ln(10) and ln(2), up to length 40, */ michael@0: /* as these are common requests. ln(10) is used by log10(x). */ michael@0: /* */ michael@0: /* 4. An iteration might be saved by widening the LNnn table, and */ michael@0: /* would certainly save at least one if it were made ten times */ michael@0: /* bigger, too (for truncated fractions 0.100 through 0.999). */ michael@0: /* However, for most practical evaluations, at least four or five */ michael@0: /* iterations will be neede -- so this would only speed up by */ michael@0: /* 20-25% and that probably does not justify increasing the table */ michael@0: /* size. */ michael@0: /* */ michael@0: /* 5. The static buffers are larger than might be expected to allow */ michael@0: /* for calls from decNumberPower. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: #if defined(__clang__) || U_GCC_MAJOR_MINOR >= 406 michael@0: #pragma GCC diagnostic push michael@0: #pragma GCC diagnostic ignored "-Warray-bounds" michael@0: #endif michael@0: decNumber * decLnOp(decNumber *res, const decNumber *rhs, michael@0: decContext *set, uInt *status) { michael@0: uInt ignore=0; /* working status accumulator */ michael@0: uInt needbytes; /* for space calculations */ michael@0: Int residue; /* rounding residue */ michael@0: Int r; /* rhs=f*10**r [see below] */ michael@0: Int p; /* working precision */ michael@0: Int pp; /* precision for iteration */ michael@0: Int t; /* work */ michael@0: michael@0: /* buffers for a (accumulator, typically precision+2) and b */ michael@0: /* (adjustment calculator, same size) */ michael@0: decNumber bufa[D2N(DECBUFFER+12)]; michael@0: decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */ michael@0: decNumber *a=bufa; /* accumulator/work */ michael@0: decNumber bufb[D2N(DECBUFFER*2+2)]; michael@0: decNumber *allocbufb=NULL; /* -> allocated bufa, iff allocated */ michael@0: decNumber *b=bufb; /* adjustment/work */ michael@0: michael@0: decNumber numone; /* constant 1 */ michael@0: decNumber cmp; /* work */ michael@0: decContext aset, bset; /* working contexts */ michael@0: michael@0: #if DECCHECK michael@0: Int iterations=0; /* for later sanity check */ michael@0: if (decCheckOperands(res, DECUNUSED, rhs, set)) return res; michael@0: #endif michael@0: michael@0: do { /* protect allocated storage */ michael@0: if (SPECIALARG) { /* handle infinities and NaNs */ michael@0: if (decNumberIsInfinite(rhs)) { /* an infinity */ michael@0: if (decNumberIsNegative(rhs)) /* -Infinity -> error */ michael@0: *status|=DEC_Invalid_operation; michael@0: else uprv_decNumberCopy(res, rhs); /* +Infinity -> self */ michael@0: } michael@0: else decNaNs(res, rhs, NULL, set, status); /* a NaN */ michael@0: break;} michael@0: michael@0: if (ISZERO(rhs)) { /* +/- zeros -> -Infinity */ michael@0: uprv_decNumberZero(res); /* make clean */ michael@0: res->bits=DECINF|DECNEG; /* set - infinity */ michael@0: break;} /* [no status to set] */ michael@0: michael@0: /* Non-zero negatives are bad... */ michael@0: if (decNumberIsNegative(rhs)) { /* -x -> error */ michael@0: *status|=DEC_Invalid_operation; michael@0: break;} michael@0: michael@0: /* Here, rhs is positive, finite, and in range */ michael@0: michael@0: /* lookaside fastpath code for ln(2) and ln(10) at common lengths */ michael@0: if (rhs->exponent==0 && set->digits<=40) { michael@0: #if DECDPUN==1 michael@0: if (rhs->lsu[0]==0 && rhs->lsu[1]==1 && rhs->digits==2) { /* ln(10) */ michael@0: #else michael@0: if (rhs->lsu[0]==10 && rhs->digits==2) { /* ln(10) */ michael@0: #endif michael@0: aset=*set; aset.round=DEC_ROUND_HALF_EVEN; michael@0: #define LN10 "2.302585092994045684017991454684364207601" michael@0: uprv_decNumberFromString(res, LN10, &aset); michael@0: *status|=(DEC_Inexact | DEC_Rounded); /* is inexact */ michael@0: break;} michael@0: if (rhs->lsu[0]==2 && rhs->digits==1) { /* ln(2) */ michael@0: aset=*set; aset.round=DEC_ROUND_HALF_EVEN; michael@0: #define LN2 "0.6931471805599453094172321214581765680755" michael@0: uprv_decNumberFromString(res, LN2, &aset); michael@0: *status|=(DEC_Inexact | DEC_Rounded); michael@0: break;} michael@0: } /* integer and short */ michael@0: michael@0: /* Determine the working precision. This is normally the */ michael@0: /* requested precision + 2, with a minimum of 9. However, if */ michael@0: /* the rhs is 'over-precise' then allow for all its digits to */ michael@0: /* potentially participate (consider an rhs where all the excess */ michael@0: /* digits are 9s) so in this case use rhs->digits+2. */ michael@0: p=MAXI(rhs->digits, MAXI(set->digits, 7))+2; michael@0: michael@0: /* Allocate space for the accumulator and the high-precision */ michael@0: /* adjustment calculator, if necessary. The accumulator must */ michael@0: /* be able to hold p digits, and the adjustment up to */ michael@0: /* rhs->digits+p digits. They are also made big enough for 16 */ michael@0: /* digits so that they can be used for calculating the initial */ michael@0: /* estimate. */ michael@0: needbytes=sizeof(decNumber)+(D2U(MAXI(p,16))-1)*sizeof(Unit); michael@0: if (needbytes>sizeof(bufa)) { /* need malloc space */ michael@0: allocbufa=(decNumber *)malloc(needbytes); michael@0: if (allocbufa==NULL) { /* hopeless -- abandon */ michael@0: *status|=DEC_Insufficient_storage; michael@0: break;} michael@0: a=allocbufa; /* use the allocated space */ michael@0: } michael@0: pp=p+rhs->digits; michael@0: needbytes=sizeof(decNumber)+(D2U(MAXI(pp,16))-1)*sizeof(Unit); michael@0: if (needbytes>sizeof(bufb)) { /* need malloc space */ michael@0: allocbufb=(decNumber *)malloc(needbytes); michael@0: if (allocbufb==NULL) { /* hopeless -- abandon */ michael@0: *status|=DEC_Insufficient_storage; michael@0: break;} michael@0: b=allocbufb; /* use the allocated space */ michael@0: } michael@0: michael@0: /* Prepare an initial estimate in acc. Calculate this by */ michael@0: /* considering the coefficient of x to be a normalized fraction, */ michael@0: /* f, with the decimal point at far left and multiplied by */ michael@0: /* 10**r. Then, rhs=f*10**r and 0.1<=f<1, and */ michael@0: /* ln(x) = ln(f) + ln(10)*r */ michael@0: /* Get the initial estimate for ln(f) from a small lookup */ michael@0: /* table (see above) indexed by the first two digits of f, */ michael@0: /* truncated. */ michael@0: michael@0: uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64); /* 16-digit extended */ michael@0: r=rhs->exponent+rhs->digits; /* 'normalised' exponent */ michael@0: uprv_decNumberFromInt32(a, r); /* a=r */ michael@0: uprv_decNumberFromInt32(b, 2302585); /* b=ln(10) (2.302585) */ michael@0: b->exponent=-6; /* .. */ michael@0: decMultiplyOp(a, a, b, &aset, &ignore); /* a=a*b */ michael@0: /* now get top two digits of rhs into b by simple truncate and */ michael@0: /* force to integer */ michael@0: residue=0; /* (no residue) */ michael@0: aset.digits=2; aset.round=DEC_ROUND_DOWN; michael@0: decCopyFit(b, rhs, &aset, &residue, &ignore); /* copy & shorten */ michael@0: b->exponent=0; /* make integer */ michael@0: t=decGetInt(b); /* [cannot fail] */ michael@0: if (t<10) t=X10(t); /* adjust single-digit b */ michael@0: t=LNnn[t-10]; /* look up ln(b) */ michael@0: uprv_decNumberFromInt32(b, t>>2); /* b=ln(b) coefficient */ michael@0: b->exponent=-(t&3)-3; /* set exponent */ michael@0: b->bits=DECNEG; /* ln(0.10)->ln(0.99) always -ve */ michael@0: aset.digits=16; aset.round=DEC_ROUND_HALF_EVEN; /* restore */ michael@0: decAddOp(a, a, b, &aset, 0, &ignore); /* acc=a+b */ michael@0: /* the initial estimate is now in a, with up to 4 digits correct. */ michael@0: /* When rhs is at or near Nmax the estimate will be low, so we */ michael@0: /* will approach it from below, avoiding overflow when calling exp. */ michael@0: michael@0: uprv_decNumberZero(&numone); *numone.lsu=1; /* constant 1 for adjustment */ michael@0: michael@0: /* accumulator bounds are as requested (could underflow, but */ michael@0: /* cannot overflow) */ michael@0: aset.emax=set->emax; michael@0: aset.emin=set->emin; michael@0: aset.clamp=0; /* no concrete format */ michael@0: /* set up a context to be used for the multiply and subtract */ michael@0: bset=aset; michael@0: bset.emax=DEC_MAX_MATH*2; /* use double bounds for the */ michael@0: bset.emin=-DEC_MAX_MATH*2; /* adjustment calculation */ michael@0: /* [see decExpOp call below] */ michael@0: /* for each iteration double the number of digits to calculate, */ michael@0: /* up to a maximum of p */ michael@0: pp=9; /* initial precision */ michael@0: /* [initially 9 as then the sequence starts 7+2, 16+2, and */ michael@0: /* 34+2, which is ideal for standard-sized numbers] */ michael@0: aset.digits=pp; /* working context */ michael@0: bset.digits=pp+rhs->digits; /* wider context */ michael@0: for (;;) { /* iterate */ michael@0: #if DECCHECK michael@0: iterations++; michael@0: if (iterations>24) break; /* consider 9 * 2**24 */ michael@0: #endif michael@0: /* calculate the adjustment (exp(-a)*x-1) into b. This is a */ michael@0: /* catastrophic subtraction but it really is the difference */ michael@0: /* from 1 that is of interest. */ michael@0: /* Use the internal entry point to Exp as it allows the double */ michael@0: /* range for calculating exp(-a) when a is the tiniest subnormal. */ michael@0: a->bits^=DECNEG; /* make -a */ michael@0: decExpOp(b, a, &bset, &ignore); /* b=exp(-a) */ michael@0: a->bits^=DECNEG; /* restore sign of a */ michael@0: /* now multiply by rhs and subtract 1, at the wider precision */ michael@0: decMultiplyOp(b, b, rhs, &bset, &ignore); /* b=b*rhs */ michael@0: decAddOp(b, b, &numone, &bset, DECNEG, &ignore); /* b=b-1 */ michael@0: michael@0: /* the iteration ends when the adjustment cannot affect the */ michael@0: /* result by >=0.5 ulp (at the requested digits), which */ michael@0: /* is when its value is smaller than the accumulator by */ michael@0: /* set->digits+1 digits (or it is zero) -- this is a looser */ michael@0: /* requirement than for Exp because all that happens to the */ michael@0: /* accumulator after this is the final rounding (but note that */ michael@0: /* there must also be full precision in a, or a=0). */ michael@0: michael@0: if (decNumberIsZero(b) || michael@0: (a->digits+a->exponent)>=(b->digits+b->exponent+set->digits+1)) { michael@0: if (a->digits==p) break; michael@0: if (decNumberIsZero(a)) { michael@0: decCompareOp(&cmp, rhs, &numone, &aset, COMPARE, &ignore); /* rhs=1 ? */ michael@0: if (cmp.lsu[0]==0) a->exponent=0; /* yes, exact 0 */ michael@0: else *status|=(DEC_Inexact | DEC_Rounded); /* no, inexact */ michael@0: break; michael@0: } michael@0: /* force padding if adjustment has gone to 0 before full length */ michael@0: if (decNumberIsZero(b)) b->exponent=a->exponent-p; michael@0: } michael@0: michael@0: /* not done yet ... */ michael@0: decAddOp(a, a, b, &aset, 0, &ignore); /* a=a+b for next estimate */ michael@0: if (pp==p) continue; /* precision is at maximum */ michael@0: /* lengthen the next calculation */ michael@0: pp=pp*2; /* double precision */ michael@0: if (pp>p) pp=p; /* clamp to maximum */ michael@0: aset.digits=pp; /* working context */ michael@0: bset.digits=pp+rhs->digits; /* wider context */ michael@0: } /* Newton's iteration */ michael@0: michael@0: #if DECCHECK michael@0: /* just a sanity check; remove the test to show always */ michael@0: if (iterations>24) michael@0: printf("Ln iterations=%ld, status=%08lx, p=%ld, d=%ld\n", michael@0: (LI)iterations, (LI)*status, (LI)p, (LI)rhs->digits); michael@0: #endif michael@0: michael@0: /* Copy and round the result to res */ michael@0: residue=1; /* indicate dirt to right */ michael@0: if (ISZERO(a)) residue=0; /* .. unless underflowed to 0 */ michael@0: aset.digits=set->digits; /* [use default rounding] */ michael@0: decCopyFit(res, a, &aset, &residue, status); /* copy & shorten */ michael@0: decFinish(res, set, &residue, status); /* cleanup/set flags */ michael@0: } while(0); /* end protected */ michael@0: michael@0: if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */ michael@0: if (allocbufb!=NULL) free(allocbufb); /* .. */ michael@0: /* [status is handled by caller] */ michael@0: return res; michael@0: } /* decLnOp */ michael@0: #if defined(__clang__) || U_GCC_MAJOR_MINOR >= 406 michael@0: #pragma GCC diagnostic pop michael@0: #endif michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decQuantizeOp -- force exponent to requested value */ michael@0: /* */ michael@0: /* This computes C = op(A, B), where op adjusts the coefficient */ michael@0: /* of C (by rounding or shifting) such that the exponent (-scale) */ michael@0: /* of C has the value B or matches the exponent of B. */ michael@0: /* The numerical value of C will equal A, except for the effects of */ michael@0: /* any rounding that occurred. */ michael@0: /* */ michael@0: /* res is C, the result. C may be A or B */ michael@0: /* lhs is A, the number to adjust */ michael@0: /* rhs is B, the requested exponent */ michael@0: /* set is the context */ michael@0: /* quant is 1 for quantize or 0 for rescale */ michael@0: /* status is the status accumulator (this can be called without */ michael@0: /* risk of control loss) */ michael@0: /* */ michael@0: /* C must have space for set->digits digits. */ michael@0: /* */ michael@0: /* Unless there is an error or the result is infinite, the exponent */ michael@0: /* after the operation is guaranteed to be that requested. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static decNumber * decQuantizeOp(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set, michael@0: Flag quant, uInt *status) { michael@0: #if DECSUBSET michael@0: decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */ michael@0: decNumber *allocrhs=NULL; /* .., rhs */ michael@0: #endif michael@0: const decNumber *inrhs=rhs; /* save original rhs */ michael@0: Int reqdigits=set->digits; /* requested DIGITS */ michael@0: Int reqexp; /* requested exponent [-scale] */ michael@0: Int residue=0; /* rounding residue */ michael@0: Int etiny=set->emin-(reqdigits-1); michael@0: michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, lhs, rhs, set)) return res; michael@0: #endif michael@0: michael@0: do { /* protect allocated storage */ michael@0: #if DECSUBSET michael@0: if (!set->extended) { michael@0: /* reduce operands and set lostDigits status, as needed */ michael@0: if (lhs->digits>reqdigits) { michael@0: alloclhs=decRoundOperand(lhs, set, status); michael@0: if (alloclhs==NULL) break; michael@0: lhs=alloclhs; michael@0: } michael@0: if (rhs->digits>reqdigits) { /* [this only checks lostDigits] */ michael@0: allocrhs=decRoundOperand(rhs, set, status); michael@0: if (allocrhs==NULL) break; michael@0: rhs=allocrhs; michael@0: } michael@0: } michael@0: #endif michael@0: /* [following code does not require input rounding] */ michael@0: michael@0: /* Handle special values */ michael@0: if (SPECIALARGS) { michael@0: /* NaNs get usual processing */ michael@0: if (SPECIALARGS & (DECSNAN | DECNAN)) michael@0: decNaNs(res, lhs, rhs, set, status); michael@0: /* one infinity but not both is bad */ michael@0: else if ((lhs->bits ^ rhs->bits) & DECINF) michael@0: *status|=DEC_Invalid_operation; michael@0: /* both infinity: return lhs */ michael@0: else uprv_decNumberCopy(res, lhs); /* [nop if in place] */ michael@0: break; michael@0: } michael@0: michael@0: /* set requested exponent */ michael@0: if (quant) reqexp=inrhs->exponent; /* quantize -- match exponents */ michael@0: else { /* rescale -- use value of rhs */ michael@0: /* Original rhs must be an integer that fits and is in range, */ michael@0: /* which could be from -1999999997 to +999999999, thanks to */ michael@0: /* subnormals */ michael@0: reqexp=decGetInt(inrhs); /* [cannot fail] */ michael@0: } michael@0: michael@0: #if DECSUBSET michael@0: if (!set->extended) etiny=set->emin; /* no subnormals */ michael@0: #endif michael@0: michael@0: if (reqexp==BADINT /* bad (rescale only) or .. */ michael@0: || reqexp==BIGODD || reqexp==BIGEVEN /* very big (ditto) or .. */ michael@0: || (reqexpset->emax)) { /* > emax */ michael@0: *status|=DEC_Invalid_operation; michael@0: break;} michael@0: michael@0: /* the RHS has been processed, so it can be overwritten now if necessary */ michael@0: if (ISZERO(lhs)) { /* zero coefficient unchanged */ michael@0: uprv_decNumberCopy(res, lhs); /* [nop if in place] */ michael@0: res->exponent=reqexp; /* .. just set exponent */ michael@0: #if DECSUBSET michael@0: if (!set->extended) res->bits=0; /* subset specification; no -0 */ michael@0: #endif michael@0: } michael@0: else { /* non-zero lhs */ michael@0: Int adjust=reqexp-lhs->exponent; /* digit adjustment needed */ michael@0: /* if adjusted coefficient will definitely not fit, give up now */ michael@0: if ((lhs->digits-adjust)>reqdigits) { michael@0: *status|=DEC_Invalid_operation; michael@0: break; michael@0: } michael@0: michael@0: if (adjust>0) { /* increasing exponent */ michael@0: /* this will decrease the length of the coefficient by adjust */ michael@0: /* digits, and must round as it does so */ michael@0: decContext workset; /* work */ michael@0: workset=*set; /* clone rounding, etc. */ michael@0: workset.digits=lhs->digits-adjust; /* set requested length */ michael@0: /* [note that the latter can be <1, here] */ michael@0: decCopyFit(res, lhs, &workset, &residue, status); /* fit to result */ michael@0: decApplyRound(res, &workset, residue, status); /* .. and round */ michael@0: residue=0; /* [used] */ michael@0: /* If just rounded a 999s case, exponent will be off by one; */ michael@0: /* adjust back (after checking space), if so. */ michael@0: if (res->exponent>reqexp) { michael@0: /* re-check needed, e.g., for quantize(0.9999, 0.001) under */ michael@0: /* set->digits==3 */ michael@0: if (res->digits==reqdigits) { /* cannot shift by 1 */ michael@0: *status&=~(DEC_Inexact | DEC_Rounded); /* [clean these] */ michael@0: *status|=DEC_Invalid_operation; michael@0: break; michael@0: } michael@0: res->digits=decShiftToMost(res->lsu, res->digits, 1); /* shift */ michael@0: res->exponent--; /* (re)adjust the exponent. */ michael@0: } michael@0: #if DECSUBSET michael@0: if (ISZERO(res) && !set->extended) res->bits=0; /* subset; no -0 */ michael@0: #endif michael@0: } /* increase */ michael@0: else /* adjust<=0 */ { /* decreasing or = exponent */ michael@0: /* this will increase the length of the coefficient by -adjust */ michael@0: /* digits, by adding zero or more trailing zeros; this is */ michael@0: /* already checked for fit, above */ michael@0: uprv_decNumberCopy(res, lhs); /* [it will fit] */ michael@0: /* if padding needed (adjust<0), add it now... */ michael@0: if (adjust<0) { michael@0: res->digits=decShiftToMost(res->lsu, res->digits, -adjust); michael@0: res->exponent+=adjust; /* adjust the exponent */ michael@0: } michael@0: } /* decrease */ michael@0: } /* non-zero */ michael@0: michael@0: /* Check for overflow [do not use Finalize in this case, as an */ michael@0: /* overflow here is a "don't fit" situation] */ michael@0: if (res->exponent>set->emax-res->digits+1) { /* too big */ michael@0: *status|=DEC_Invalid_operation; michael@0: break; michael@0: } michael@0: else { michael@0: decFinalize(res, set, &residue, status); /* set subnormal flags */ michael@0: *status&=~DEC_Underflow; /* suppress Underflow [as per 754] */ michael@0: } michael@0: } while(0); /* end protected */ michael@0: michael@0: #if DECSUBSET michael@0: if (allocrhs!=NULL) free(allocrhs); /* drop any storage used */ michael@0: if (alloclhs!=NULL) free(alloclhs); /* .. */ michael@0: #endif michael@0: return res; michael@0: } /* decQuantizeOp */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decCompareOp -- compare, min, or max two Numbers */ michael@0: /* */ michael@0: /* This computes C = A ? B and carries out one of four operations: */ michael@0: /* COMPARE -- returns the signum (as a number) giving the */ michael@0: /* result of a comparison unless one or both */ michael@0: /* operands is a NaN (in which case a NaN results) */ michael@0: /* COMPSIG -- as COMPARE except that a quiet NaN raises */ michael@0: /* Invalid operation. */ michael@0: /* COMPMAX -- returns the larger of the operands, using the */ michael@0: /* 754 maxnum operation */ michael@0: /* COMPMAXMAG -- ditto, comparing absolute values */ michael@0: /* COMPMIN -- the 754 minnum operation */ michael@0: /* COMPMINMAG -- ditto, comparing absolute values */ michael@0: /* COMTOTAL -- returns the signum (as a number) giving the */ michael@0: /* result of a comparison using 754 total ordering */ michael@0: /* */ michael@0: /* res is C, the result. C may be A and/or B (e.g., X=X?X) */ michael@0: /* lhs is A */ michael@0: /* rhs is B */ michael@0: /* set is the context */ michael@0: /* op is the operation flag */ michael@0: /* status is the usual accumulator */ michael@0: /* */ michael@0: /* C must have space for one digit for COMPARE or set->digits for */ michael@0: /* COMPMAX, COMPMIN, COMPMAXMAG, or COMPMINMAG. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: /* The emphasis here is on speed for common cases, and avoiding */ michael@0: /* coefficient comparison if possible. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static decNumber * decCompareOp(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set, michael@0: Flag op, uInt *status) { michael@0: #if DECSUBSET michael@0: decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */ michael@0: decNumber *allocrhs=NULL; /* .., rhs */ michael@0: #endif michael@0: Int result=0; /* default result value */ michael@0: uByte merged; /* work */ michael@0: michael@0: #if DECCHECK michael@0: if (decCheckOperands(res, lhs, rhs, set)) return res; michael@0: #endif michael@0: michael@0: do { /* protect allocated storage */ michael@0: #if DECSUBSET michael@0: if (!set->extended) { michael@0: /* reduce operands and set lostDigits status, as needed */ michael@0: if (lhs->digits>set->digits) { michael@0: alloclhs=decRoundOperand(lhs, set, status); michael@0: if (alloclhs==NULL) {result=BADINT; break;} michael@0: lhs=alloclhs; michael@0: } michael@0: if (rhs->digits>set->digits) { michael@0: allocrhs=decRoundOperand(rhs, set, status); michael@0: if (allocrhs==NULL) {result=BADINT; break;} michael@0: rhs=allocrhs; michael@0: } michael@0: } michael@0: #endif michael@0: /* [following code does not require input rounding] */ michael@0: michael@0: /* If total ordering then handle differing signs 'up front' */ michael@0: if (op==COMPTOTAL) { /* total ordering */ michael@0: if (decNumberIsNegative(lhs) && !decNumberIsNegative(rhs)) { michael@0: result=-1; michael@0: break; michael@0: } michael@0: if (!decNumberIsNegative(lhs) && decNumberIsNegative(rhs)) { michael@0: result=+1; michael@0: break; michael@0: } michael@0: } michael@0: michael@0: /* handle NaNs specially; let infinities drop through */ michael@0: /* This assumes sNaN (even just one) leads to NaN. */ michael@0: merged=(lhs->bits | rhs->bits) & (DECSNAN | DECNAN); michael@0: if (merged) { /* a NaN bit set */ michael@0: if (op==COMPARE); /* result will be NaN */ michael@0: else if (op==COMPSIG) /* treat qNaN as sNaN */ michael@0: *status|=DEC_Invalid_operation | DEC_sNaN; michael@0: else if (op==COMPTOTAL) { /* total ordering, always finite */ michael@0: /* signs are known to be the same; compute the ordering here */ michael@0: /* as if the signs are both positive, then invert for negatives */ michael@0: if (!decNumberIsNaN(lhs)) result=-1; michael@0: else if (!decNumberIsNaN(rhs)) result=+1; michael@0: /* here if both NaNs */ michael@0: else if (decNumberIsSNaN(lhs) && decNumberIsQNaN(rhs)) result=-1; michael@0: else if (decNumberIsQNaN(lhs) && decNumberIsSNaN(rhs)) result=+1; michael@0: else { /* both NaN or both sNaN */ michael@0: /* now it just depends on the payload */ michael@0: result=decUnitCompare(lhs->lsu, D2U(lhs->digits), michael@0: rhs->lsu, D2U(rhs->digits), 0); michael@0: /* [Error not possible, as these are 'aligned'] */ michael@0: } /* both same NaNs */ michael@0: if (decNumberIsNegative(lhs)) result=-result; michael@0: break; michael@0: } /* total order */ michael@0: michael@0: else if (merged & DECSNAN); /* sNaN -> qNaN */ michael@0: else { /* here if MIN or MAX and one or two quiet NaNs */ michael@0: /* min or max -- 754 rules ignore single NaN */ michael@0: if (!decNumberIsNaN(lhs) || !decNumberIsNaN(rhs)) { michael@0: /* just one NaN; force choice to be the non-NaN operand */ michael@0: op=COMPMAX; michael@0: if (lhs->bits & DECNAN) result=-1; /* pick rhs */ michael@0: else result=+1; /* pick lhs */ michael@0: break; michael@0: } michael@0: } /* max or min */ michael@0: op=COMPNAN; /* use special path */ michael@0: decNaNs(res, lhs, rhs, set, status); /* propagate NaN */ michael@0: break; michael@0: } michael@0: /* have numbers */ michael@0: if (op==COMPMAXMAG || op==COMPMINMAG) result=decCompare(lhs, rhs, 1); michael@0: else result=decCompare(lhs, rhs, 0); /* sign matters */ michael@0: } while(0); /* end protected */ michael@0: michael@0: if (result==BADINT) *status|=DEC_Insufficient_storage; /* rare */ michael@0: else { michael@0: if (op==COMPARE || op==COMPSIG ||op==COMPTOTAL) { /* returning signum */ michael@0: if (op==COMPTOTAL && result==0) { michael@0: /* operands are numerically equal or same NaN (and same sign, */ michael@0: /* tested first); if identical, leave result 0 */ michael@0: if (lhs->exponent!=rhs->exponent) { michael@0: if (lhs->exponentexponent) result=-1; michael@0: else result=+1; michael@0: if (decNumberIsNegative(lhs)) result=-result; michael@0: } /* lexp!=rexp */ michael@0: } /* total-order by exponent */ michael@0: uprv_decNumberZero(res); /* [always a valid result] */ michael@0: if (result!=0) { /* must be -1 or +1 */ michael@0: *res->lsu=1; michael@0: if (result<0) res->bits=DECNEG; michael@0: } michael@0: } michael@0: else if (op==COMPNAN); /* special, drop through */ michael@0: else { /* MAX or MIN, non-NaN result */ michael@0: Int residue=0; /* rounding accumulator */ michael@0: /* choose the operand for the result */ michael@0: const decNumber *choice; michael@0: if (result==0) { /* operands are numerically equal */ michael@0: /* choose according to sign then exponent (see 754) */ michael@0: uByte slhs=(lhs->bits & DECNEG); michael@0: uByte srhs=(rhs->bits & DECNEG); michael@0: #if DECSUBSET michael@0: if (!set->extended) { /* subset: force left-hand */ michael@0: op=COMPMAX; michael@0: result=+1; michael@0: } michael@0: else michael@0: #endif michael@0: if (slhs!=srhs) { /* signs differ */ michael@0: if (slhs) result=-1; /* rhs is max */ michael@0: else result=+1; /* lhs is max */ michael@0: } michael@0: else if (slhs && srhs) { /* both negative */ michael@0: if (lhs->exponentexponent) result=+1; michael@0: else result=-1; michael@0: /* [if equal, use lhs, technically identical] */ michael@0: } michael@0: else { /* both positive */ michael@0: if (lhs->exponent>rhs->exponent) result=+1; michael@0: else result=-1; michael@0: /* [ditto] */ michael@0: } michael@0: } /* numerically equal */ michael@0: /* here result will be non-0; reverse if looking for MIN */ michael@0: if (op==COMPMIN || op==COMPMINMAG) result=-result; michael@0: choice=(result>0 ? lhs : rhs); /* choose */ michael@0: /* copy chosen to result, rounding if need be */ michael@0: decCopyFit(res, choice, set, &residue, status); michael@0: decFinish(res, set, &residue, status); michael@0: } michael@0: } michael@0: #if DECSUBSET michael@0: if (allocrhs!=NULL) free(allocrhs); /* free any storage used */ michael@0: if (alloclhs!=NULL) free(alloclhs); /* .. */ michael@0: #endif michael@0: return res; michael@0: } /* decCompareOp */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decCompare -- compare two decNumbers by numerical value */ michael@0: /* */ michael@0: /* This routine compares A ? B without altering them. */ michael@0: /* */ michael@0: /* Arg1 is A, a decNumber which is not a NaN */ michael@0: /* Arg2 is B, a decNumber which is not a NaN */ michael@0: /* Arg3 is 1 for a sign-independent compare, 0 otherwise */ michael@0: /* */ michael@0: /* returns -1, 0, or 1 for AB, or BADINT if failure */ michael@0: /* (the only possible failure is an allocation error) */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static Int decCompare(const decNumber *lhs, const decNumber *rhs, michael@0: Flag abs_c) { michael@0: Int result; /* result value */ michael@0: Int sigr; /* rhs signum */ michael@0: Int compare; /* work */ michael@0: michael@0: result=1; /* assume signum(lhs) */ michael@0: if (ISZERO(lhs)) result=0; michael@0: if (abs_c) { michael@0: if (ISZERO(rhs)) return result; /* LHS wins or both 0 */ michael@0: /* RHS is non-zero */ michael@0: if (result==0) return -1; /* LHS is 0; RHS wins */ michael@0: /* [here, both non-zero, result=1] */ michael@0: } michael@0: else { /* signs matter */ michael@0: if (result && decNumberIsNegative(lhs)) result=-1; michael@0: sigr=1; /* compute signum(rhs) */ michael@0: if (ISZERO(rhs)) sigr=0; michael@0: else if (decNumberIsNegative(rhs)) sigr=-1; michael@0: if (result > sigr) return +1; /* L > R, return 1 */ michael@0: if (result < sigr) return -1; /* L < R, return -1 */ michael@0: if (result==0) return 0; /* both 0 */ michael@0: } michael@0: michael@0: /* signums are the same; both are non-zero */ michael@0: if ((lhs->bits | rhs->bits) & DECINF) { /* one or more infinities */ michael@0: if (decNumberIsInfinite(rhs)) { michael@0: if (decNumberIsInfinite(lhs)) result=0;/* both infinite */ michael@0: else result=-result; /* only rhs infinite */ michael@0: } michael@0: return result; michael@0: } michael@0: /* must compare the coefficients, allowing for exponents */ michael@0: if (lhs->exponent>rhs->exponent) { /* LHS exponent larger */ michael@0: /* swap sides, and sign */ michael@0: const decNumber *temp=lhs; michael@0: lhs=rhs; michael@0: rhs=temp; michael@0: result=-result; michael@0: } michael@0: compare=decUnitCompare(lhs->lsu, D2U(lhs->digits), michael@0: rhs->lsu, D2U(rhs->digits), michael@0: rhs->exponent-lhs->exponent); michael@0: if (compare!=BADINT) compare*=result; /* comparison succeeded */ michael@0: return compare; michael@0: } /* decCompare */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decUnitCompare -- compare two >=0 integers in Unit arrays */ michael@0: /* */ michael@0: /* This routine compares A ? B*10**E where A and B are unit arrays */ michael@0: /* A is a plain integer */ michael@0: /* B has an exponent of E (which must be non-negative) */ michael@0: /* */ michael@0: /* Arg1 is A first Unit (lsu) */ michael@0: /* Arg2 is A length in Units */ michael@0: /* Arg3 is B first Unit (lsu) */ michael@0: /* Arg4 is B length in Units */ michael@0: /* Arg5 is E (0 if the units are aligned) */ michael@0: /* */ michael@0: /* returns -1, 0, or 1 for AB, or BADINT if failure */ michael@0: /* (the only possible failure is an allocation error, which can */ michael@0: /* only occur if E!=0) */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static Int decUnitCompare(const Unit *a, Int alength, michael@0: const Unit *b, Int blength, Int exp) { michael@0: Unit *acc; /* accumulator for result */ michael@0: Unit accbuff[SD2U(DECBUFFER*2+1)]; /* local buffer */ michael@0: Unit *allocacc=NULL; /* -> allocated acc buffer, iff allocated */ michael@0: Int accunits, need; /* units in use or needed for acc */ michael@0: const Unit *l, *r, *u; /* work */ michael@0: Int expunits, exprem, result; /* .. */ michael@0: michael@0: if (exp==0) { /* aligned; fastpath */ michael@0: if (alength>blength) return 1; michael@0: if (alength=a; l--, r--) { michael@0: if (*l>*r) return 1; michael@0: if (*l<*r) return -1; michael@0: } michael@0: return 0; /* all units match */ michael@0: } /* aligned */ michael@0: michael@0: /* Unaligned. If one is >1 unit longer than the other, padded */ michael@0: /* approximately, then can return easily */ michael@0: if (alength>blength+(Int)D2U(exp)) return 1; michael@0: if (alength+1sizeof(accbuff)) { michael@0: allocacc=(Unit *)malloc(need*sizeof(Unit)); michael@0: if (allocacc==NULL) return BADINT; /* hopeless -- abandon */ michael@0: acc=allocacc; michael@0: } michael@0: /* Calculate units and remainder from exponent. */ michael@0: expunits=exp/DECDPUN; michael@0: exprem=exp%DECDPUN; michael@0: /* subtract [A+B*(-m)] */ michael@0: accunits=decUnitAddSub(a, alength, b, blength, expunits, acc, michael@0: -(Int)powers[exprem]); michael@0: /* [UnitAddSub result may have leading zeros, even on zero] */ michael@0: if (accunits<0) result=-1; /* negative result */ michael@0: else { /* non-negative result */ michael@0: /* check units of the result before freeing any storage */ michael@0: for (u=acc; u=0 integers in Unit arrays */ michael@0: /* */ michael@0: /* This routine performs the calculation: */ michael@0: /* */ michael@0: /* C=A+(B*M) */ michael@0: /* */ michael@0: /* Where M is in the range -DECDPUNMAX through +DECDPUNMAX. */ michael@0: /* */ michael@0: /* A may be shorter or longer than B. */ michael@0: /* */ michael@0: /* Leading zeros are not removed after a calculation. The result is */ michael@0: /* either the same length as the longer of A and B (adding any */ michael@0: /* shift), or one Unit longer than that (if a Unit carry occurred). */ michael@0: /* */ michael@0: /* A and B content are not altered unless C is also A or B. */ michael@0: /* C may be the same array as A or B, but only if no zero padding is */ michael@0: /* requested (that is, C may be B only if bshift==0). */ michael@0: /* C is filled from the lsu; only those units necessary to complete */ michael@0: /* the calculation are referenced. */ michael@0: /* */ michael@0: /* Arg1 is A first Unit (lsu) */ michael@0: /* Arg2 is A length in Units */ michael@0: /* Arg3 is B first Unit (lsu) */ michael@0: /* Arg4 is B length in Units */ michael@0: /* Arg5 is B shift in Units (>=0; pads with 0 units if positive) */ michael@0: /* Arg6 is C first Unit (lsu) */ michael@0: /* Arg7 is M, the multiplier */ michael@0: /* */ michael@0: /* returns the count of Units written to C, which will be non-zero */ michael@0: /* and negated if the result is negative. That is, the sign of the */ michael@0: /* returned Int is the sign of the result (positive for zero) and */ michael@0: /* the absolute value of the Int is the count of Units. */ michael@0: /* */ michael@0: /* It is the caller's responsibility to make sure that C size is */ michael@0: /* safe, allowing space if necessary for a one-Unit carry. */ michael@0: /* */ michael@0: /* This routine is severely performance-critical; *any* change here */ michael@0: /* must be measured (timed) to assure no performance degradation. */ michael@0: /* In particular, trickery here tends to be counter-productive, as */ michael@0: /* increased complexity of code hurts register optimizations on */ michael@0: /* register-poor architectures. Avoiding divisions is nearly */ michael@0: /* always a Good Idea, however. */ michael@0: /* */ michael@0: /* Special thanks to Rick McGuire (IBM Cambridge, MA) and Dave Clark */ michael@0: /* (IBM Warwick, UK) for some of the ideas used in this routine. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static Int decUnitAddSub(const Unit *a, Int alength, michael@0: const Unit *b, Int blength, Int bshift, michael@0: Unit *c, Int m) { michael@0: const Unit *alsu=a; /* A lsu [need to remember it] */ michael@0: Unit *clsu=c; /* C ditto */ michael@0: Unit *minC; /* low water mark for C */ michael@0: Unit *maxC; /* high water mark for C */ michael@0: eInt carry=0; /* carry integer (could be Long) */ michael@0: Int add; /* work */ michael@0: #if DECDPUN<=4 /* myriadal, millenary, etc. */ michael@0: Int est; /* estimated quotient */ michael@0: #endif michael@0: michael@0: #if DECTRACE michael@0: if (alength<1 || blength<1) michael@0: printf("decUnitAddSub: alen blen m %ld %ld [%ld]\n", alength, blength, m); michael@0: #endif michael@0: michael@0: maxC=c+alength; /* A is usually the longer */ michael@0: minC=c+blength; /* .. and B the shorter */ michael@0: if (bshift!=0) { /* B is shifted; low As copy across */ michael@0: minC+=bshift; michael@0: /* if in place [common], skip copy unless there's a gap [rare] */ michael@0: if (a==c && bshift<=alength) { michael@0: c+=bshift; michael@0: a+=bshift; michael@0: } michael@0: else for (; cmaxC) { /* swap */ michael@0: Unit *hold=minC; michael@0: minC=maxC; michael@0: maxC=hold; michael@0: } michael@0: michael@0: /* For speed, do the addition as two loops; the first where both A */ michael@0: /* and B contribute, and the second (if necessary) where only one or */ michael@0: /* other of the numbers contribute. */ michael@0: /* Carry handling is the same (i.e., duplicated) in each case. */ michael@0: for (; c=0) { michael@0: est=(((ueInt)carry>>11)*53687)>>18; michael@0: *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */ michael@0: carry=est; /* likely quotient [89%] */ michael@0: if (*c>11)*53687)>>18; michael@0: *c=(Unit)(carry-est*(DECDPUNMAX+1)); michael@0: carry=est-(DECDPUNMAX+1); /* correctly negative */ michael@0: if (*c=0) { michael@0: est=(((ueInt)carry>>3)*16777)>>21; michael@0: *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */ michael@0: carry=est; /* likely quotient [99%] */ michael@0: if (*c>3)*16777)>>21; michael@0: *c=(Unit)(carry-est*(DECDPUNMAX+1)); michael@0: carry=est-(DECDPUNMAX+1); /* correctly negative */ michael@0: if (*c=0) { michael@0: est=QUOT10(carry, DECDPUN); michael@0: *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */ michael@0: carry=est; /* quotient */ michael@0: continue; michael@0: } michael@0: /* negative case */ michael@0: carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */ michael@0: est=QUOT10(carry, DECDPUN); michael@0: *c=(Unit)(carry-est*(DECDPUNMAX+1)); michael@0: carry=est-(DECDPUNMAX+1); /* correctly negative */ michael@0: #else michael@0: /* remainder operator is undefined if negative, so must test */ michael@0: if ((ueInt)carry<(DECDPUNMAX+1)*2) { /* fastpath carry +1 */ michael@0: *c=(Unit)(carry-(DECDPUNMAX+1)); /* [helps additions] */ michael@0: carry=1; michael@0: continue; michael@0: } michael@0: if (carry>=0) { michael@0: *c=(Unit)(carry%(DECDPUNMAX+1)); michael@0: carry=carry/(DECDPUNMAX+1); michael@0: continue; michael@0: } michael@0: /* negative case */ michael@0: carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */ michael@0: *c=(Unit)(carry%(DECDPUNMAX+1)); michael@0: carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1); michael@0: #endif michael@0: } /* c */ michael@0: michael@0: /* now may have one or other to complete */ michael@0: /* [pretest to avoid loop setup/shutdown] */ michael@0: if (cDECDPUNMAX */ michael@0: #if DECDPUN==4 /* use divide-by-multiply */ michael@0: if (carry>=0) { michael@0: est=(((ueInt)carry>>11)*53687)>>18; michael@0: *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */ michael@0: carry=est; /* likely quotient [79.7%] */ michael@0: if (*c>11)*53687)>>18; michael@0: *c=(Unit)(carry-est*(DECDPUNMAX+1)); michael@0: carry=est-(DECDPUNMAX+1); /* correctly negative */ michael@0: if (*c=0) { michael@0: est=(((ueInt)carry>>3)*16777)>>21; michael@0: *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */ michael@0: carry=est; /* likely quotient [99%] */ michael@0: if (*c>3)*16777)>>21; michael@0: *c=(Unit)(carry-est*(DECDPUNMAX+1)); michael@0: carry=est-(DECDPUNMAX+1); /* correctly negative */ michael@0: if (*c=0) { michael@0: est=QUOT10(carry, DECDPUN); michael@0: *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */ michael@0: carry=est; /* quotient */ michael@0: continue; michael@0: } michael@0: /* negative case */ michael@0: carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */ michael@0: est=QUOT10(carry, DECDPUN); michael@0: *c=(Unit)(carry-est*(DECDPUNMAX+1)); michael@0: carry=est-(DECDPUNMAX+1); /* correctly negative */ michael@0: #else michael@0: if ((ueInt)carry<(DECDPUNMAX+1)*2){ /* fastpath carry 1 */ michael@0: *c=(Unit)(carry-(DECDPUNMAX+1)); michael@0: carry=1; michael@0: continue; michael@0: } michael@0: /* remainder operator is undefined if negative, so must test */ michael@0: if (carry>=0) { michael@0: *c=(Unit)(carry%(DECDPUNMAX+1)); michael@0: carry=carry/(DECDPUNMAX+1); michael@0: continue; michael@0: } michael@0: /* negative case */ michael@0: carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */ michael@0: *c=(Unit)(carry%(DECDPUNMAX+1)); michael@0: carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1); michael@0: #endif michael@0: } /* c */ michael@0: michael@0: /* OK, all A and B processed; might still have carry or borrow */ michael@0: /* return number of Units in the result, negated if a borrow */ michael@0: if (carry==0) return c-clsu; /* no carry, so no more to do */ michael@0: if (carry>0) { /* positive carry */ michael@0: *c=(Unit)carry; /* place as new unit */ michael@0: c++; /* .. */ michael@0: return c-clsu; michael@0: } michael@0: /* -ve carry: it's a borrow; complement needed */ michael@0: add=1; /* temporary carry... */ michael@0: for (c=clsu; c current Unit */ michael@0: michael@0: #if DECCHECK michael@0: if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn; michael@0: #endif michael@0: michael@0: *dropped=0; /* assume no zeros dropped */ michael@0: if ((dn->bits & DECSPECIAL) /* fast exit if special .. */ michael@0: || (*dn->lsu & 0x01)) return dn; /* .. or odd */ michael@0: if (ISZERO(dn)) { /* .. or 0 */ michael@0: dn->exponent=0; /* (sign is preserved) */ michael@0: return dn; michael@0: } michael@0: michael@0: /* have a finite number which is even */ michael@0: exp=dn->exponent; michael@0: cut=1; /* digit (1-DECDPUN) in Unit */ michael@0: up=dn->lsu; /* -> current Unit */ michael@0: for (d=0; ddigits-1; d++) { /* [don't strip the final digit] */ michael@0: /* slice by powers */ michael@0: #if DECDPUN<=4 michael@0: uInt quot=QUOT10(*up, cut); michael@0: if ((*up-quot*powers[cut])!=0) break; /* found non-0 digit */ michael@0: #else michael@0: if (*up%powers[cut]!=0) break; /* found non-0 digit */ michael@0: #endif michael@0: /* have a trailing 0 */ michael@0: if (!all) { /* trimming */ michael@0: /* [if exp>0 then all trailing 0s are significant for trim] */ michael@0: if (exp<=0) { /* if digit might be significant */ michael@0: if (exp==0) break; /* then quit */ michael@0: exp++; /* next digit might be significant */ michael@0: } michael@0: } michael@0: cut++; /* next power */ michael@0: if (cut>DECDPUN) { /* need new Unit */ michael@0: up++; michael@0: cut=1; michael@0: } michael@0: } /* d */ michael@0: if (d==0) return dn; /* none to drop */ michael@0: michael@0: /* may need to limit drop if clamping */ michael@0: if (set->clamp && !noclamp) { michael@0: Int maxd=set->emax-set->digits+1-dn->exponent; michael@0: if (maxd<=0) return dn; /* nothing possible */ michael@0: if (d>maxd) d=maxd; michael@0: } michael@0: michael@0: /* effect the drop */ michael@0: decShiftToLeast(dn->lsu, D2U(dn->digits), d); michael@0: dn->exponent+=d; /* maintain numerical value */ michael@0: dn->digits-=d; /* new length */ michael@0: *dropped=d; /* report the count */ michael@0: return dn; michael@0: } /* decTrim */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decReverse -- reverse a Unit array in place */ michael@0: /* */ michael@0: /* ulo is the start of the array */ michael@0: /* uhi is the end of the array (highest Unit to include) */ michael@0: /* */ michael@0: /* The units ulo through uhi are reversed in place (if the number */ michael@0: /* of units is odd, the middle one is untouched). Note that the */ michael@0: /* digit(s) in each unit are unaffected. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static void decReverse(Unit *ulo, Unit *uhi) { michael@0: Unit temp; michael@0: for (; ulo=uar; source--, target--) *target=*source; michael@0: } michael@0: else { michael@0: first=uar+D2U(digits+shift)-1; /* where msu of source will end up */ michael@0: for (; source>=uar; source--, target--) { michael@0: /* split the source Unit and accumulate remainder for next */ michael@0: #if DECDPUN<=4 michael@0: uInt quot=QUOT10(*source, cut); michael@0: uInt rem=*source-quot*powers[cut]; michael@0: next+=quot; michael@0: #else michael@0: uInt rem=*source%powers[cut]; michael@0: next+=*source/powers[cut]; michael@0: #endif michael@0: if (target<=first) *target=(Unit)next; /* write to target iff valid */ michael@0: next=rem*powers[DECDPUN-cut]; /* save remainder for next Unit */ michael@0: } michael@0: } /* shift-move */ michael@0: michael@0: /* propagate any partial unit to one below and clear the rest */ michael@0: for (; target>=uar; target--) { michael@0: *target=(Unit)next; michael@0: next=0; michael@0: } michael@0: return digits+shift; michael@0: } /* decShiftToMost */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decShiftToLeast -- shift digits in array towards least significant */ michael@0: /* */ michael@0: /* uar is the array */ michael@0: /* units is length of the array, in units */ michael@0: /* shift is the number of digits to remove from the lsu end; it */ michael@0: /* must be zero or positive and <= than units*DECDPUN. */ michael@0: /* */ michael@0: /* returns the new length of the integer in the array, in units */ michael@0: /* */ michael@0: /* Removed digits are discarded (lost). Units not required to hold */ michael@0: /* the final result are unchanged. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static Int decShiftToLeast(Unit *uar, Int units, Int shift) { michael@0: Unit *target, *up; /* work */ michael@0: Int cut, count; /* work */ michael@0: Int quot, rem; /* for division */ michael@0: michael@0: if (shift==0) return units; /* [fastpath] nothing to do */ michael@0: if (shift==units*DECDPUN) { /* [fastpath] little to do */ michael@0: *uar=0; /* all digits cleared gives zero */ michael@0: return 1; /* leaves just the one */ michael@0: } michael@0: michael@0: target=uar; /* both paths */ michael@0: cut=MSUDIGITS(shift); michael@0: if (cut==DECDPUN) { /* unit-boundary case; easy */ michael@0: up=uar+D2U(shift); michael@0: for (; updigits is > set->digits) */ michael@0: /* set is the relevant context */ michael@0: /* status is the status accumulator */ michael@0: /* */ michael@0: /* returns an allocated decNumber with the rounded result. */ michael@0: /* */ michael@0: /* lostDigits and other status may be set by this. */ michael@0: /* */ michael@0: /* Since the input is an operand, it must not be modified. */ michael@0: /* Instead, return an allocated decNumber, rounded as required. */ michael@0: /* It is the caller's responsibility to free the allocated storage. */ michael@0: /* */ michael@0: /* If no storage is available then the result cannot be used, so NULL */ michael@0: /* is returned. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static decNumber *decRoundOperand(const decNumber *dn, decContext *set, michael@0: uInt *status) { michael@0: decNumber *res; /* result structure */ michael@0: uInt newstatus=0; /* status from round */ michael@0: Int residue=0; /* rounding accumulator */ michael@0: michael@0: /* Allocate storage for the returned decNumber, big enough for the */ michael@0: /* length specified by the context */ michael@0: res=(decNumber *)malloc(sizeof(decNumber) michael@0: +(D2U(set->digits)-1)*sizeof(Unit)); michael@0: if (res==NULL) { michael@0: *status|=DEC_Insufficient_storage; michael@0: return NULL; michael@0: } michael@0: decCopyFit(res, dn, set, &residue, &newstatus); michael@0: decApplyRound(res, set, residue, &newstatus); michael@0: michael@0: /* If that set Inexact then "lost digits" is raised... */ michael@0: if (newstatus & DEC_Inexact) newstatus|=DEC_Lost_digits; michael@0: *status|=newstatus; michael@0: return res; michael@0: } /* decRoundOperand */ michael@0: #endif michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decCopyFit -- copy a number, truncating the coefficient if needed */ michael@0: /* */ michael@0: /* dest is the target decNumber */ michael@0: /* src is the source decNumber */ michael@0: /* set is the context [used for length (digits) and rounding mode] */ michael@0: /* residue is the residue accumulator */ michael@0: /* status contains the current status to be updated */ michael@0: /* */ michael@0: /* (dest==src is allowed and will be a no-op if fits) */ michael@0: /* All fields are updated as required. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static void decCopyFit(decNumber *dest, const decNumber *src, michael@0: decContext *set, Int *residue, uInt *status) { michael@0: dest->bits=src->bits; michael@0: dest->exponent=src->exponent; michael@0: decSetCoeff(dest, set, src->lsu, src->digits, residue, status); michael@0: } /* decCopyFit */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decSetCoeff -- set the coefficient of a number */ michael@0: /* */ michael@0: /* dn is the number whose coefficient array is to be set. */ michael@0: /* It must have space for set->digits digits */ michael@0: /* set is the context [for size] */ michael@0: /* lsu -> lsu of the source coefficient [may be dn->lsu] */ michael@0: /* len is digits in the source coefficient [may be dn->digits] */ michael@0: /* residue is the residue accumulator. This has values as in */ michael@0: /* decApplyRound, and will be unchanged unless the */ michael@0: /* target size is less than len. In this case, the */ michael@0: /* coefficient is truncated and the residue is updated to */ michael@0: /* reflect the previous residue and the dropped digits. */ michael@0: /* status is the status accumulator, as usual */ michael@0: /* */ michael@0: /* The coefficient may already be in the number, or it can be an */ michael@0: /* external intermediate array. If it is in the number, lsu must == */ michael@0: /* dn->lsu and len must == dn->digits. */ michael@0: /* */ michael@0: /* Note that the coefficient length (len) may be < set->digits, and */ michael@0: /* in this case this merely copies the coefficient (or is a no-op */ michael@0: /* if dn->lsu==lsu). */ michael@0: /* */ michael@0: /* Note also that (only internally, from decQuantizeOp and */ michael@0: /* decSetSubnormal) the value of set->digits may be less than one, */ michael@0: /* indicating a round to left. This routine handles that case */ michael@0: /* correctly; caller ensures space. */ michael@0: /* */ michael@0: /* dn->digits, dn->lsu (and as required), and dn->exponent are */ michael@0: /* updated as necessary. dn->bits (sign) is unchanged. */ michael@0: /* */ michael@0: /* DEC_Rounded status is set if any digits are discarded. */ michael@0: /* DEC_Inexact status is set if any non-zero digits are discarded, or */ michael@0: /* incoming residue was non-0 (implies rounded) */ michael@0: /* ------------------------------------------------------------------ */ michael@0: /* mapping array: maps 0-9 to canonical residues, so that a residue */ michael@0: /* can be adjusted in the range [-1, +1] and achieve correct rounding */ michael@0: /* 0 1 2 3 4 5 6 7 8 9 */ michael@0: static const uByte resmap[10]={0, 3, 3, 3, 3, 5, 7, 7, 7, 7}; michael@0: static void decSetCoeff(decNumber *dn, decContext *set, const Unit *lsu, michael@0: Int len, Int *residue, uInt *status) { michael@0: Int discard; /* number of digits to discard */ michael@0: uInt cut; /* cut point in Unit */ michael@0: const Unit *up; /* work */ michael@0: Unit *target; /* .. */ michael@0: Int count; /* .. */ michael@0: #if DECDPUN<=4 michael@0: uInt temp; /* .. */ michael@0: #endif michael@0: michael@0: discard=len-set->digits; /* digits to discard */ michael@0: if (discard<=0) { /* no digits are being discarded */ michael@0: if (dn->lsu!=lsu) { /* copy needed */ michael@0: /* copy the coefficient array to the result number; no shift needed */ michael@0: count=len; /* avoids D2U */ michael@0: up=lsu; michael@0: for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN) michael@0: *target=*up; michael@0: dn->digits=len; /* set the new length */ michael@0: } michael@0: /* dn->exponent and residue are unchanged, record any inexactitude */ michael@0: if (*residue!=0) *status|=(DEC_Inexact | DEC_Rounded); michael@0: return; michael@0: } michael@0: michael@0: /* some digits must be discarded ... */ michael@0: dn->exponent+=discard; /* maintain numerical value */ michael@0: *status|=DEC_Rounded; /* accumulate Rounded status */ michael@0: if (*residue>1) *residue=1; /* previous residue now to right, so reduce */ michael@0: michael@0: if (discard>len) { /* everything, +1, is being discarded */ michael@0: /* guard digit is 0 */ michael@0: /* residue is all the number [NB could be all 0s] */ michael@0: if (*residue<=0) { /* not already positive */ michael@0: count=len; /* avoids D2U */ michael@0: for (up=lsu; count>0; up++, count-=DECDPUN) if (*up!=0) { /* found non-0 */ michael@0: *residue=1; michael@0: break; /* no need to check any others */ michael@0: } michael@0: } michael@0: if (*residue!=0) *status|=DEC_Inexact; /* record inexactitude */ michael@0: *dn->lsu=0; /* coefficient will now be 0 */ michael@0: dn->digits=1; /* .. */ michael@0: return; michael@0: } /* total discard */ michael@0: michael@0: /* partial discard [most common case] */ michael@0: /* here, at least the first (most significant) discarded digit exists */ michael@0: michael@0: /* spin up the number, noting residue during the spin, until get to */ michael@0: /* the Unit with the first discarded digit. When reach it, extract */ michael@0: /* it and remember its position */ michael@0: count=0; michael@0: for (up=lsu;; up++) { michael@0: count+=DECDPUN; michael@0: if (count>=discard) break; /* full ones all checked */ michael@0: if (*up!=0) *residue=1; michael@0: } /* up */ michael@0: michael@0: /* here up -> Unit with first discarded digit */ michael@0: cut=discard-(count-DECDPUN)-1; michael@0: if (cut==DECDPUN-1) { /* unit-boundary case (fast) */ michael@0: Unit half=(Unit)powers[DECDPUN]>>1; michael@0: /* set residue directly */ michael@0: if (*up>=half) { michael@0: if (*up>half) *residue=7; michael@0: else *residue+=5; /* add sticky bit */ michael@0: } michael@0: else { /* digits<=0) { /* special for Quantize/Subnormal :-( */ michael@0: *dn->lsu=0; /* .. result is 0 */ michael@0: dn->digits=1; /* .. */ michael@0: } michael@0: else { /* shift to least */ michael@0: count=set->digits; /* now digits to end up with */ michael@0: dn->digits=count; /* set the new length */ michael@0: up++; /* move to next */ michael@0: /* on unit boundary, so shift-down copy loop is simple */ michael@0: for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN) michael@0: *target=*up; michael@0: } michael@0: } /* unit-boundary case */ michael@0: michael@0: else { /* discard digit is in low digit(s), and not top digit */ michael@0: uInt discard1; /* first discarded digit */ michael@0: uInt quot, rem; /* for divisions */ michael@0: if (cut==0) quot=*up; /* is at bottom of unit */ michael@0: else /* cut>0 */ { /* it's not at bottom of unit */ michael@0: #if DECDPUN<=4 michael@0: U_ASSERT(/* cut >= 0 &&*/ cut <= 4); michael@0: quot=QUOT10(*up, cut); michael@0: rem=*up-quot*powers[cut]; michael@0: #else michael@0: rem=*up%powers[cut]; michael@0: quot=*up/powers[cut]; michael@0: #endif michael@0: if (rem!=0) *residue=1; michael@0: } michael@0: /* discard digit is now at bottom of quot */ michael@0: #if DECDPUN<=4 michael@0: temp=(quot*6554)>>16; /* fast /10 */ michael@0: /* Vowels algorithm here not a win (9 instructions) */ michael@0: discard1=quot-X10(temp); michael@0: quot=temp; michael@0: #else michael@0: discard1=quot%10; michael@0: quot=quot/10; michael@0: #endif michael@0: /* here, discard1 is the guard digit, and residue is everything */ michael@0: /* else [use mapping array to accumulate residue safely] */ michael@0: *residue+=resmap[discard1]; michael@0: cut++; /* update cut */ michael@0: /* here: up -> Unit of the array with bottom digit */ michael@0: /* cut is the division point for each Unit */ michael@0: /* quot holds the uncut high-order digits for the current unit */ michael@0: if (set->digits<=0) { /* special for Quantize/Subnormal :-( */ michael@0: *dn->lsu=0; /* .. result is 0 */ michael@0: dn->digits=1; /* .. */ michael@0: } michael@0: else { /* shift to least needed */ michael@0: count=set->digits; /* now digits to end up with */ michael@0: dn->digits=count; /* set the new length */ michael@0: /* shift-copy the coefficient array to the result number */ michael@0: for (target=dn->lsu; ; target++) { michael@0: *target=(Unit)quot; michael@0: count-=(DECDPUN-cut); michael@0: if (count<=0) break; michael@0: up++; michael@0: quot=*up; michael@0: #if DECDPUN<=4 michael@0: quot=QUOT10(quot, cut); michael@0: rem=*up-quot*powers[cut]; michael@0: #else michael@0: rem=quot%powers[cut]; michael@0: quot=quot/powers[cut]; michael@0: #endif michael@0: *target=(Unit)(*target+rem*powers[DECDPUN-cut]); michael@0: count-=cut; michael@0: if (count<=0) break; michael@0: } /* shift-copy loop */ michael@0: } /* shift to least */ michael@0: } /* not unit boundary */ michael@0: michael@0: if (*residue!=0) *status|=DEC_Inexact; /* record inexactitude */ michael@0: return; michael@0: } /* decSetCoeff */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decApplyRound -- apply pending rounding to a number */ michael@0: /* */ michael@0: /* dn is the number, with space for set->digits digits */ michael@0: /* set is the context [for size and rounding mode] */ michael@0: /* residue indicates pending rounding, being any accumulated */ michael@0: /* guard and sticky information. It may be: */ michael@0: /* 6-9: rounding digit is >5 */ michael@0: /* 5: rounding digit is exactly half-way */ michael@0: /* 1-4: rounding digit is <5 and >0 */ michael@0: /* 0: the coefficient is exact */ michael@0: /* -1: as 1, but the hidden digits are subtractive, that */ michael@0: /* is, of the opposite sign to dn. In this case the */ michael@0: /* coefficient must be non-0. This case occurs when */ michael@0: /* subtracting a small number (which can be reduced to */ michael@0: /* a sticky bit); see decAddOp. */ michael@0: /* status is the status accumulator, as usual */ michael@0: /* */ michael@0: /* This routine applies rounding while keeping the length of the */ michael@0: /* coefficient constant. The exponent and status are unchanged */ michael@0: /* except if: */ michael@0: /* */ michael@0: /* -- the coefficient was increased and is all nines (in which */ michael@0: /* case Overflow could occur, and is handled directly here so */ michael@0: /* the caller does not need to re-test for overflow) */ michael@0: /* */ michael@0: /* -- the coefficient was decreased and becomes all nines (in which */ michael@0: /* case Underflow could occur, and is also handled directly). */ michael@0: /* */ michael@0: /* All fields in dn are updated as required. */ michael@0: /* */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static void decApplyRound(decNumber *dn, decContext *set, Int residue, michael@0: uInt *status) { michael@0: Int bump; /* 1 if coefficient needs to be incremented */ michael@0: /* -1 if coefficient needs to be decremented */ michael@0: michael@0: if (residue==0) return; /* nothing to apply */ michael@0: michael@0: bump=0; /* assume a smooth ride */ michael@0: michael@0: /* now decide whether, and how, to round, depending on mode */ michael@0: switch (set->round) { michael@0: case DEC_ROUND_05UP: { /* round zero or five up (for reround) */ michael@0: /* This is the same as DEC_ROUND_DOWN unless there is a */ michael@0: /* positive residue and the lsd of dn is 0 or 5, in which case */ michael@0: /* it is bumped; when residue is <0, the number is therefore */ michael@0: /* bumped down unless the final digit was 1 or 6 (in which */ michael@0: /* case it is bumped down and then up -- a no-op) */ michael@0: Int lsd5=*dn->lsu%5; /* get lsd and quintate */ michael@0: if (residue<0 && lsd5!=1) bump=-1; michael@0: else if (residue>0 && lsd5==0) bump=1; michael@0: /* [bump==1 could be applied directly; use common path for clarity] */ michael@0: break;} /* r-05 */ michael@0: michael@0: case DEC_ROUND_DOWN: { michael@0: /* no change, except if negative residue */ michael@0: if (residue<0) bump=-1; michael@0: break;} /* r-d */ michael@0: michael@0: case DEC_ROUND_HALF_DOWN: { michael@0: if (residue>5) bump=1; michael@0: break;} /* r-h-d */ michael@0: michael@0: case DEC_ROUND_HALF_EVEN: { michael@0: if (residue>5) bump=1; /* >0.5 goes up */ michael@0: else if (residue==5) { /* exactly 0.5000... */ michael@0: /* 0.5 goes up iff [new] lsd is odd */ michael@0: if (*dn->lsu & 0x01) bump=1; michael@0: } michael@0: break;} /* r-h-e */ michael@0: michael@0: case DEC_ROUND_HALF_UP: { michael@0: if (residue>=5) bump=1; michael@0: break;} /* r-h-u */ michael@0: michael@0: case DEC_ROUND_UP: { michael@0: if (residue>0) bump=1; michael@0: break;} /* r-u */ michael@0: michael@0: case DEC_ROUND_CEILING: { michael@0: /* same as _UP for positive numbers, and as _DOWN for negatives */ michael@0: /* [negative residue cannot occur on 0] */ michael@0: if (decNumberIsNegative(dn)) { michael@0: if (residue<0) bump=-1; michael@0: } michael@0: else { michael@0: if (residue>0) bump=1; michael@0: } michael@0: break;} /* r-c */ michael@0: michael@0: case DEC_ROUND_FLOOR: { michael@0: /* same as _UP for negative numbers, and as _DOWN for positive */ michael@0: /* [negative residue cannot occur on 0] */ michael@0: if (!decNumberIsNegative(dn)) { michael@0: if (residue<0) bump=-1; michael@0: } michael@0: else { michael@0: if (residue>0) bump=1; michael@0: } michael@0: break;} /* r-f */ michael@0: michael@0: default: { /* e.g., DEC_ROUND_MAX */ michael@0: *status|=DEC_Invalid_context; michael@0: #if DECTRACE || (DECCHECK && DECVERB) michael@0: printf("Unknown rounding mode: %d\n", set->round); michael@0: #endif michael@0: break;} michael@0: } /* switch */ michael@0: michael@0: /* now bump the number, up or down, if need be */ michael@0: if (bump==0) return; /* no action required */ michael@0: michael@0: /* Simply use decUnitAddSub unless bumping up and the number is */ michael@0: /* all nines. In this special case set to 100... explicitly */ michael@0: /* and adjust the exponent by one (as otherwise could overflow */ michael@0: /* the array) */ michael@0: /* Similarly handle all-nines result if bumping down. */ michael@0: if (bump>0) { michael@0: Unit *up; /* work */ michael@0: uInt count=dn->digits; /* digits to be checked */ michael@0: for (up=dn->lsu; ; up++) { michael@0: if (count<=DECDPUN) { michael@0: /* this is the last Unit (the msu) */ michael@0: if (*up!=powers[count]-1) break; /* not still 9s */ michael@0: /* here if it, too, is all nines */ michael@0: *up=(Unit)powers[count-1]; /* here 999 -> 100 etc. */ michael@0: for (up=up-1; up>=dn->lsu; up--) *up=0; /* others all to 0 */ michael@0: dn->exponent++; /* and bump exponent */ michael@0: /* [which, very rarely, could cause Overflow...] */ michael@0: if ((dn->exponent+dn->digits)>set->emax+1) { michael@0: decSetOverflow(dn, set, status); michael@0: } michael@0: return; /* done */ michael@0: } michael@0: /* a full unit to check, with more to come */ michael@0: if (*up!=DECDPUNMAX) break; /* not still 9s */ michael@0: count-=DECDPUN; michael@0: } /* up */ michael@0: } /* bump>0 */ michael@0: else { /* -1 */ michael@0: /* here checking for a pre-bump of 1000... (leading 1, all */ michael@0: /* other digits zero) */ michael@0: Unit *up, *sup; /* work */ michael@0: uInt count=dn->digits; /* digits to be checked */ michael@0: for (up=dn->lsu; ; up++) { michael@0: if (count<=DECDPUN) { michael@0: /* this is the last Unit (the msu) */ michael@0: if (*up!=powers[count-1]) break; /* not 100.. */ michael@0: /* here if have the 1000... case */ michael@0: sup=up; /* save msu pointer */ michael@0: *up=(Unit)powers[count]-1; /* here 100 in msu -> 999 */ michael@0: /* others all to all-nines, too */ michael@0: for (up=up-1; up>=dn->lsu; up--) *up=(Unit)powers[DECDPUN]-1; michael@0: dn->exponent--; /* and bump exponent */ michael@0: michael@0: /* iff the number was at the subnormal boundary (exponent=etiny) */ michael@0: /* then the exponent is now out of range, so it will in fact get */ michael@0: /* clamped to etiny and the final 9 dropped. */ michael@0: /* printf(">> emin=%d exp=%d sdig=%d\n", set->emin, */ michael@0: /* dn->exponent, set->digits); */ michael@0: if (dn->exponent+1==set->emin-set->digits+1) { michael@0: if (count==1 && dn->digits==1) *sup=0; /* here 9 -> 0[.9] */ michael@0: else { michael@0: *sup=(Unit)powers[count-1]-1; /* here 999.. in msu -> 99.. */ michael@0: dn->digits--; michael@0: } michael@0: dn->exponent++; michael@0: *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded; michael@0: } michael@0: return; /* done */ michael@0: } michael@0: michael@0: /* a full unit to check, with more to come */ michael@0: if (*up!=0) break; /* not still 0s */ michael@0: count-=DECDPUN; michael@0: } /* up */ michael@0: michael@0: } /* bump<0 */ michael@0: michael@0: /* Actual bump needed. Do it. */ michael@0: decUnitAddSub(dn->lsu, D2U(dn->digits), uarrone, 1, 0, dn->lsu, bump); michael@0: } /* decApplyRound */ michael@0: michael@0: #if DECSUBSET michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decFinish -- finish processing a number */ michael@0: /* */ michael@0: /* dn is the number */ michael@0: /* set is the context */ michael@0: /* residue is the rounding accumulator (as in decApplyRound) */ michael@0: /* status is the accumulator */ michael@0: /* */ michael@0: /* This finishes off the current number by: */ michael@0: /* 1. If not extended: */ michael@0: /* a. Converting a zero result to clean '0' */ michael@0: /* b. Reducing positive exponents to 0, if would fit in digits */ michael@0: /* 2. Checking for overflow and subnormals (always) */ michael@0: /* Note this is just Finalize when no subset arithmetic. */ michael@0: /* All fields are updated as required. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static void decFinish(decNumber *dn, decContext *set, Int *residue, michael@0: uInt *status) { michael@0: if (!set->extended) { michael@0: if ISZERO(dn) { /* value is zero */ michael@0: dn->exponent=0; /* clean exponent .. */ michael@0: dn->bits=0; /* .. and sign */ michael@0: return; /* no error possible */ michael@0: } michael@0: if (dn->exponent>=0) { /* non-negative exponent */ michael@0: /* >0; reduce to integer if possible */ michael@0: if (set->digits >= (dn->exponent+dn->digits)) { michael@0: dn->digits=decShiftToMost(dn->lsu, dn->digits, dn->exponent); michael@0: dn->exponent=0; michael@0: } michael@0: } michael@0: } /* !extended */ michael@0: michael@0: decFinalize(dn, set, residue, status); michael@0: } /* decFinish */ michael@0: #endif michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decFinalize -- final check, clamp, and round of a number */ michael@0: /* */ michael@0: /* dn is the number */ michael@0: /* set is the context */ michael@0: /* residue is the rounding accumulator (as in decApplyRound) */ michael@0: /* status is the status accumulator */ michael@0: /* */ michael@0: /* This finishes off the current number by checking for subnormal */ michael@0: /* results, applying any pending rounding, checking for overflow, */ michael@0: /* and applying any clamping. */ michael@0: /* Underflow and overflow conditions are raised as appropriate. */ michael@0: /* All fields are updated as required. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static void decFinalize(decNumber *dn, decContext *set, Int *residue, michael@0: uInt *status) { michael@0: Int shift; /* shift needed if clamping */ michael@0: Int tinyexp=set->emin-dn->digits+1; /* precalculate subnormal boundary */ michael@0: michael@0: /* Must be careful, here, when checking the exponent as the */ michael@0: /* adjusted exponent could overflow 31 bits [because it may already */ michael@0: /* be up to twice the expected]. */ michael@0: michael@0: /* First test for subnormal. This must be done before any final */ michael@0: /* round as the result could be rounded to Nmin or 0. */ michael@0: if (dn->exponent<=tinyexp) { /* prefilter */ michael@0: Int comp; michael@0: decNumber nmin; michael@0: /* A very nasty case here is dn == Nmin and residue<0 */ michael@0: if (dn->exponentemin; michael@0: comp=decCompare(dn, &nmin, 1); /* (signless compare) */ michael@0: if (comp==BADINT) { /* oops */ michael@0: *status|=DEC_Insufficient_storage; /* abandon... */ michael@0: return; michael@0: } michael@0: if (*residue<0 && comp==0) { /* neg residue and dn==Nmin */ michael@0: decApplyRound(dn, set, *residue, status); /* might force down */ michael@0: decSetSubnormal(dn, set, residue, status); michael@0: return; michael@0: } michael@0: } michael@0: michael@0: /* now apply any pending round (this could raise overflow). */ michael@0: if (*residue!=0) decApplyRound(dn, set, *residue, status); michael@0: michael@0: /* Check for overflow [redundant in the 'rare' case] or clamp */ michael@0: if (dn->exponent<=set->emax-set->digits+1) return; /* neither needed */ michael@0: michael@0: michael@0: /* here when might have an overflow or clamp to do */ michael@0: if (dn->exponent>set->emax-dn->digits+1) { /* too big */ michael@0: decSetOverflow(dn, set, status); michael@0: return; michael@0: } michael@0: /* here when the result is normal but in clamp range */ michael@0: if (!set->clamp) return; michael@0: michael@0: /* here when need to apply the IEEE exponent clamp (fold-down) */ michael@0: shift=dn->exponent-(set->emax-set->digits+1); michael@0: michael@0: /* shift coefficient (if non-zero) */ michael@0: if (!ISZERO(dn)) { michael@0: dn->digits=decShiftToMost(dn->lsu, dn->digits, shift); michael@0: } michael@0: dn->exponent-=shift; /* adjust the exponent to match */ michael@0: *status|=DEC_Clamped; /* and record the dirty deed */ michael@0: return; michael@0: } /* decFinalize */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decSetOverflow -- set number to proper overflow value */ michael@0: /* */ michael@0: /* dn is the number (used for sign [only] and result) */ michael@0: /* set is the context [used for the rounding mode, etc.] */ michael@0: /* status contains the current status to be updated */ michael@0: /* */ michael@0: /* This sets the sign of a number and sets its value to either */ michael@0: /* Infinity or the maximum finite value, depending on the sign of */ michael@0: /* dn and the rounding mode, following IEEE 754 rules. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static void decSetOverflow(decNumber *dn, decContext *set, uInt *status) { michael@0: Flag needmax=0; /* result is maximum finite value */ michael@0: uByte sign=dn->bits&DECNEG; /* clean and save sign bit */ michael@0: michael@0: if (ISZERO(dn)) { /* zero does not overflow magnitude */ michael@0: Int emax=set->emax; /* limit value */ michael@0: if (set->clamp) emax-=set->digits-1; /* lower if clamping */ michael@0: if (dn->exponent>emax) { /* clamp required */ michael@0: dn->exponent=emax; michael@0: *status|=DEC_Clamped; michael@0: } michael@0: return; michael@0: } michael@0: michael@0: uprv_decNumberZero(dn); michael@0: switch (set->round) { michael@0: case DEC_ROUND_DOWN: { michael@0: needmax=1; /* never Infinity */ michael@0: break;} /* r-d */ michael@0: case DEC_ROUND_05UP: { michael@0: needmax=1; /* never Infinity */ michael@0: break;} /* r-05 */ michael@0: case DEC_ROUND_CEILING: { michael@0: if (sign) needmax=1; /* Infinity if non-negative */ michael@0: break;} /* r-c */ michael@0: case DEC_ROUND_FLOOR: { michael@0: if (!sign) needmax=1; /* Infinity if negative */ michael@0: break;} /* r-f */ michael@0: default: break; /* Infinity in all other cases */ michael@0: } michael@0: if (needmax) { michael@0: decSetMaxValue(dn, set); michael@0: dn->bits=sign; /* set sign */ michael@0: } michael@0: else dn->bits=sign|DECINF; /* Value is +/-Infinity */ michael@0: *status|=DEC_Overflow | DEC_Inexact | DEC_Rounded; michael@0: } /* decSetOverflow */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decSetMaxValue -- set number to +Nmax (maximum normal value) */ michael@0: /* */ michael@0: /* dn is the number to set */ michael@0: /* set is the context [used for digits and emax] */ michael@0: /* */ michael@0: /* This sets the number to the maximum positive value. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static void decSetMaxValue(decNumber *dn, decContext *set) { michael@0: Unit *up; /* work */ michael@0: Int count=set->digits; /* nines to add */ michael@0: dn->digits=count; michael@0: /* fill in all nines to set maximum value */ michael@0: for (up=dn->lsu; ; up++) { michael@0: if (count>DECDPUN) *up=DECDPUNMAX; /* unit full o'nines */ michael@0: else { /* this is the msu */ michael@0: *up=(Unit)(powers[count]-1); michael@0: break; michael@0: } michael@0: count-=DECDPUN; /* filled those digits */ michael@0: } /* up */ michael@0: dn->bits=0; /* + sign */ michael@0: dn->exponent=set->emax-set->digits+1; michael@0: } /* decSetMaxValue */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decSetSubnormal -- process value whose exponent is extended) { michael@0: uprv_decNumberZero(dn); michael@0: /* always full overflow */ michael@0: *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded; michael@0: return; michael@0: } michael@0: #endif michael@0: michael@0: /* Full arithmetic -- allow subnormals, rounded to minimum exponent */ michael@0: /* (Etiny) if needed */ michael@0: etiny=set->emin-(set->digits-1); /* smallest allowed exponent */ michael@0: michael@0: if ISZERO(dn) { /* value is zero */ michael@0: /* residue can never be non-zero here */ michael@0: #if DECCHECK michael@0: if (*residue!=0) { michael@0: printf("++ Subnormal 0 residue %ld\n", (LI)*residue); michael@0: *status|=DEC_Invalid_operation; michael@0: } michael@0: #endif michael@0: if (dn->exponentexponent=etiny; michael@0: *status|=DEC_Clamped; michael@0: } michael@0: return; michael@0: } michael@0: michael@0: *status|=DEC_Subnormal; /* have a non-zero subnormal */ michael@0: adjust=etiny-dn->exponent; /* calculate digits to remove */ michael@0: if (adjust<=0) { /* not out of range; unrounded */ michael@0: /* residue can never be non-zero here, except in the Nmin-residue */ michael@0: /* case (which is a subnormal result), so can take fast-path here */ michael@0: /* it may already be inexact (from setting the coefficient) */ michael@0: if (*status&DEC_Inexact) *status|=DEC_Underflow; michael@0: return; michael@0: } michael@0: michael@0: /* adjust>0, so need to rescale the result so exponent becomes Etiny */ michael@0: /* [this code is similar to that in rescale] */ michael@0: workset=*set; /* clone rounding, etc. */ michael@0: workset.digits=dn->digits-adjust; /* set requested length */ michael@0: workset.emin-=adjust; /* and adjust emin to match */ michael@0: /* [note that the latter can be <1, here, similar to Rescale case] */ michael@0: decSetCoeff(dn, &workset, dn->lsu, dn->digits, residue, status); michael@0: decApplyRound(dn, &workset, *residue, status); michael@0: michael@0: /* Use 754 default rule: Underflow is set iff Inexact */ michael@0: /* [independent of whether trapped] */ michael@0: if (*status&DEC_Inexact) *status|=DEC_Underflow; michael@0: michael@0: /* if rounded up a 999s case, exponent will be off by one; adjust */ michael@0: /* back if so [it will fit, because it was shortened earlier] */ michael@0: if (dn->exponent>etiny) { michael@0: dn->digits=decShiftToMost(dn->lsu, dn->digits, 1); michael@0: dn->exponent--; /* (re)adjust the exponent. */ michael@0: } michael@0: michael@0: /* if rounded to zero, it is by definition clamped... */ michael@0: if (ISZERO(dn)) *status|=DEC_Clamped; michael@0: } /* decSetSubnormal */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decCheckMath - check entry conditions for a math function */ michael@0: /* */ michael@0: /* This checks the context and the operand */ michael@0: /* */ michael@0: /* rhs is the operand to check */ michael@0: /* set is the context to check */ michael@0: /* status is unchanged if both are good */ michael@0: /* */ michael@0: /* returns non-zero if status is changed, 0 otherwise */ michael@0: /* */ michael@0: /* Restrictions enforced: */ michael@0: /* */ michael@0: /* digits, emax, and -emin in the context must be less than */ michael@0: /* DEC_MAX_MATH (999999), and A must be within these bounds if */ michael@0: /* non-zero. Invalid_operation is set in the status if a */ michael@0: /* restriction is violated. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static uInt decCheckMath(const decNumber *rhs, decContext *set, michael@0: uInt *status) { michael@0: uInt save=*status; /* record */ michael@0: if (set->digits>DEC_MAX_MATH michael@0: || set->emax>DEC_MAX_MATH michael@0: || -set->emin>DEC_MAX_MATH) *status|=DEC_Invalid_context; michael@0: else if ((rhs->digits>DEC_MAX_MATH michael@0: || rhs->exponent+rhs->digits>DEC_MAX_MATH+1 michael@0: || rhs->exponent+rhs->digits<2*(1-DEC_MAX_MATH)) michael@0: && !ISZERO(rhs)) *status|=DEC_Invalid_operation; michael@0: return (*status!=save); michael@0: } /* decCheckMath */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decGetInt -- get integer from a number */ michael@0: /* */ michael@0: /* dn is the number [which will not be altered] */ michael@0: /* */ michael@0: /* returns one of: */ michael@0: /* BADINT if there is a non-zero fraction */ michael@0: /* the converted integer */ michael@0: /* BIGEVEN if the integer is even and magnitude > 2*10**9 */ michael@0: /* BIGODD if the integer is odd and magnitude > 2*10**9 */ michael@0: /* */ michael@0: /* This checks and gets a whole number from the input decNumber. */ michael@0: /* The sign can be determined from dn by the caller when BIGEVEN or */ michael@0: /* BIGODD is returned. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static Int decGetInt(const decNumber *dn) { michael@0: Int theInt; /* result accumulator */ michael@0: const Unit *up; /* work */ michael@0: Int got; /* digits (real or not) processed */ michael@0: Int ilength=dn->digits+dn->exponent; /* integral length */ michael@0: Flag neg=decNumberIsNegative(dn); /* 1 if -ve */ michael@0: michael@0: /* The number must be an integer that fits in 10 digits */ michael@0: /* Assert, here, that 10 is enough for any rescale Etiny */ michael@0: #if DEC_MAX_EMAX > 999999999 michael@0: #error GetInt may need updating [for Emax] michael@0: #endif michael@0: #if DEC_MIN_EMIN < -999999999 michael@0: #error GetInt may need updating [for Emin] michael@0: #endif michael@0: if (ISZERO(dn)) return 0; /* zeros are OK, with any exponent */ michael@0: michael@0: up=dn->lsu; /* ready for lsu */ michael@0: theInt=0; /* ready to accumulate */ michael@0: if (dn->exponent>=0) { /* relatively easy */ michael@0: /* no fractional part [usual]; allow for positive exponent */ michael@0: got=dn->exponent; michael@0: } michael@0: else { /* -ve exponent; some fractional part to check and discard */ michael@0: Int count=-dn->exponent; /* digits to discard */ michael@0: /* spin up whole units until reach the Unit with the unit digit */ michael@0: for (; count>=DECDPUN; up++) { michael@0: if (*up!=0) return BADINT; /* non-zero Unit to discard */ michael@0: count-=DECDPUN; michael@0: } michael@0: if (count==0) got=0; /* [a multiple of DECDPUN] */ michael@0: else { /* [not multiple of DECDPUN] */ michael@0: Int rem; /* work */ michael@0: /* slice off fraction digits and check for non-zero */ michael@0: #if DECDPUN<=4 michael@0: theInt=QUOT10(*up, count); michael@0: rem=*up-theInt*powers[count]; michael@0: #else michael@0: rem=*up%powers[count]; /* slice off discards */ michael@0: theInt=*up/powers[count]; michael@0: #endif michael@0: if (rem!=0) return BADINT; /* non-zero fraction */ michael@0: /* it looks good */ michael@0: got=DECDPUN-count; /* number of digits so far */ michael@0: up++; /* ready for next */ michael@0: } michael@0: } michael@0: /* now it's known there's no fractional part */ michael@0: michael@0: /* tricky code now, to accumulate up to 9.3 digits */ michael@0: if (got==0) {theInt=*up; got+=DECDPUN; up++;} /* ensure lsu is there */ michael@0: michael@0: if (ilength<11) { michael@0: Int save=theInt; michael@0: /* collect any remaining unit(s) */ michael@0: for (; got1999999997) ilength=11; michael@0: else if (!neg && theInt>999999999) ilength=11; michael@0: if (ilength==11) theInt=save; /* restore correct low bit */ michael@0: } michael@0: } michael@0: michael@0: if (ilength>10) { /* too big */ michael@0: if (theInt&1) return BIGODD; /* bottom bit 1 */ michael@0: return BIGEVEN; /* bottom bit 0 */ michael@0: } michael@0: michael@0: if (neg) theInt=-theInt; /* apply sign */ michael@0: return theInt; michael@0: } /* decGetInt */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decDecap -- decapitate the coefficient of a number */ michael@0: /* */ michael@0: /* dn is the number to be decapitated */ michael@0: /* drop is the number of digits to be removed from the left of dn; */ michael@0: /* this must be <= dn->digits (if equal, the coefficient is */ michael@0: /* set to 0) */ michael@0: /* */ michael@0: /* Returns dn; dn->digits will be <= the initial digits less drop */ michael@0: /* (after removing drop digits there may be leading zero digits */ michael@0: /* which will also be removed). Only dn->lsu and dn->digits change. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static decNumber *decDecap(decNumber *dn, Int drop) { michael@0: Unit *msu; /* -> target cut point */ michael@0: Int cut; /* work */ michael@0: if (drop>=dn->digits) { /* losing the whole thing */ michael@0: #if DECCHECK michael@0: if (drop>dn->digits) michael@0: printf("decDecap called with drop>digits [%ld>%ld]\n", michael@0: (LI)drop, (LI)dn->digits); michael@0: #endif michael@0: dn->lsu[0]=0; michael@0: dn->digits=1; michael@0: return dn; michael@0: } michael@0: msu=dn->lsu+D2U(dn->digits-drop)-1; /* -> likely msu */ michael@0: cut=MSUDIGITS(dn->digits-drop); /* digits to be in use in msu */ michael@0: if (cut!=DECDPUN) *msu%=powers[cut]; /* clear left digits */ michael@0: /* that may have left leading zero digits, so do a proper count... */ michael@0: dn->digits=decGetDigits(dn->lsu, msu-dn->lsu+1); michael@0: return dn; michael@0: } /* decDecap */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decBiStr -- compare string with pairwise options */ michael@0: /* */ michael@0: /* targ is the string to compare */ michael@0: /* str1 is one of the strings to compare against (length may be 0) */ michael@0: /* str2 is the other; it must be the same length as str1 */ michael@0: /* */ michael@0: /* returns 1 if strings compare equal, (that is, it is the same */ michael@0: /* length as str1 and str2, and each character of targ is in either */ michael@0: /* str1 or str2 in the corresponding position), or 0 otherwise */ michael@0: /* */ michael@0: /* This is used for generic caseless compare, including the awkward */ michael@0: /* case of the Turkish dotted and dotless Is. Use as (for example): */ michael@0: /* if (decBiStr(test, "mike", "MIKE")) ... */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static Flag decBiStr(const char *targ, const char *str1, const char *str2) { michael@0: for (;;targ++, str1++, str2++) { michael@0: if (*targ!=*str1 && *targ!=*str2) return 0; michael@0: /* *targ has a match in one (or both, if terminator) */ michael@0: if (*targ=='\0') break; michael@0: } /* forever */ michael@0: return 1; michael@0: } /* decBiStr */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNaNs -- handle NaN operand or operands */ michael@0: /* */ michael@0: /* res is the result number */ michael@0: /* lhs is the first operand */ michael@0: /* rhs is the second operand, or NULL if none */ michael@0: /* context is used to limit payload length */ michael@0: /* status contains the current status */ michael@0: /* returns res in case convenient */ michael@0: /* */ michael@0: /* Called when one or both operands is a NaN, and propagates the */ michael@0: /* appropriate result to res. When an sNaN is found, it is changed */ michael@0: /* to a qNaN and Invalid operation is set. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static decNumber * decNaNs(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set, michael@0: uInt *status) { michael@0: /* This decision tree ends up with LHS being the source pointer, */ michael@0: /* and status updated if need be */ michael@0: if (lhs->bits & DECSNAN) michael@0: *status|=DEC_Invalid_operation | DEC_sNaN; michael@0: else if (rhs==NULL); michael@0: else if (rhs->bits & DECSNAN) { michael@0: lhs=rhs; michael@0: *status|=DEC_Invalid_operation | DEC_sNaN; michael@0: } michael@0: else if (lhs->bits & DECNAN); michael@0: else lhs=rhs; michael@0: michael@0: /* propagate the payload */ michael@0: if (lhs->digits<=set->digits) uprv_decNumberCopy(res, lhs); /* easy */ michael@0: else { /* too long */ michael@0: const Unit *ul; michael@0: Unit *ur, *uresp1; michael@0: /* copy safe number of units, then decapitate */ michael@0: res->bits=lhs->bits; /* need sign etc. */ michael@0: uresp1=res->lsu+D2U(set->digits); michael@0: for (ur=res->lsu, ul=lhs->lsu; urdigits=D2U(set->digits)*DECDPUN; michael@0: /* maybe still too long */ michael@0: if (res->digits>set->digits) decDecap(res, res->digits-set->digits); michael@0: } michael@0: michael@0: res->bits&=~DECSNAN; /* convert any sNaN to NaN, while */ michael@0: res->bits|=DECNAN; /* .. preserving sign */ michael@0: res->exponent=0; /* clean exponent */ michael@0: /* [coefficient was copied/decapitated] */ michael@0: return res; michael@0: } /* decNaNs */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decStatus -- apply non-zero status */ michael@0: /* */ michael@0: /* dn is the number to set if error */ michael@0: /* status contains the current status (not yet in context) */ michael@0: /* set is the context */ michael@0: /* */ michael@0: /* If the status is an error status, the number is set to a NaN, */ michael@0: /* unless the error was an overflow, divide-by-zero, or underflow, */ michael@0: /* in which case the number will have already been set. */ michael@0: /* */ michael@0: /* The context status is then updated with the new status. Note that */ michael@0: /* this may raise a signal, so control may never return from this */ michael@0: /* routine (hence resources must be recovered before it is called). */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static void decStatus(decNumber *dn, uInt status, decContext *set) { michael@0: if (status & DEC_NaNs) { /* error status -> NaN */ michael@0: /* if cause was an sNaN, clear and propagate [NaN is already set up] */ michael@0: if (status & DEC_sNaN) status&=~DEC_sNaN; michael@0: else { michael@0: uprv_decNumberZero(dn); /* other error: clean throughout */ michael@0: dn->bits=DECNAN; /* and make a quiet NaN */ michael@0: } michael@0: } michael@0: uprv_decContextSetStatus(set, status); /* [may not return] */ michael@0: return; michael@0: } /* decStatus */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decGetDigits -- count digits in a Units array */ michael@0: /* */ michael@0: /* uar is the Unit array holding the number (this is often an */ michael@0: /* accumulator of some sort) */ michael@0: /* len is the length of the array in units [>=1] */ michael@0: /* */ michael@0: /* returns the number of (significant) digits in the array */ michael@0: /* */ michael@0: /* All leading zeros are excluded, except the last if the array has */ michael@0: /* only zero Units. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: /* This may be called twice during some operations. */ michael@0: static Int decGetDigits(Unit *uar, Int len) { michael@0: Unit *up=uar+(len-1); /* -> msu */ michael@0: Int digits=(len-1)*DECDPUN+1; /* possible digits excluding msu */ michael@0: #if DECDPUN>4 michael@0: uInt const *pow; /* work */ michael@0: #endif michael@0: /* (at least 1 in final msu) */ michael@0: #if DECCHECK michael@0: if (len<1) printf("decGetDigits called with len<1 [%ld]\n", (LI)len); michael@0: #endif michael@0: michael@0: for (; up>=uar; up--) { michael@0: if (*up==0) { /* unit is all 0s */ michael@0: if (digits==1) break; /* a zero has one digit */ michael@0: digits-=DECDPUN; /* adjust for 0 unit */ michael@0: continue;} michael@0: /* found the first (most significant) non-zero Unit */ michael@0: #if DECDPUN>1 /* not done yet */ michael@0: if (*up<10) break; /* is 1-9 */ michael@0: digits++; michael@0: #if DECDPUN>2 /* not done yet */ michael@0: if (*up<100) break; /* is 10-99 */ michael@0: digits++; michael@0: #if DECDPUN>3 /* not done yet */ michael@0: if (*up<1000) break; /* is 100-999 */ michael@0: digits++; michael@0: #if DECDPUN>4 /* count the rest ... */ michael@0: for (pow=&powers[4]; *up>=*pow; pow++) digits++; michael@0: #endif michael@0: #endif michael@0: #endif michael@0: #endif michael@0: break; michael@0: } /* up */ michael@0: return digits; michael@0: } /* decGetDigits */ michael@0: michael@0: #if DECTRACE | DECCHECK michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decNumberShow -- display a number [debug aid] */ michael@0: /* dn is the number to show */ michael@0: /* */ michael@0: /* Shows: sign, exponent, coefficient (msu first), digits */ michael@0: /* or: sign, special-value */ michael@0: /* ------------------------------------------------------------------ */ michael@0: /* this is public so other modules can use it */ michael@0: void uprv_decNumberShow(const decNumber *dn) { michael@0: const Unit *up; /* work */ michael@0: uInt u, d; /* .. */ michael@0: Int cut; /* .. */ michael@0: char isign='+'; /* main sign */ michael@0: if (dn==NULL) { michael@0: printf("NULL\n"); michael@0: return;} michael@0: if (decNumberIsNegative(dn)) isign='-'; michael@0: printf(" >> %c ", isign); michael@0: if (dn->bits&DECSPECIAL) { /* Is a special value */ michael@0: if (decNumberIsInfinite(dn)) printf("Infinity"); michael@0: else { /* a NaN */ michael@0: if (dn->bits&DECSNAN) printf("sNaN"); /* signalling NaN */ michael@0: else printf("NaN"); michael@0: } michael@0: /* if coefficient and exponent are 0, no more to do */ michael@0: if (dn->exponent==0 && dn->digits==1 && *dn->lsu==0) { michael@0: printf("\n"); michael@0: return;} michael@0: /* drop through to report other information */ michael@0: printf(" "); michael@0: } michael@0: michael@0: /* now carefully display the coefficient */ michael@0: up=dn->lsu+D2U(dn->digits)-1; /* msu */ michael@0: printf("%ld", (LI)*up); michael@0: for (up=up-1; up>=dn->lsu; up--) { michael@0: u=*up; michael@0: printf(":"); michael@0: for (cut=DECDPUN-1; cut>=0; cut--) { michael@0: d=u/powers[cut]; michael@0: u-=d*powers[cut]; michael@0: printf("%ld", (LI)d); michael@0: } /* cut */ michael@0: } /* up */ michael@0: if (dn->exponent!=0) { michael@0: char esign='+'; michael@0: if (dn->exponent<0) esign='-'; michael@0: printf(" E%c%ld", esign, (LI)abs(dn->exponent)); michael@0: } michael@0: printf(" [%ld]\n", (LI)dn->digits); michael@0: } /* decNumberShow */ michael@0: #endif michael@0: michael@0: #if DECTRACE || DECCHECK michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decDumpAr -- display a unit array [debug/check aid] */ michael@0: /* name is a single-character tag name */ michael@0: /* ar is the array to display */ michael@0: /* len is the length of the array in Units */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static void decDumpAr(char name, const Unit *ar, Int len) { michael@0: Int i; michael@0: const char *spec; michael@0: #if DECDPUN==9 michael@0: spec="%09d "; michael@0: #elif DECDPUN==8 michael@0: spec="%08d "; michael@0: #elif DECDPUN==7 michael@0: spec="%07d "; michael@0: #elif DECDPUN==6 michael@0: spec="%06d "; michael@0: #elif DECDPUN==5 michael@0: spec="%05d "; michael@0: #elif DECDPUN==4 michael@0: spec="%04d "; michael@0: #elif DECDPUN==3 michael@0: spec="%03d "; michael@0: #elif DECDPUN==2 michael@0: spec="%02d "; michael@0: #else michael@0: spec="%d "; michael@0: #endif michael@0: printf(" :%c: ", name); michael@0: for (i=len-1; i>=0; i--) { michael@0: if (i==len-1) printf("%ld ", (LI)ar[i]); michael@0: else printf(spec, ar[i]); michael@0: } michael@0: printf("\n"); michael@0: return;} michael@0: #endif michael@0: michael@0: #if DECCHECK michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decCheckOperands -- check operand(s) to a routine */ michael@0: /* res is the result structure (not checked; it will be set to */ michael@0: /* quiet NaN if error found (and it is not NULL)) */ michael@0: /* lhs is the first operand (may be DECUNRESU) */ michael@0: /* rhs is the second (may be DECUNUSED) */ michael@0: /* set is the context (may be DECUNCONT) */ michael@0: /* returns 0 if both operands, and the context are clean, or 1 */ michael@0: /* otherwise (in which case the context will show an error, */ michael@0: /* unless NULL). Note that res is not cleaned; caller should */ michael@0: /* handle this so res=NULL case is safe. */ michael@0: /* The caller is expected to abandon immediately if 1 is returned. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static Flag decCheckOperands(decNumber *res, const decNumber *lhs, michael@0: const decNumber *rhs, decContext *set) { michael@0: Flag bad=0; michael@0: if (set==NULL) { /* oops; hopeless */ michael@0: #if DECTRACE || DECVERB michael@0: printf("Reference to context is NULL.\n"); michael@0: #endif michael@0: bad=1; michael@0: return 1;} michael@0: else if (set!=DECUNCONT michael@0: && (set->digits<1 || set->round>=DEC_ROUND_MAX)) { michael@0: bad=1; michael@0: #if DECTRACE || DECVERB michael@0: printf("Bad context [digits=%ld round=%ld].\n", michael@0: (LI)set->digits, (LI)set->round); michael@0: #endif michael@0: } michael@0: else { michael@0: if (res==NULL) { michael@0: bad=1; michael@0: #if DECTRACE michael@0: /* this one not DECVERB as standard tests include NULL */ michael@0: printf("Reference to result is NULL.\n"); michael@0: #endif michael@0: } michael@0: if (!bad && lhs!=DECUNUSED) bad=(decCheckNumber(lhs)); michael@0: if (!bad && rhs!=DECUNUSED) bad=(decCheckNumber(rhs)); michael@0: } michael@0: if (bad) { michael@0: if (set!=DECUNCONT) uprv_decContextSetStatus(set, DEC_Invalid_operation); michael@0: if (res!=DECUNRESU && res!=NULL) { michael@0: uprv_decNumberZero(res); michael@0: res->bits=DECNAN; /* qNaN */ michael@0: } michael@0: } michael@0: return bad; michael@0: } /* decCheckOperands */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decCheckNumber -- check a number */ michael@0: /* dn is the number to check */ michael@0: /* returns 0 if the number is clean, or 1 otherwise */ michael@0: /* */ michael@0: /* The number is considered valid if it could be a result from some */ michael@0: /* operation in some valid context. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static Flag decCheckNumber(const decNumber *dn) { michael@0: const Unit *up; /* work */ michael@0: uInt maxuint; /* .. */ michael@0: Int ae, d, digits; /* .. */ michael@0: Int emin, emax; /* .. */ michael@0: michael@0: if (dn==NULL) { /* hopeless */ michael@0: #if DECTRACE michael@0: /* this one not DECVERB as standard tests include NULL */ michael@0: printf("Reference to decNumber is NULL.\n"); michael@0: #endif michael@0: return 1;} michael@0: michael@0: /* check special values */ michael@0: if (dn->bits & DECSPECIAL) { michael@0: if (dn->exponent!=0) { michael@0: #if DECTRACE || DECVERB michael@0: printf("Exponent %ld (not 0) for a special value [%02x].\n", michael@0: (LI)dn->exponent, dn->bits); michael@0: #endif michael@0: return 1;} michael@0: michael@0: /* 2003.09.08: NaNs may now have coefficients, so next tests Inf only */ michael@0: if (decNumberIsInfinite(dn)) { michael@0: if (dn->digits!=1) { michael@0: #if DECTRACE || DECVERB michael@0: printf("Digits %ld (not 1) for an infinity.\n", (LI)dn->digits); michael@0: #endif michael@0: return 1;} michael@0: if (*dn->lsu!=0) { michael@0: #if DECTRACE || DECVERB michael@0: printf("LSU %ld (not 0) for an infinity.\n", (LI)*dn->lsu); michael@0: #endif michael@0: decDumpAr('I', dn->lsu, D2U(dn->digits)); michael@0: return 1;} michael@0: } /* Inf */ michael@0: /* 2002.12.26: negative NaNs can now appear through proposed IEEE */ michael@0: /* concrete formats (decimal64, etc.). */ michael@0: return 0; michael@0: } michael@0: michael@0: /* check the coefficient */ michael@0: if (dn->digits<1 || dn->digits>DECNUMMAXP) { michael@0: #if DECTRACE || DECVERB michael@0: printf("Digits %ld in number.\n", (LI)dn->digits); michael@0: #endif michael@0: return 1;} michael@0: michael@0: d=dn->digits; michael@0: michael@0: for (up=dn->lsu; d>0; up++) { michael@0: if (d>DECDPUN) maxuint=DECDPUNMAX; michael@0: else { /* reached the msu */ michael@0: maxuint=powers[d]-1; michael@0: if (dn->digits>1 && *upmaxuint) { michael@0: #if DECTRACE || DECVERB michael@0: printf("Bad Unit [%08lx] in %ld-digit number at offset %ld [maxuint %ld].\n", michael@0: (LI)*up, (LI)dn->digits, (LI)(up-dn->lsu), (LI)maxuint); michael@0: #endif michael@0: return 1;} michael@0: d-=DECDPUN; michael@0: } michael@0: michael@0: /* check the exponent. Note that input operands can have exponents */ michael@0: /* which are out of the set->emin/set->emax and set->digits range */ michael@0: /* (just as they can have more digits than set->digits). */ michael@0: ae=dn->exponent+dn->digits-1; /* adjusted exponent */ michael@0: emax=DECNUMMAXE; michael@0: emin=DECNUMMINE; michael@0: digits=DECNUMMAXP; michael@0: if (ae+emax) { michael@0: #if DECTRACE || DECVERB michael@0: printf("Adjusted exponent overflow [%ld].\n", (LI)ae); michael@0: uprv_decNumberShow(dn); michael@0: #endif michael@0: return 1;} michael@0: michael@0: return 0; /* it's OK */ michael@0: } /* decCheckNumber */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decCheckInexact -- check a normal finite inexact result has digits */ michael@0: /* dn is the number to check */ michael@0: /* set is the context (for status and precision) */ michael@0: /* sets Invalid operation, etc., if some digits are missing */ michael@0: /* [this check is not made for DECSUBSET compilation or when */ michael@0: /* subnormal is not set] */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static void decCheckInexact(const decNumber *dn, decContext *set) { michael@0: #if !DECSUBSET && DECEXTFLAG michael@0: if ((set->status & (DEC_Inexact|DEC_Subnormal))==DEC_Inexact michael@0: && (set->digits!=dn->digits) && !(dn->bits & DECSPECIAL)) { michael@0: #if DECTRACE || DECVERB michael@0: printf("Insufficient digits [%ld] on normal Inexact result.\n", michael@0: (LI)dn->digits); michael@0: uprv_decNumberShow(dn); michael@0: #endif michael@0: uprv_decContextSetStatus(set, DEC_Invalid_operation); michael@0: } michael@0: #else michael@0: /* next is a noop for quiet compiler */ michael@0: if (dn!=NULL && dn->digits==0) set->status|=DEC_Invalid_operation; michael@0: #endif michael@0: return; michael@0: } /* decCheckInexact */ michael@0: #endif michael@0: michael@0: #if DECALLOC michael@0: #undef malloc michael@0: #undef free michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decMalloc -- accountable allocation routine */ michael@0: /* n is the number of bytes to allocate */ michael@0: /* */ michael@0: /* Semantics is the same as the stdlib malloc routine, but bytes */ michael@0: /* allocated are accounted for globally, and corruption fences are */ michael@0: /* added before and after the 'actual' storage. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: /* This routine allocates storage with an extra twelve bytes; 8 are */ michael@0: /* at the start and hold: */ michael@0: /* 0-3 the original length requested */ michael@0: /* 4-7 buffer corruption detection fence (DECFENCE, x4) */ michael@0: /* The 4 bytes at the end also hold a corruption fence (DECFENCE, x4) */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static void *decMalloc(size_t n) { michael@0: uInt size=n+12; /* true size */ michael@0: void *alloc; /* -> allocated storage */ michael@0: uByte *b, *b0; /* work */ michael@0: uInt uiwork; /* for macros */ michael@0: michael@0: alloc=malloc(size); /* -> allocated storage */ michael@0: if (alloc==NULL) return NULL; /* out of strorage */ michael@0: b0=(uByte *)alloc; /* as bytes */ michael@0: decAllocBytes+=n; /* account for storage */ michael@0: UBFROMUI(alloc, n); /* save n */ michael@0: /* printf(" alloc ++ dAB: %ld (%ld)\n", (LI)decAllocBytes, (LI)n); */ michael@0: for (b=b0+4; b play area */ michael@0: } /* decMalloc */ michael@0: michael@0: /* ------------------------------------------------------------------ */ michael@0: /* decFree -- accountable free routine */ michael@0: /* alloc is the storage to free */ michael@0: /* */ michael@0: /* Semantics is the same as the stdlib malloc routine, except that */ michael@0: /* the global storage accounting is updated and the fences are */ michael@0: /* checked to ensure that no routine has written 'out of bounds'. */ michael@0: /* ------------------------------------------------------------------ */ michael@0: /* This routine first checks that the fences have not been corrupted. */ michael@0: /* It then frees the storage using the 'truw' storage address (that */ michael@0: /* is, offset by 8). */ michael@0: /* ------------------------------------------------------------------ */ michael@0: static void decFree(void *alloc) { michael@0: uInt n; /* original length */ michael@0: uByte *b, *b0; /* work */ michael@0: uInt uiwork; /* for macros */ michael@0: michael@0: if (alloc==NULL) return; /* allowed; it's a nop */ michael@0: b0=(uByte *)alloc; /* as bytes */ michael@0: b0-=8; /* -> true start of storage */ michael@0: n=UBTOUI(b0); /* lift length */ michael@0: for (b=b0+4; b