simple-squiggle

A restricted subset of Squiggle
Log | Files | Refs | README

decimal.js (135913B)


      1 ;(function (globalScope) {
      2   'use strict';
      3 
      4 
      5   /*
      6    *  decimal.js v10.3.1
      7    *  An arbitrary-precision Decimal type for JavaScript.
      8    *  https://github.com/MikeMcl/decimal.js
      9    *  Copyright (c) 2021 Michael Mclaughlin <M8ch88l@gmail.com>
     10    *  MIT Licence
     11    */
     12 
     13 
     14   // -----------------------------------  EDITABLE DEFAULTS  ------------------------------------ //
     15 
     16 
     17     // The maximum exponent magnitude.
     18     // The limit on the value of `toExpNeg`, `toExpPos`, `minE` and `maxE`.
     19   var EXP_LIMIT = 9e15,                      // 0 to 9e15
     20 
     21     // The limit on the value of `precision`, and on the value of the first argument to
     22     // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`.
     23     MAX_DIGITS = 1e9,                        // 0 to 1e9
     24 
     25     // Base conversion alphabet.
     26     NUMERALS = '0123456789abcdef',
     27 
     28     // The natural logarithm of 10 (1025 digits).
     29     LN10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058',
     30 
     31     // Pi (1025 digits).
     32     PI = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789',
     33 
     34 
     35     // The initial configuration properties of the Decimal constructor.
     36     DEFAULTS = {
     37 
     38       // These values must be integers within the stated ranges (inclusive).
     39       // Most of these values can be changed at run-time using the `Decimal.config` method.
     40 
     41       // The maximum number of significant digits of the result of a calculation or base conversion.
     42       // E.g. `Decimal.config({ precision: 20 });`
     43       precision: 20,                         // 1 to MAX_DIGITS
     44 
     45       // The rounding mode used when rounding to `precision`.
     46       //
     47       // ROUND_UP         0 Away from zero.
     48       // ROUND_DOWN       1 Towards zero.
     49       // ROUND_CEIL       2 Towards +Infinity.
     50       // ROUND_FLOOR      3 Towards -Infinity.
     51       // ROUND_HALF_UP    4 Towards nearest neighbour. If equidistant, up.
     52       // ROUND_HALF_DOWN  5 Towards nearest neighbour. If equidistant, down.
     53       // ROUND_HALF_EVEN  6 Towards nearest neighbour. If equidistant, towards even neighbour.
     54       // ROUND_HALF_CEIL  7 Towards nearest neighbour. If equidistant, towards +Infinity.
     55       // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
     56       //
     57       // E.g.
     58       // `Decimal.rounding = 4;`
     59       // `Decimal.rounding = Decimal.ROUND_HALF_UP;`
     60       rounding: 4,                           // 0 to 8
     61 
     62       // The modulo mode used when calculating the modulus: a mod n.
     63       // The quotient (q = a / n) is calculated according to the corresponding rounding mode.
     64       // The remainder (r) is calculated as: r = a - n * q.
     65       //
     66       // UP         0 The remainder is positive if the dividend is negative, else is negative.
     67       // DOWN       1 The remainder has the same sign as the dividend (JavaScript %).
     68       // FLOOR      3 The remainder has the same sign as the divisor (Python %).
     69       // HALF_EVEN  6 The IEEE 754 remainder function.
     70       // EUCLID     9 Euclidian division. q = sign(n) * floor(a / abs(n)). Always positive.
     71       //
     72       // Truncated division (1), floored division (3), the IEEE 754 remainder (6), and Euclidian
     73       // division (9) are commonly used for the modulus operation. The other rounding modes can also
     74       // be used, but they may not give useful results.
     75       modulo: 1,                             // 0 to 9
     76 
     77       // The exponent value at and beneath which `toString` returns exponential notation.
     78       // JavaScript numbers: -7
     79       toExpNeg: -7,                          // 0 to -EXP_LIMIT
     80 
     81       // The exponent value at and above which `toString` returns exponential notation.
     82       // JavaScript numbers: 21
     83       toExpPos:  21,                         // 0 to EXP_LIMIT
     84 
     85       // The minimum exponent value, beneath which underflow to zero occurs.
     86       // JavaScript numbers: -324  (5e-324)
     87       minE: -EXP_LIMIT,                      // -1 to -EXP_LIMIT
     88 
     89       // The maximum exponent value, above which overflow to Infinity occurs.
     90       // JavaScript numbers: 308  (1.7976931348623157e+308)
     91       maxE: EXP_LIMIT,                       // 1 to EXP_LIMIT
     92 
     93       // Whether to use cryptographically-secure random number generation, if available.
     94       crypto: false                          // true/false
     95     },
     96 
     97 
     98   // ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- //
     99 
    100 
    101     Decimal, inexact, noConflict, quadrant,
    102     external = true,
    103 
    104     decimalError = '[DecimalError] ',
    105     invalidArgument = decimalError + 'Invalid argument: ',
    106     precisionLimitExceeded = decimalError + 'Precision limit exceeded',
    107     cryptoUnavailable = decimalError + 'crypto unavailable',
    108     tag = '[object Decimal]',
    109 
    110     mathfloor = Math.floor,
    111     mathpow = Math.pow,
    112 
    113     isBinary = /^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,
    114     isHex = /^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,
    115     isOctal = /^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,
    116     isDecimal = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
    117 
    118     BASE = 1e7,
    119     LOG_BASE = 7,
    120     MAX_SAFE_INTEGER = 9007199254740991,
    121 
    122     LN10_PRECISION = LN10.length - 1,
    123     PI_PRECISION = PI.length - 1,
    124 
    125     // Decimal.prototype object
    126     P = { toStringTag: tag };
    127 
    128 
    129   // Decimal prototype methods
    130 
    131 
    132   /*
    133    *  absoluteValue             abs
    134    *  ceil
    135    *  clampedTo                 clamp
    136    *  comparedTo                cmp
    137    *  cosine                    cos
    138    *  cubeRoot                  cbrt
    139    *  decimalPlaces             dp
    140    *  dividedBy                 div
    141    *  dividedToIntegerBy        divToInt
    142    *  equals                    eq
    143    *  floor
    144    *  greaterThan               gt
    145    *  greaterThanOrEqualTo      gte
    146    *  hyperbolicCosine          cosh
    147    *  hyperbolicSine            sinh
    148    *  hyperbolicTangent         tanh
    149    *  inverseCosine             acos
    150    *  inverseHyperbolicCosine   acosh
    151    *  inverseHyperbolicSine     asinh
    152    *  inverseHyperbolicTangent  atanh
    153    *  inverseSine               asin
    154    *  inverseTangent            atan
    155    *  isFinite
    156    *  isInteger                 isInt
    157    *  isNaN
    158    *  isNegative                isNeg
    159    *  isPositive                isPos
    160    *  isZero
    161    *  lessThan                  lt
    162    *  lessThanOrEqualTo         lte
    163    *  logarithm                 log
    164    *  [maximum]                 [max]
    165    *  [minimum]                 [min]
    166    *  minus                     sub
    167    *  modulo                    mod
    168    *  naturalExponential        exp
    169    *  naturalLogarithm          ln
    170    *  negated                   neg
    171    *  plus                      add
    172    *  precision                 sd
    173    *  round
    174    *  sine                      sin
    175    *  squareRoot                sqrt
    176    *  tangent                   tan
    177    *  times                     mul
    178    *  toBinary
    179    *  toDecimalPlaces           toDP
    180    *  toExponential
    181    *  toFixed
    182    *  toFraction
    183    *  toHexadecimal             toHex
    184    *  toNearest
    185    *  toNumber
    186    *  toOctal
    187    *  toPower                   pow
    188    *  toPrecision
    189    *  toSignificantDigits       toSD
    190    *  toString
    191    *  truncated                 trunc
    192    *  valueOf                   toJSON
    193    */
    194 
    195 
    196   /*
    197    * Return a new Decimal whose value is the absolute value of this Decimal.
    198    *
    199    */
    200   P.absoluteValue = P.abs = function () {
    201     var x = new this.constructor(this);
    202     if (x.s < 0) x.s = 1;
    203     return finalise(x);
    204   };
    205 
    206 
    207   /*
    208    * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the
    209    * direction of positive Infinity.
    210    *
    211    */
    212   P.ceil = function () {
    213     return finalise(new this.constructor(this), this.e + 1, 2);
    214   };
    215 
    216 
    217   /*
    218    * Return a new Decimal whose value is the value of this Decimal clamped to the range
    219    * delineated by `min` and `max`.
    220    *
    221    * min {number|string|Decimal}
    222    * max {number|string|Decimal}
    223    *
    224    */
    225   P.clampedTo = P.clamp = function (min, max) {
    226     var k,
    227       x = this,
    228       Ctor = x.constructor;
    229     min = new Ctor(min);
    230     max = new Ctor(max);
    231     if (!min.s || !max.s) return new Ctor(NaN);
    232     if (min.gt(max)) throw Error(invalidArgument + max);
    233     k = x.cmp(min);
    234     return k < 0 ? min : x.cmp(max) > 0 ? max : new Ctor(x);
    235   };
    236 
    237 
    238   /*
    239    * Return
    240    *   1    if the value of this Decimal is greater than the value of `y`,
    241    *  -1    if the value of this Decimal is less than the value of `y`,
    242    *   0    if they have the same value,
    243    *   NaN  if the value of either Decimal is NaN.
    244    *
    245    */
    246   P.comparedTo = P.cmp = function (y) {
    247     var i, j, xdL, ydL,
    248       x = this,
    249       xd = x.d,
    250       yd = (y = new x.constructor(y)).d,
    251       xs = x.s,
    252       ys = y.s;
    253 
    254     // Either NaN or ±Infinity?
    255     if (!xd || !yd) {
    256       return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1;
    257     }
    258 
    259     // Either zero?
    260     if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0;
    261 
    262     // Signs differ?
    263     if (xs !== ys) return xs;
    264 
    265     // Compare exponents.
    266     if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1;
    267 
    268     xdL = xd.length;
    269     ydL = yd.length;
    270 
    271     // Compare digit by digit.
    272     for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) {
    273       if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1;
    274     }
    275 
    276     // Compare lengths.
    277     return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1;
    278   };
    279 
    280 
    281   /*
    282    * Return a new Decimal whose value is the cosine of the value in radians of this Decimal.
    283    *
    284    * Domain: [-Infinity, Infinity]
    285    * Range: [-1, 1]
    286    *
    287    * cos(0)         = 1
    288    * cos(-0)        = 1
    289    * cos(Infinity)  = NaN
    290    * cos(-Infinity) = NaN
    291    * cos(NaN)       = NaN
    292    *
    293    */
    294   P.cosine = P.cos = function () {
    295     var pr, rm,
    296       x = this,
    297       Ctor = x.constructor;
    298 
    299     if (!x.d) return new Ctor(NaN);
    300 
    301     // cos(0) = cos(-0) = 1
    302     if (!x.d[0]) return new Ctor(1);
    303 
    304     pr = Ctor.precision;
    305     rm = Ctor.rounding;
    306     Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;
    307     Ctor.rounding = 1;
    308 
    309     x = cosine(Ctor, toLessThanHalfPi(Ctor, x));
    310 
    311     Ctor.precision = pr;
    312     Ctor.rounding = rm;
    313 
    314     return finalise(quadrant == 2 || quadrant == 3 ? x.neg() : x, pr, rm, true);
    315   };
    316 
    317 
    318   /*
    319    *
    320    * Return a new Decimal whose value is the cube root of the value of this Decimal, rounded to
    321    * `precision` significant digits using rounding mode `rounding`.
    322    *
    323    *  cbrt(0)  =  0
    324    *  cbrt(-0) = -0
    325    *  cbrt(1)  =  1
    326    *  cbrt(-1) = -1
    327    *  cbrt(N)  =  N
    328    *  cbrt(-I) = -I
    329    *  cbrt(I)  =  I
    330    *
    331    * Math.cbrt(x) = (x < 0 ? -Math.pow(-x, 1/3) : Math.pow(x, 1/3))
    332    *
    333    */
    334   P.cubeRoot = P.cbrt = function () {
    335     var e, m, n, r, rep, s, sd, t, t3, t3plusx,
    336       x = this,
    337       Ctor = x.constructor;
    338 
    339     if (!x.isFinite() || x.isZero()) return new Ctor(x);
    340     external = false;
    341 
    342     // Initial estimate.
    343     s = x.s * mathpow(x.s * x, 1 / 3);
    344 
    345      // Math.cbrt underflow/overflow?
    346      // Pass x to Math.pow as integer, then adjust the exponent of the result.
    347     if (!s || Math.abs(s) == 1 / 0) {
    348       n = digitsToString(x.d);
    349       e = x.e;
    350 
    351       // Adjust n exponent so it is a multiple of 3 away from x exponent.
    352       if (s = (e - n.length + 1) % 3) n += (s == 1 || s == -2 ? '0' : '00');
    353       s = mathpow(n, 1 / 3);
    354 
    355       // Rarely, e may be one less than the result exponent value.
    356       e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2));
    357 
    358       if (s == 1 / 0) {
    359         n = '5e' + e;
    360       } else {
    361         n = s.toExponential();
    362         n = n.slice(0, n.indexOf('e') + 1) + e;
    363       }
    364 
    365       r = new Ctor(n);
    366       r.s = x.s;
    367     } else {
    368       r = new Ctor(s.toString());
    369     }
    370 
    371     sd = (e = Ctor.precision) + 3;
    372 
    373     // Halley's method.
    374     // TODO? Compare Newton's method.
    375     for (;;) {
    376       t = r;
    377       t3 = t.times(t).times(t);
    378       t3plusx = t3.plus(x);
    379       r = divide(t3plusx.plus(x).times(t), t3plusx.plus(t3), sd + 2, 1);
    380 
    381       // TODO? Replace with for-loop and checkRoundingDigits.
    382       if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {
    383         n = n.slice(sd - 3, sd + 1);
    384 
    385         // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or 4999
    386         // , i.e. approaching a rounding boundary, continue the iteration.
    387         if (n == '9999' || !rep && n == '4999') {
    388 
    389           // On the first iteration only, check to see if rounding up gives the exact result as the
    390           // nines may infinitely repeat.
    391           if (!rep) {
    392             finalise(t, e + 1, 0);
    393 
    394             if (t.times(t).times(t).eq(x)) {
    395               r = t;
    396               break;
    397             }
    398           }
    399 
    400           sd += 4;
    401           rep = 1;
    402         } else {
    403 
    404           // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.
    405           // If not, then there are further digits and m will be truthy.
    406           if (!+n || !+n.slice(1) && n.charAt(0) == '5') {
    407 
    408             // Truncate to the first rounding digit.
    409             finalise(r, e + 1, 1);
    410             m = !r.times(r).times(r).eq(x);
    411           }
    412 
    413           break;
    414         }
    415       }
    416     }
    417 
    418     external = true;
    419 
    420     return finalise(r, e, Ctor.rounding, m);
    421   };
    422 
    423 
    424   /*
    425    * Return the number of decimal places of the value of this Decimal.
    426    *
    427    */
    428   P.decimalPlaces = P.dp = function () {
    429     var w,
    430       d = this.d,
    431       n = NaN;
    432 
    433     if (d) {
    434       w = d.length - 1;
    435       n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE;
    436 
    437       // Subtract the number of trailing zeros of the last word.
    438       w = d[w];
    439       if (w) for (; w % 10 == 0; w /= 10) n--;
    440       if (n < 0) n = 0;
    441     }
    442 
    443     return n;
    444   };
    445 
    446 
    447   /*
    448    *  n / 0 = I
    449    *  n / N = N
    450    *  n / I = 0
    451    *  0 / n = 0
    452    *  0 / 0 = N
    453    *  0 / N = N
    454    *  0 / I = 0
    455    *  N / n = N
    456    *  N / 0 = N
    457    *  N / N = N
    458    *  N / I = N
    459    *  I / n = I
    460    *  I / 0 = I
    461    *  I / N = N
    462    *  I / I = N
    463    *
    464    * Return a new Decimal whose value is the value of this Decimal divided by `y`, rounded to
    465    * `precision` significant digits using rounding mode `rounding`.
    466    *
    467    */
    468   P.dividedBy = P.div = function (y) {
    469     return divide(this, new this.constructor(y));
    470   };
    471 
    472 
    473   /*
    474    * Return a new Decimal whose value is the integer part of dividing the value of this Decimal
    475    * by the value of `y`, rounded to `precision` significant digits using rounding mode `rounding`.
    476    *
    477    */
    478   P.dividedToIntegerBy = P.divToInt = function (y) {
    479     var x = this,
    480       Ctor = x.constructor;
    481     return finalise(divide(x, new Ctor(y), 0, 1, 1), Ctor.precision, Ctor.rounding);
    482   };
    483 
    484 
    485   /*
    486    * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false.
    487    *
    488    */
    489   P.equals = P.eq = function (y) {
    490     return this.cmp(y) === 0;
    491   };
    492 
    493 
    494   /*
    495    * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the
    496    * direction of negative Infinity.
    497    *
    498    */
    499   P.floor = function () {
    500     return finalise(new this.constructor(this), this.e + 1, 3);
    501   };
    502 
    503 
    504   /*
    505    * Return true if the value of this Decimal is greater than the value of `y`, otherwise return
    506    * false.
    507    *
    508    */
    509   P.greaterThan = P.gt = function (y) {
    510     return this.cmp(y) > 0;
    511   };
    512 
    513 
    514   /*
    515    * Return true if the value of this Decimal is greater than or equal to the value of `y`,
    516    * otherwise return false.
    517    *
    518    */
    519   P.greaterThanOrEqualTo = P.gte = function (y) {
    520     var k = this.cmp(y);
    521     return k == 1 || k === 0;
    522   };
    523 
    524 
    525   /*
    526    * Return a new Decimal whose value is the hyperbolic cosine of the value in radians of this
    527    * Decimal.
    528    *
    529    * Domain: [-Infinity, Infinity]
    530    * Range: [1, Infinity]
    531    *
    532    * cosh(x) = 1 + x^2/2! + x^4/4! + x^6/6! + ...
    533    *
    534    * cosh(0)         = 1
    535    * cosh(-0)        = 1
    536    * cosh(Infinity)  = Infinity
    537    * cosh(-Infinity) = Infinity
    538    * cosh(NaN)       = NaN
    539    *
    540    *  x        time taken (ms)   result
    541    * 1000      9                 9.8503555700852349694e+433
    542    * 10000     25                4.4034091128314607936e+4342
    543    * 100000    171               1.4033316802130615897e+43429
    544    * 1000000   3817              1.5166076984010437725e+434294
    545    * 10000000  abandoned after 2 minute wait
    546    *
    547    * TODO? Compare performance of cosh(x) = 0.5 * (exp(x) + exp(-x))
    548    *
    549    */
    550   P.hyperbolicCosine = P.cosh = function () {
    551     var k, n, pr, rm, len,
    552       x = this,
    553       Ctor = x.constructor,
    554       one = new Ctor(1);
    555 
    556     if (!x.isFinite()) return new Ctor(x.s ? 1 / 0 : NaN);
    557     if (x.isZero()) return one;
    558 
    559     pr = Ctor.precision;
    560     rm = Ctor.rounding;
    561     Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;
    562     Ctor.rounding = 1;
    563     len = x.d.length;
    564 
    565     // Argument reduction: cos(4x) = 1 - 8cos^2(x) + 8cos^4(x) + 1
    566     // i.e. cos(x) = 1 - cos^2(x/4)(8 - 8cos^2(x/4))
    567 
    568     // Estimate the optimum number of times to use the argument reduction.
    569     // TODO? Estimation reused from cosine() and may not be optimal here.
    570     if (len < 32) {
    571       k = Math.ceil(len / 3);
    572       n = (1 / tinyPow(4, k)).toString();
    573     } else {
    574       k = 16;
    575       n = '2.3283064365386962890625e-10';
    576     }
    577 
    578     x = taylorSeries(Ctor, 1, x.times(n), new Ctor(1), true);
    579 
    580     // Reverse argument reduction
    581     var cosh2_x,
    582       i = k,
    583       d8 = new Ctor(8);
    584     for (; i--;) {
    585       cosh2_x = x.times(x);
    586       x = one.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8))));
    587     }
    588 
    589     return finalise(x, Ctor.precision = pr, Ctor.rounding = rm, true);
    590   };
    591 
    592 
    593   /*
    594    * Return a new Decimal whose value is the hyperbolic sine of the value in radians of this
    595    * Decimal.
    596    *
    597    * Domain: [-Infinity, Infinity]
    598    * Range: [-Infinity, Infinity]
    599    *
    600    * sinh(x) = x + x^3/3! + x^5/5! + x^7/7! + ...
    601    *
    602    * sinh(0)         = 0
    603    * sinh(-0)        = -0
    604    * sinh(Infinity)  = Infinity
    605    * sinh(-Infinity) = -Infinity
    606    * sinh(NaN)       = NaN
    607    *
    608    * x        time taken (ms)
    609    * 10       2 ms
    610    * 100      5 ms
    611    * 1000     14 ms
    612    * 10000    82 ms
    613    * 100000   886 ms            1.4033316802130615897e+43429
    614    * 200000   2613 ms
    615    * 300000   5407 ms
    616    * 400000   8824 ms
    617    * 500000   13026 ms          8.7080643612718084129e+217146
    618    * 1000000  48543 ms
    619    *
    620    * TODO? Compare performance of sinh(x) = 0.5 * (exp(x) - exp(-x))
    621    *
    622    */
    623   P.hyperbolicSine = P.sinh = function () {
    624     var k, pr, rm, len,
    625       x = this,
    626       Ctor = x.constructor;
    627 
    628     if (!x.isFinite() || x.isZero()) return new Ctor(x);
    629 
    630     pr = Ctor.precision;
    631     rm = Ctor.rounding;
    632     Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;
    633     Ctor.rounding = 1;
    634     len = x.d.length;
    635 
    636     if (len < 3) {
    637       x = taylorSeries(Ctor, 2, x, x, true);
    638     } else {
    639 
    640       // Alternative argument reduction: sinh(3x) = sinh(x)(3 + 4sinh^2(x))
    641       // i.e. sinh(x) = sinh(x/3)(3 + 4sinh^2(x/3))
    642       // 3 multiplications and 1 addition
    643 
    644       // Argument reduction: sinh(5x) = sinh(x)(5 + sinh^2(x)(20 + 16sinh^2(x)))
    645       // i.e. sinh(x) = sinh(x/5)(5 + sinh^2(x/5)(20 + 16sinh^2(x/5)))
    646       // 4 multiplications and 2 additions
    647 
    648       // Estimate the optimum number of times to use the argument reduction.
    649       k = 1.4 * Math.sqrt(len);
    650       k = k > 16 ? 16 : k | 0;
    651 
    652       x = x.times(1 / tinyPow(5, k));
    653       x = taylorSeries(Ctor, 2, x, x, true);
    654 
    655       // Reverse argument reduction
    656       var sinh2_x,
    657         d5 = new Ctor(5),
    658         d16 = new Ctor(16),
    659         d20 = new Ctor(20);
    660       for (; k--;) {
    661         sinh2_x = x.times(x);
    662         x = x.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20))));
    663       }
    664     }
    665 
    666     Ctor.precision = pr;
    667     Ctor.rounding = rm;
    668 
    669     return finalise(x, pr, rm, true);
    670   };
    671 
    672 
    673   /*
    674    * Return a new Decimal whose value is the hyperbolic tangent of the value in radians of this
    675    * Decimal.
    676    *
    677    * Domain: [-Infinity, Infinity]
    678    * Range: [-1, 1]
    679    *
    680    * tanh(x) = sinh(x) / cosh(x)
    681    *
    682    * tanh(0)         = 0
    683    * tanh(-0)        = -0
    684    * tanh(Infinity)  = 1
    685    * tanh(-Infinity) = -1
    686    * tanh(NaN)       = NaN
    687    *
    688    */
    689   P.hyperbolicTangent = P.tanh = function () {
    690     var pr, rm,
    691       x = this,
    692       Ctor = x.constructor;
    693 
    694     if (!x.isFinite()) return new Ctor(x.s);
    695     if (x.isZero()) return new Ctor(x);
    696 
    697     pr = Ctor.precision;
    698     rm = Ctor.rounding;
    699     Ctor.precision = pr + 7;
    700     Ctor.rounding = 1;
    701 
    702     return divide(x.sinh(), x.cosh(), Ctor.precision = pr, Ctor.rounding = rm);
    703   };
    704 
    705 
    706   /*
    707    * Return a new Decimal whose value is the arccosine (inverse cosine) in radians of the value of
    708    * this Decimal.
    709    *
    710    * Domain: [-1, 1]
    711    * Range: [0, pi]
    712    *
    713    * acos(x) = pi/2 - asin(x)
    714    *
    715    * acos(0)       = pi/2
    716    * acos(-0)      = pi/2
    717    * acos(1)       = 0
    718    * acos(-1)      = pi
    719    * acos(1/2)     = pi/3
    720    * acos(-1/2)    = 2*pi/3
    721    * acos(|x| > 1) = NaN
    722    * acos(NaN)     = NaN
    723    *
    724    */
    725   P.inverseCosine = P.acos = function () {
    726     var halfPi,
    727       x = this,
    728       Ctor = x.constructor,
    729       k = x.abs().cmp(1),
    730       pr = Ctor.precision,
    731       rm = Ctor.rounding;
    732 
    733     if (k !== -1) {
    734       return k === 0
    735         // |x| is 1
    736         ? x.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0)
    737         // |x| > 1 or x is NaN
    738         : new Ctor(NaN);
    739     }
    740 
    741     if (x.isZero()) return getPi(Ctor, pr + 4, rm).times(0.5);
    742 
    743     // TODO? Special case acos(0.5) = pi/3 and acos(-0.5) = 2*pi/3
    744 
    745     Ctor.precision = pr + 6;
    746     Ctor.rounding = 1;
    747 
    748     x = x.asin();
    749     halfPi = getPi(Ctor, pr + 4, rm).times(0.5);
    750 
    751     Ctor.precision = pr;
    752     Ctor.rounding = rm;
    753 
    754     return halfPi.minus(x);
    755   };
    756 
    757 
    758   /*
    759    * Return a new Decimal whose value is the inverse of the hyperbolic cosine in radians of the
    760    * value of this Decimal.
    761    *
    762    * Domain: [1, Infinity]
    763    * Range: [0, Infinity]
    764    *
    765    * acosh(x) = ln(x + sqrt(x^2 - 1))
    766    *
    767    * acosh(x < 1)     = NaN
    768    * acosh(NaN)       = NaN
    769    * acosh(Infinity)  = Infinity
    770    * acosh(-Infinity) = NaN
    771    * acosh(0)         = NaN
    772    * acosh(-0)        = NaN
    773    * acosh(1)         = 0
    774    * acosh(-1)        = NaN
    775    *
    776    */
    777   P.inverseHyperbolicCosine = P.acosh = function () {
    778     var pr, rm,
    779       x = this,
    780       Ctor = x.constructor;
    781 
    782     if (x.lte(1)) return new Ctor(x.eq(1) ? 0 : NaN);
    783     if (!x.isFinite()) return new Ctor(x);
    784 
    785     pr = Ctor.precision;
    786     rm = Ctor.rounding;
    787     Ctor.precision = pr + Math.max(Math.abs(x.e), x.sd()) + 4;
    788     Ctor.rounding = 1;
    789     external = false;
    790 
    791     x = x.times(x).minus(1).sqrt().plus(x);
    792 
    793     external = true;
    794     Ctor.precision = pr;
    795     Ctor.rounding = rm;
    796 
    797     return x.ln();
    798   };
    799 
    800 
    801   /*
    802    * Return a new Decimal whose value is the inverse of the hyperbolic sine in radians of the value
    803    * of this Decimal.
    804    *
    805    * Domain: [-Infinity, Infinity]
    806    * Range: [-Infinity, Infinity]
    807    *
    808    * asinh(x) = ln(x + sqrt(x^2 + 1))
    809    *
    810    * asinh(NaN)       = NaN
    811    * asinh(Infinity)  = Infinity
    812    * asinh(-Infinity) = -Infinity
    813    * asinh(0)         = 0
    814    * asinh(-0)        = -0
    815    *
    816    */
    817   P.inverseHyperbolicSine = P.asinh = function () {
    818     var pr, rm,
    819       x = this,
    820       Ctor = x.constructor;
    821 
    822     if (!x.isFinite() || x.isZero()) return new Ctor(x);
    823 
    824     pr = Ctor.precision;
    825     rm = Ctor.rounding;
    826     Ctor.precision = pr + 2 * Math.max(Math.abs(x.e), x.sd()) + 6;
    827     Ctor.rounding = 1;
    828     external = false;
    829 
    830     x = x.times(x).plus(1).sqrt().plus(x);
    831 
    832     external = true;
    833     Ctor.precision = pr;
    834     Ctor.rounding = rm;
    835 
    836     return x.ln();
    837   };
    838 
    839 
    840   /*
    841    * Return a new Decimal whose value is the inverse of the hyperbolic tangent in radians of the
    842    * value of this Decimal.
    843    *
    844    * Domain: [-1, 1]
    845    * Range: [-Infinity, Infinity]
    846    *
    847    * atanh(x) = 0.5 * ln((1 + x) / (1 - x))
    848    *
    849    * atanh(|x| > 1)   = NaN
    850    * atanh(NaN)       = NaN
    851    * atanh(Infinity)  = NaN
    852    * atanh(-Infinity) = NaN
    853    * atanh(0)         = 0
    854    * atanh(-0)        = -0
    855    * atanh(1)         = Infinity
    856    * atanh(-1)        = -Infinity
    857    *
    858    */
    859   P.inverseHyperbolicTangent = P.atanh = function () {
    860     var pr, rm, wpr, xsd,
    861       x = this,
    862       Ctor = x.constructor;
    863 
    864     if (!x.isFinite()) return new Ctor(NaN);
    865     if (x.e >= 0) return new Ctor(x.abs().eq(1) ? x.s / 0 : x.isZero() ? x : NaN);
    866 
    867     pr = Ctor.precision;
    868     rm = Ctor.rounding;
    869     xsd = x.sd();
    870 
    871     if (Math.max(xsd, pr) < 2 * -x.e - 1) return finalise(new Ctor(x), pr, rm, true);
    872 
    873     Ctor.precision = wpr = xsd - x.e;
    874 
    875     x = divide(x.plus(1), new Ctor(1).minus(x), wpr + pr, 1);
    876 
    877     Ctor.precision = pr + 4;
    878     Ctor.rounding = 1;
    879 
    880     x = x.ln();
    881 
    882     Ctor.precision = pr;
    883     Ctor.rounding = rm;
    884 
    885     return x.times(0.5);
    886   };
    887 
    888 
    889   /*
    890    * Return a new Decimal whose value is the arcsine (inverse sine) in radians of the value of this
    891    * Decimal.
    892    *
    893    * Domain: [-Infinity, Infinity]
    894    * Range: [-pi/2, pi/2]
    895    *
    896    * asin(x) = 2*atan(x/(1 + sqrt(1 - x^2)))
    897    *
    898    * asin(0)       = 0
    899    * asin(-0)      = -0
    900    * asin(1/2)     = pi/6
    901    * asin(-1/2)    = -pi/6
    902    * asin(1)       = pi/2
    903    * asin(-1)      = -pi/2
    904    * asin(|x| > 1) = NaN
    905    * asin(NaN)     = NaN
    906    *
    907    * TODO? Compare performance of Taylor series.
    908    *
    909    */
    910   P.inverseSine = P.asin = function () {
    911     var halfPi, k,
    912       pr, rm,
    913       x = this,
    914       Ctor = x.constructor;
    915 
    916     if (x.isZero()) return new Ctor(x);
    917 
    918     k = x.abs().cmp(1);
    919     pr = Ctor.precision;
    920     rm = Ctor.rounding;
    921 
    922     if (k !== -1) {
    923 
    924       // |x| is 1
    925       if (k === 0) {
    926         halfPi = getPi(Ctor, pr + 4, rm).times(0.5);
    927         halfPi.s = x.s;
    928         return halfPi;
    929       }
    930 
    931       // |x| > 1 or x is NaN
    932       return new Ctor(NaN);
    933     }
    934 
    935     // TODO? Special case asin(1/2) = pi/6 and asin(-1/2) = -pi/6
    936 
    937     Ctor.precision = pr + 6;
    938     Ctor.rounding = 1;
    939 
    940     x = x.div(new Ctor(1).minus(x.times(x)).sqrt().plus(1)).atan();
    941 
    942     Ctor.precision = pr;
    943     Ctor.rounding = rm;
    944 
    945     return x.times(2);
    946   };
    947 
    948 
    949   /*
    950    * Return a new Decimal whose value is the arctangent (inverse tangent) in radians of the value
    951    * of this Decimal.
    952    *
    953    * Domain: [-Infinity, Infinity]
    954    * Range: [-pi/2, pi/2]
    955    *
    956    * atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...
    957    *
    958    * atan(0)         = 0
    959    * atan(-0)        = -0
    960    * atan(1)         = pi/4
    961    * atan(-1)        = -pi/4
    962    * atan(Infinity)  = pi/2
    963    * atan(-Infinity) = -pi/2
    964    * atan(NaN)       = NaN
    965    *
    966    */
    967   P.inverseTangent = P.atan = function () {
    968     var i, j, k, n, px, t, r, wpr, x2,
    969       x = this,
    970       Ctor = x.constructor,
    971       pr = Ctor.precision,
    972       rm = Ctor.rounding;
    973 
    974     if (!x.isFinite()) {
    975       if (!x.s) return new Ctor(NaN);
    976       if (pr + 4 <= PI_PRECISION) {
    977         r = getPi(Ctor, pr + 4, rm).times(0.5);
    978         r.s = x.s;
    979         return r;
    980       }
    981     } else if (x.isZero()) {
    982       return new Ctor(x);
    983     } else if (x.abs().eq(1) && pr + 4 <= PI_PRECISION) {
    984       r = getPi(Ctor, pr + 4, rm).times(0.25);
    985       r.s = x.s;
    986       return r;
    987     }
    988 
    989     Ctor.precision = wpr = pr + 10;
    990     Ctor.rounding = 1;
    991 
    992     // TODO? if (x >= 1 && pr <= PI_PRECISION) atan(x) = halfPi * x.s - atan(1 / x);
    993 
    994     // Argument reduction
    995     // Ensure |x| < 0.42
    996     // atan(x) = 2 * atan(x / (1 + sqrt(1 + x^2)))
    997 
    998     k = Math.min(28, wpr / LOG_BASE + 2 | 0);
    999 
   1000     for (i = k; i; --i) x = x.div(x.times(x).plus(1).sqrt().plus(1));
   1001 
   1002     external = false;
   1003 
   1004     j = Math.ceil(wpr / LOG_BASE);
   1005     n = 1;
   1006     x2 = x.times(x);
   1007     r = new Ctor(x);
   1008     px = x;
   1009 
   1010     // atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...
   1011     for (; i !== -1;) {
   1012       px = px.times(x2);
   1013       t = r.minus(px.div(n += 2));
   1014 
   1015       px = px.times(x2);
   1016       r = t.plus(px.div(n += 2));
   1017 
   1018       if (r.d[j] !== void 0) for (i = j; r.d[i] === t.d[i] && i--;);
   1019     }
   1020 
   1021     if (k) r = r.times(2 << (k - 1));
   1022 
   1023     external = true;
   1024 
   1025     return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true);
   1026   };
   1027 
   1028 
   1029   /*
   1030    * Return true if the value of this Decimal is a finite number, otherwise return false.
   1031    *
   1032    */
   1033   P.isFinite = function () {
   1034     return !!this.d;
   1035   };
   1036 
   1037 
   1038   /*
   1039    * Return true if the value of this Decimal is an integer, otherwise return false.
   1040    *
   1041    */
   1042   P.isInteger = P.isInt = function () {
   1043     return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2;
   1044   };
   1045 
   1046 
   1047   /*
   1048    * Return true if the value of this Decimal is NaN, otherwise return false.
   1049    *
   1050    */
   1051   P.isNaN = function () {
   1052     return !this.s;
   1053   };
   1054 
   1055 
   1056   /*
   1057    * Return true if the value of this Decimal is negative, otherwise return false.
   1058    *
   1059    */
   1060   P.isNegative = P.isNeg = function () {
   1061     return this.s < 0;
   1062   };
   1063 
   1064 
   1065   /*
   1066    * Return true if the value of this Decimal is positive, otherwise return false.
   1067    *
   1068    */
   1069   P.isPositive = P.isPos = function () {
   1070     return this.s > 0;
   1071   };
   1072 
   1073 
   1074   /*
   1075    * Return true if the value of this Decimal is 0 or -0, otherwise return false.
   1076    *
   1077    */
   1078   P.isZero = function () {
   1079     return !!this.d && this.d[0] === 0;
   1080   };
   1081 
   1082 
   1083   /*
   1084    * Return true if the value of this Decimal is less than `y`, otherwise return false.
   1085    *
   1086    */
   1087   P.lessThan = P.lt = function (y) {
   1088     return this.cmp(y) < 0;
   1089   };
   1090 
   1091 
   1092   /*
   1093    * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false.
   1094    *
   1095    */
   1096   P.lessThanOrEqualTo = P.lte = function (y) {
   1097     return this.cmp(y) < 1;
   1098   };
   1099 
   1100 
   1101   /*
   1102    * Return the logarithm of the value of this Decimal to the specified base, rounded to `precision`
   1103    * significant digits using rounding mode `rounding`.
   1104    *
   1105    * If no base is specified, return log[10](arg).
   1106    *
   1107    * log[base](arg) = ln(arg) / ln(base)
   1108    *
   1109    * The result will always be correctly rounded if the base of the log is 10, and 'almost always'
   1110    * otherwise:
   1111    *
   1112    * Depending on the rounding mode, the result may be incorrectly rounded if the first fifteen
   1113    * rounding digits are [49]99999999999999 or [50]00000000000000. In that case, the maximum error
   1114    * between the result and the correctly rounded result will be one ulp (unit in the last place).
   1115    *
   1116    * log[-b](a)       = NaN
   1117    * log[0](a)        = NaN
   1118    * log[1](a)        = NaN
   1119    * log[NaN](a)      = NaN
   1120    * log[Infinity](a) = NaN
   1121    * log[b](0)        = -Infinity
   1122    * log[b](-0)       = -Infinity
   1123    * log[b](-a)       = NaN
   1124    * log[b](1)        = 0
   1125    * log[b](Infinity) = Infinity
   1126    * log[b](NaN)      = NaN
   1127    *
   1128    * [base] {number|string|Decimal} The base of the logarithm.
   1129    *
   1130    */
   1131   P.logarithm = P.log = function (base) {
   1132     var isBase10, d, denominator, k, inf, num, sd, r,
   1133       arg = this,
   1134       Ctor = arg.constructor,
   1135       pr = Ctor.precision,
   1136       rm = Ctor.rounding,
   1137       guard = 5;
   1138 
   1139     // Default base is 10.
   1140     if (base == null) {
   1141       base = new Ctor(10);
   1142       isBase10 = true;
   1143     } else {
   1144       base = new Ctor(base);
   1145       d = base.d;
   1146 
   1147       // Return NaN if base is negative, or non-finite, or is 0 or 1.
   1148       if (base.s < 0 || !d || !d[0] || base.eq(1)) return new Ctor(NaN);
   1149 
   1150       isBase10 = base.eq(10);
   1151     }
   1152 
   1153     d = arg.d;
   1154 
   1155     // Is arg negative, non-finite, 0 or 1?
   1156     if (arg.s < 0 || !d || !d[0] || arg.eq(1)) {
   1157       return new Ctor(d && !d[0] ? -1 / 0 : arg.s != 1 ? NaN : d ? 0 : 1 / 0);
   1158     }
   1159 
   1160     // The result will have a non-terminating decimal expansion if base is 10 and arg is not an
   1161     // integer power of 10.
   1162     if (isBase10) {
   1163       if (d.length > 1) {
   1164         inf = true;
   1165       } else {
   1166         for (k = d[0]; k % 10 === 0;) k /= 10;
   1167         inf = k !== 1;
   1168       }
   1169     }
   1170 
   1171     external = false;
   1172     sd = pr + guard;
   1173     num = naturalLogarithm(arg, sd);
   1174     denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);
   1175 
   1176     // The result will have 5 rounding digits.
   1177     r = divide(num, denominator, sd, 1);
   1178 
   1179     // If at a rounding boundary, i.e. the result's rounding digits are [49]9999 or [50]0000,
   1180     // calculate 10 further digits.
   1181     //
   1182     // If the result is known to have an infinite decimal expansion, repeat this until it is clear
   1183     // that the result is above or below the boundary. Otherwise, if after calculating the 10
   1184     // further digits, the last 14 are nines, round up and assume the result is exact.
   1185     // Also assume the result is exact if the last 14 are zero.
   1186     //
   1187     // Example of a result that will be incorrectly rounded:
   1188     // log[1048576](4503599627370502) = 2.60000000000000009610279511444746...
   1189     // The above result correctly rounded using ROUND_CEIL to 1 decimal place should be 2.7, but it
   1190     // will be given as 2.6 as there are 15 zeros immediately after the requested decimal place, so
   1191     // the exact result would be assumed to be 2.6, which rounded using ROUND_CEIL to 1 decimal
   1192     // place is still 2.6.
   1193     if (checkRoundingDigits(r.d, k = pr, rm)) {
   1194 
   1195       do {
   1196         sd += 10;
   1197         num = naturalLogarithm(arg, sd);
   1198         denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);
   1199         r = divide(num, denominator, sd, 1);
   1200 
   1201         if (!inf) {
   1202 
   1203           // Check for 14 nines from the 2nd rounding digit, as the first may be 4.
   1204           if (+digitsToString(r.d).slice(k + 1, k + 15) + 1 == 1e14) {
   1205             r = finalise(r, pr + 1, 0);
   1206           }
   1207 
   1208           break;
   1209         }
   1210       } while (checkRoundingDigits(r.d, k += 10, rm));
   1211     }
   1212 
   1213     external = true;
   1214 
   1215     return finalise(r, pr, rm);
   1216   };
   1217 
   1218 
   1219   /*
   1220    * Return a new Decimal whose value is the maximum of the arguments and the value of this Decimal.
   1221    *
   1222    * arguments {number|string|Decimal}
   1223    *
   1224   P.max = function () {
   1225     Array.prototype.push.call(arguments, this);
   1226     return maxOrMin(this.constructor, arguments, 'lt');
   1227   };
   1228    */
   1229 
   1230 
   1231   /*
   1232    * Return a new Decimal whose value is the minimum of the arguments and the value of this Decimal.
   1233    *
   1234    * arguments {number|string|Decimal}
   1235    *
   1236   P.min = function () {
   1237     Array.prototype.push.call(arguments, this);
   1238     return maxOrMin(this.constructor, arguments, 'gt');
   1239   };
   1240    */
   1241 
   1242 
   1243   /*
   1244    *  n - 0 = n
   1245    *  n - N = N
   1246    *  n - I = -I
   1247    *  0 - n = -n
   1248    *  0 - 0 = 0
   1249    *  0 - N = N
   1250    *  0 - I = -I
   1251    *  N - n = N
   1252    *  N - 0 = N
   1253    *  N - N = N
   1254    *  N - I = N
   1255    *  I - n = I
   1256    *  I - 0 = I
   1257    *  I - N = N
   1258    *  I - I = N
   1259    *
   1260    * Return a new Decimal whose value is the value of this Decimal minus `y`, rounded to `precision`
   1261    * significant digits using rounding mode `rounding`.
   1262    *
   1263    */
   1264   P.minus = P.sub = function (y) {
   1265     var d, e, i, j, k, len, pr, rm, xd, xe, xLTy, yd,
   1266       x = this,
   1267       Ctor = x.constructor;
   1268 
   1269     y = new Ctor(y);
   1270 
   1271     // If either is not finite...
   1272     if (!x.d || !y.d) {
   1273 
   1274       // Return NaN if either is NaN.
   1275       if (!x.s || !y.s) y = new Ctor(NaN);
   1276 
   1277       // Return y negated if x is finite and y is ±Infinity.
   1278       else if (x.d) y.s = -y.s;
   1279 
   1280       // Return x if y is finite and x is ±Infinity.
   1281       // Return x if both are ±Infinity with different signs.
   1282       // Return NaN if both are ±Infinity with the same sign.
   1283       else y = new Ctor(y.d || x.s !== y.s ? x : NaN);
   1284 
   1285       return y;
   1286     }
   1287 
   1288     // If signs differ...
   1289     if (x.s != y.s) {
   1290       y.s = -y.s;
   1291       return x.plus(y);
   1292     }
   1293 
   1294     xd = x.d;
   1295     yd = y.d;
   1296     pr = Ctor.precision;
   1297     rm = Ctor.rounding;
   1298 
   1299     // If either is zero...
   1300     if (!xd[0] || !yd[0]) {
   1301 
   1302       // Return y negated if x is zero and y is non-zero.
   1303       if (yd[0]) y.s = -y.s;
   1304 
   1305       // Return x if y is zero and x is non-zero.
   1306       else if (xd[0]) y = new Ctor(x);
   1307 
   1308       // Return zero if both are zero.
   1309       // From IEEE 754 (2008) 6.3: 0 - 0 = -0 - -0 = -0 when rounding to -Infinity.
   1310       else return new Ctor(rm === 3 ? -0 : 0);
   1311 
   1312       return external ? finalise(y, pr, rm) : y;
   1313     }
   1314 
   1315     // x and y are finite, non-zero numbers with the same sign.
   1316 
   1317     // Calculate base 1e7 exponents.
   1318     e = mathfloor(y.e / LOG_BASE);
   1319     xe = mathfloor(x.e / LOG_BASE);
   1320 
   1321     xd = xd.slice();
   1322     k = xe - e;
   1323 
   1324     // If base 1e7 exponents differ...
   1325     if (k) {
   1326       xLTy = k < 0;
   1327 
   1328       if (xLTy) {
   1329         d = xd;
   1330         k = -k;
   1331         len = yd.length;
   1332       } else {
   1333         d = yd;
   1334         e = xe;
   1335         len = xd.length;
   1336       }
   1337 
   1338       // Numbers with massively different exponents would result in a very high number of
   1339       // zeros needing to be prepended, but this can be avoided while still ensuring correct
   1340       // rounding by limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`.
   1341       i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2;
   1342 
   1343       if (k > i) {
   1344         k = i;
   1345         d.length = 1;
   1346       }
   1347 
   1348       // Prepend zeros to equalise exponents.
   1349       d.reverse();
   1350       for (i = k; i--;) d.push(0);
   1351       d.reverse();
   1352 
   1353     // Base 1e7 exponents equal.
   1354     } else {
   1355 
   1356       // Check digits to determine which is the bigger number.
   1357 
   1358       i = xd.length;
   1359       len = yd.length;
   1360       xLTy = i < len;
   1361       if (xLTy) len = i;
   1362 
   1363       for (i = 0; i < len; i++) {
   1364         if (xd[i] != yd[i]) {
   1365           xLTy = xd[i] < yd[i];
   1366           break;
   1367         }
   1368       }
   1369 
   1370       k = 0;
   1371     }
   1372 
   1373     if (xLTy) {
   1374       d = xd;
   1375       xd = yd;
   1376       yd = d;
   1377       y.s = -y.s;
   1378     }
   1379 
   1380     len = xd.length;
   1381 
   1382     // Append zeros to `xd` if shorter.
   1383     // Don't add zeros to `yd` if shorter as subtraction only needs to start at `yd` length.
   1384     for (i = yd.length - len; i > 0; --i) xd[len++] = 0;
   1385 
   1386     // Subtract yd from xd.
   1387     for (i = yd.length; i > k;) {
   1388 
   1389       if (xd[--i] < yd[i]) {
   1390         for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1;
   1391         --xd[j];
   1392         xd[i] += BASE;
   1393       }
   1394 
   1395       xd[i] -= yd[i];
   1396     }
   1397 
   1398     // Remove trailing zeros.
   1399     for (; xd[--len] === 0;) xd.pop();
   1400 
   1401     // Remove leading zeros and adjust exponent accordingly.
   1402     for (; xd[0] === 0; xd.shift()) --e;
   1403 
   1404     // Zero?
   1405     if (!xd[0]) return new Ctor(rm === 3 ? -0 : 0);
   1406 
   1407     y.d = xd;
   1408     y.e = getBase10Exponent(xd, e);
   1409 
   1410     return external ? finalise(y, pr, rm) : y;
   1411   };
   1412 
   1413 
   1414   /*
   1415    *   n % 0 =  N
   1416    *   n % N =  N
   1417    *   n % I =  n
   1418    *   0 % n =  0
   1419    *  -0 % n = -0
   1420    *   0 % 0 =  N
   1421    *   0 % N =  N
   1422    *   0 % I =  0
   1423    *   N % n =  N
   1424    *   N % 0 =  N
   1425    *   N % N =  N
   1426    *   N % I =  N
   1427    *   I % n =  N
   1428    *   I % 0 =  N
   1429    *   I % N =  N
   1430    *   I % I =  N
   1431    *
   1432    * Return a new Decimal whose value is the value of this Decimal modulo `y`, rounded to
   1433    * `precision` significant digits using rounding mode `rounding`.
   1434    *
   1435    * The result depends on the modulo mode.
   1436    *
   1437    */
   1438   P.modulo = P.mod = function (y) {
   1439     var q,
   1440       x = this,
   1441       Ctor = x.constructor;
   1442 
   1443     y = new Ctor(y);
   1444 
   1445     // Return NaN if x is ±Infinity or NaN, or y is NaN or ±0.
   1446     if (!x.d || !y.s || y.d && !y.d[0]) return new Ctor(NaN);
   1447 
   1448     // Return x if y is ±Infinity or x is ±0.
   1449     if (!y.d || x.d && !x.d[0]) {
   1450       return finalise(new Ctor(x), Ctor.precision, Ctor.rounding);
   1451     }
   1452 
   1453     // Prevent rounding of intermediate calculations.
   1454     external = false;
   1455 
   1456     if (Ctor.modulo == 9) {
   1457 
   1458       // Euclidian division: q = sign(y) * floor(x / abs(y))
   1459       // result = x - q * y    where  0 <= result < abs(y)
   1460       q = divide(x, y.abs(), 0, 3, 1);
   1461       q.s *= y.s;
   1462     } else {
   1463       q = divide(x, y, 0, Ctor.modulo, 1);
   1464     }
   1465 
   1466     q = q.times(y);
   1467 
   1468     external = true;
   1469 
   1470     return x.minus(q);
   1471   };
   1472 
   1473 
   1474   /*
   1475    * Return a new Decimal whose value is the natural exponential of the value of this Decimal,
   1476    * i.e. the base e raised to the power the value of this Decimal, rounded to `precision`
   1477    * significant digits using rounding mode `rounding`.
   1478    *
   1479    */
   1480   P.naturalExponential = P.exp = function () {
   1481     return naturalExponential(this);
   1482   };
   1483 
   1484 
   1485   /*
   1486    * Return a new Decimal whose value is the natural logarithm of the value of this Decimal,
   1487    * rounded to `precision` significant digits using rounding mode `rounding`.
   1488    *
   1489    */
   1490   P.naturalLogarithm = P.ln = function () {
   1491     return naturalLogarithm(this);
   1492   };
   1493 
   1494 
   1495   /*
   1496    * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by
   1497    * -1.
   1498    *
   1499    */
   1500   P.negated = P.neg = function () {
   1501     var x = new this.constructor(this);
   1502     x.s = -x.s;
   1503     return finalise(x);
   1504   };
   1505 
   1506 
   1507   /*
   1508    *  n + 0 = n
   1509    *  n + N = N
   1510    *  n + I = I
   1511    *  0 + n = n
   1512    *  0 + 0 = 0
   1513    *  0 + N = N
   1514    *  0 + I = I
   1515    *  N + n = N
   1516    *  N + 0 = N
   1517    *  N + N = N
   1518    *  N + I = N
   1519    *  I + n = I
   1520    *  I + 0 = I
   1521    *  I + N = N
   1522    *  I + I = I
   1523    *
   1524    * Return a new Decimal whose value is the value of this Decimal plus `y`, rounded to `precision`
   1525    * significant digits using rounding mode `rounding`.
   1526    *
   1527    */
   1528   P.plus = P.add = function (y) {
   1529     var carry, d, e, i, k, len, pr, rm, xd, yd,
   1530       x = this,
   1531       Ctor = x.constructor;
   1532 
   1533     y = new Ctor(y);
   1534 
   1535     // If either is not finite...
   1536     if (!x.d || !y.d) {
   1537 
   1538       // Return NaN if either is NaN.
   1539       if (!x.s || !y.s) y = new Ctor(NaN);
   1540 
   1541       // Return x if y is finite and x is ±Infinity.
   1542       // Return x if both are ±Infinity with the same sign.
   1543       // Return NaN if both are ±Infinity with different signs.
   1544       // Return y if x is finite and y is ±Infinity.
   1545       else if (!x.d) y = new Ctor(y.d || x.s === y.s ? x : NaN);
   1546 
   1547       return y;
   1548     }
   1549 
   1550      // If signs differ...
   1551     if (x.s != y.s) {
   1552       y.s = -y.s;
   1553       return x.minus(y);
   1554     }
   1555 
   1556     xd = x.d;
   1557     yd = y.d;
   1558     pr = Ctor.precision;
   1559     rm = Ctor.rounding;
   1560 
   1561     // If either is zero...
   1562     if (!xd[0] || !yd[0]) {
   1563 
   1564       // Return x if y is zero.
   1565       // Return y if y is non-zero.
   1566       if (!yd[0]) y = new Ctor(x);
   1567 
   1568       return external ? finalise(y, pr, rm) : y;
   1569     }
   1570 
   1571     // x and y are finite, non-zero numbers with the same sign.
   1572 
   1573     // Calculate base 1e7 exponents.
   1574     k = mathfloor(x.e / LOG_BASE);
   1575     e = mathfloor(y.e / LOG_BASE);
   1576 
   1577     xd = xd.slice();
   1578     i = k - e;
   1579 
   1580     // If base 1e7 exponents differ...
   1581     if (i) {
   1582 
   1583       if (i < 0) {
   1584         d = xd;
   1585         i = -i;
   1586         len = yd.length;
   1587       } else {
   1588         d = yd;
   1589         e = k;
   1590         len = xd.length;
   1591       }
   1592 
   1593       // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1.
   1594       k = Math.ceil(pr / LOG_BASE);
   1595       len = k > len ? k + 1 : len + 1;
   1596 
   1597       if (i > len) {
   1598         i = len;
   1599         d.length = 1;
   1600       }
   1601 
   1602       // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts.
   1603       d.reverse();
   1604       for (; i--;) d.push(0);
   1605       d.reverse();
   1606     }
   1607 
   1608     len = xd.length;
   1609     i = yd.length;
   1610 
   1611     // If yd is longer than xd, swap xd and yd so xd points to the longer array.
   1612     if (len - i < 0) {
   1613       i = len;
   1614       d = yd;
   1615       yd = xd;
   1616       xd = d;
   1617     }
   1618 
   1619     // Only start adding at yd.length - 1 as the further digits of xd can be left as they are.
   1620     for (carry = 0; i;) {
   1621       carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0;
   1622       xd[i] %= BASE;
   1623     }
   1624 
   1625     if (carry) {
   1626       xd.unshift(carry);
   1627       ++e;
   1628     }
   1629 
   1630     // Remove trailing zeros.
   1631     // No need to check for zero, as +x + +y != 0 && -x + -y != 0
   1632     for (len = xd.length; xd[--len] == 0;) xd.pop();
   1633 
   1634     y.d = xd;
   1635     y.e = getBase10Exponent(xd, e);
   1636 
   1637     return external ? finalise(y, pr, rm) : y;
   1638   };
   1639 
   1640 
   1641   /*
   1642    * Return the number of significant digits of the value of this Decimal.
   1643    *
   1644    * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
   1645    *
   1646    */
   1647   P.precision = P.sd = function (z) {
   1648     var k,
   1649       x = this;
   1650 
   1651     if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z);
   1652 
   1653     if (x.d) {
   1654       k = getPrecision(x.d);
   1655       if (z && x.e + 1 > k) k = x.e + 1;
   1656     } else {
   1657       k = NaN;
   1658     }
   1659 
   1660     return k;
   1661   };
   1662 
   1663 
   1664   /*
   1665    * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using
   1666    * rounding mode `rounding`.
   1667    *
   1668    */
   1669   P.round = function () {
   1670     var x = this,
   1671       Ctor = x.constructor;
   1672 
   1673     return finalise(new Ctor(x), x.e + 1, Ctor.rounding);
   1674   };
   1675 
   1676 
   1677   /*
   1678    * Return a new Decimal whose value is the sine of the value in radians of this Decimal.
   1679    *
   1680    * Domain: [-Infinity, Infinity]
   1681    * Range: [-1, 1]
   1682    *
   1683    * sin(x) = x - x^3/3! + x^5/5! - ...
   1684    *
   1685    * sin(0)         = 0
   1686    * sin(-0)        = -0
   1687    * sin(Infinity)  = NaN
   1688    * sin(-Infinity) = NaN
   1689    * sin(NaN)       = NaN
   1690    *
   1691    */
   1692   P.sine = P.sin = function () {
   1693     var pr, rm,
   1694       x = this,
   1695       Ctor = x.constructor;
   1696 
   1697     if (!x.isFinite()) return new Ctor(NaN);
   1698     if (x.isZero()) return new Ctor(x);
   1699 
   1700     pr = Ctor.precision;
   1701     rm = Ctor.rounding;
   1702     Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;
   1703     Ctor.rounding = 1;
   1704 
   1705     x = sine(Ctor, toLessThanHalfPi(Ctor, x));
   1706 
   1707     Ctor.precision = pr;
   1708     Ctor.rounding = rm;
   1709 
   1710     return finalise(quadrant > 2 ? x.neg() : x, pr, rm, true);
   1711   };
   1712 
   1713 
   1714   /*
   1715    * Return a new Decimal whose value is the square root of this Decimal, rounded to `precision`
   1716    * significant digits using rounding mode `rounding`.
   1717    *
   1718    *  sqrt(-n) =  N
   1719    *  sqrt(N)  =  N
   1720    *  sqrt(-I) =  N
   1721    *  sqrt(I)  =  I
   1722    *  sqrt(0)  =  0
   1723    *  sqrt(-0) = -0
   1724    *
   1725    */
   1726   P.squareRoot = P.sqrt = function () {
   1727     var m, n, sd, r, rep, t,
   1728       x = this,
   1729       d = x.d,
   1730       e = x.e,
   1731       s = x.s,
   1732       Ctor = x.constructor;
   1733 
   1734     // Negative/NaN/Infinity/zero?
   1735     if (s !== 1 || !d || !d[0]) {
   1736       return new Ctor(!s || s < 0 && (!d || d[0]) ? NaN : d ? x : 1 / 0);
   1737     }
   1738 
   1739     external = false;
   1740 
   1741     // Initial estimate.
   1742     s = Math.sqrt(+x);
   1743 
   1744     // Math.sqrt underflow/overflow?
   1745     // Pass x to Math.sqrt as integer, then adjust the exponent of the result.
   1746     if (s == 0 || s == 1 / 0) {
   1747       n = digitsToString(d);
   1748 
   1749       if ((n.length + e) % 2 == 0) n += '0';
   1750       s = Math.sqrt(n);
   1751       e = mathfloor((e + 1) / 2) - (e < 0 || e % 2);
   1752 
   1753       if (s == 1 / 0) {
   1754         n = '5e' + e;
   1755       } else {
   1756         n = s.toExponential();
   1757         n = n.slice(0, n.indexOf('e') + 1) + e;
   1758       }
   1759 
   1760       r = new Ctor(n);
   1761     } else {
   1762       r = new Ctor(s.toString());
   1763     }
   1764 
   1765     sd = (e = Ctor.precision) + 3;
   1766 
   1767     // Newton-Raphson iteration.
   1768     for (;;) {
   1769       t = r;
   1770       r = t.plus(divide(x, t, sd + 2, 1)).times(0.5);
   1771 
   1772       // TODO? Replace with for-loop and checkRoundingDigits.
   1773       if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {
   1774         n = n.slice(sd - 3, sd + 1);
   1775 
   1776         // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or
   1777         // 4999, i.e. approaching a rounding boundary, continue the iteration.
   1778         if (n == '9999' || !rep && n == '4999') {
   1779 
   1780           // On the first iteration only, check to see if rounding up gives the exact result as the
   1781           // nines may infinitely repeat.
   1782           if (!rep) {
   1783             finalise(t, e + 1, 0);
   1784 
   1785             if (t.times(t).eq(x)) {
   1786               r = t;
   1787               break;
   1788             }
   1789           }
   1790 
   1791           sd += 4;
   1792           rep = 1;
   1793         } else {
   1794 
   1795           // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.
   1796           // If not, then there are further digits and m will be truthy.
   1797           if (!+n || !+n.slice(1) && n.charAt(0) == '5') {
   1798 
   1799             // Truncate to the first rounding digit.
   1800             finalise(r, e + 1, 1);
   1801             m = !r.times(r).eq(x);
   1802           }
   1803 
   1804           break;
   1805         }
   1806       }
   1807     }
   1808 
   1809     external = true;
   1810 
   1811     return finalise(r, e, Ctor.rounding, m);
   1812   };
   1813 
   1814 
   1815   /*
   1816    * Return a new Decimal whose value is the tangent of the value in radians of this Decimal.
   1817    *
   1818    * Domain: [-Infinity, Infinity]
   1819    * Range: [-Infinity, Infinity]
   1820    *
   1821    * tan(0)         = 0
   1822    * tan(-0)        = -0
   1823    * tan(Infinity)  = NaN
   1824    * tan(-Infinity) = NaN
   1825    * tan(NaN)       = NaN
   1826    *
   1827    */
   1828   P.tangent = P.tan = function () {
   1829     var pr, rm,
   1830       x = this,
   1831       Ctor = x.constructor;
   1832 
   1833     if (!x.isFinite()) return new Ctor(NaN);
   1834     if (x.isZero()) return new Ctor(x);
   1835 
   1836     pr = Ctor.precision;
   1837     rm = Ctor.rounding;
   1838     Ctor.precision = pr + 10;
   1839     Ctor.rounding = 1;
   1840 
   1841     x = x.sin();
   1842     x.s = 1;
   1843     x = divide(x, new Ctor(1).minus(x.times(x)).sqrt(), pr + 10, 0);
   1844 
   1845     Ctor.precision = pr;
   1846     Ctor.rounding = rm;
   1847 
   1848     return finalise(quadrant == 2 || quadrant == 4 ? x.neg() : x, pr, rm, true);
   1849   };
   1850 
   1851 
   1852   /*
   1853    *  n * 0 = 0
   1854    *  n * N = N
   1855    *  n * I = I
   1856    *  0 * n = 0
   1857    *  0 * 0 = 0
   1858    *  0 * N = N
   1859    *  0 * I = N
   1860    *  N * n = N
   1861    *  N * 0 = N
   1862    *  N * N = N
   1863    *  N * I = N
   1864    *  I * n = I
   1865    *  I * 0 = N
   1866    *  I * N = N
   1867    *  I * I = I
   1868    *
   1869    * Return a new Decimal whose value is this Decimal times `y`, rounded to `precision` significant
   1870    * digits using rounding mode `rounding`.
   1871    *
   1872    */
   1873   P.times = P.mul = function (y) {
   1874     var carry, e, i, k, r, rL, t, xdL, ydL,
   1875       x = this,
   1876       Ctor = x.constructor,
   1877       xd = x.d,
   1878       yd = (y = new Ctor(y)).d;
   1879 
   1880     y.s *= x.s;
   1881 
   1882      // If either is NaN, ±Infinity or ±0...
   1883     if (!xd || !xd[0] || !yd || !yd[0]) {
   1884 
   1885       return new Ctor(!y.s || xd && !xd[0] && !yd || yd && !yd[0] && !xd
   1886 
   1887         // Return NaN if either is NaN.
   1888         // Return NaN if x is ±0 and y is ±Infinity, or y is ±0 and x is ±Infinity.
   1889         ? NaN
   1890 
   1891         // Return ±Infinity if either is ±Infinity.
   1892         // Return ±0 if either is ±0.
   1893         : !xd || !yd ? y.s / 0 : y.s * 0);
   1894     }
   1895 
   1896     e = mathfloor(x.e / LOG_BASE) + mathfloor(y.e / LOG_BASE);
   1897     xdL = xd.length;
   1898     ydL = yd.length;
   1899 
   1900     // Ensure xd points to the longer array.
   1901     if (xdL < ydL) {
   1902       r = xd;
   1903       xd = yd;
   1904       yd = r;
   1905       rL = xdL;
   1906       xdL = ydL;
   1907       ydL = rL;
   1908     }
   1909 
   1910     // Initialise the result array with zeros.
   1911     r = [];
   1912     rL = xdL + ydL;
   1913     for (i = rL; i--;) r.push(0);
   1914 
   1915     // Multiply!
   1916     for (i = ydL; --i >= 0;) {
   1917       carry = 0;
   1918       for (k = xdL + i; k > i;) {
   1919         t = r[k] + yd[i] * xd[k - i - 1] + carry;
   1920         r[k--] = t % BASE | 0;
   1921         carry = t / BASE | 0;
   1922       }
   1923 
   1924       r[k] = (r[k] + carry) % BASE | 0;
   1925     }
   1926 
   1927     // Remove trailing zeros.
   1928     for (; !r[--rL];) r.pop();
   1929 
   1930     if (carry) ++e;
   1931     else r.shift();
   1932 
   1933     y.d = r;
   1934     y.e = getBase10Exponent(r, e);
   1935 
   1936     return external ? finalise(y, Ctor.precision, Ctor.rounding) : y;
   1937   };
   1938 
   1939 
   1940   /*
   1941    * Return a string representing the value of this Decimal in base 2, round to `sd` significant
   1942    * digits using rounding mode `rm`.
   1943    *
   1944    * If the optional `sd` argument is present then return binary exponential notation.
   1945    *
   1946    * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
   1947    * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
   1948    *
   1949    */
   1950   P.toBinary = function (sd, rm) {
   1951     return toStringBinary(this, 2, sd, rm);
   1952   };
   1953 
   1954 
   1955   /*
   1956    * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp`
   1957    * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted.
   1958    *
   1959    * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal.
   1960    *
   1961    * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
   1962    * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
   1963    *
   1964    */
   1965   P.toDecimalPlaces = P.toDP = function (dp, rm) {
   1966     var x = this,
   1967       Ctor = x.constructor;
   1968 
   1969     x = new Ctor(x);
   1970     if (dp === void 0) return x;
   1971 
   1972     checkInt32(dp, 0, MAX_DIGITS);
   1973 
   1974     if (rm === void 0) rm = Ctor.rounding;
   1975     else checkInt32(rm, 0, 8);
   1976 
   1977     return finalise(x, dp + x.e + 1, rm);
   1978   };
   1979 
   1980 
   1981   /*
   1982    * Return a string representing the value of this Decimal in exponential notation rounded to
   1983    * `dp` fixed decimal places using rounding mode `rounding`.
   1984    *
   1985    * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
   1986    * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
   1987    *
   1988    */
   1989   P.toExponential = function (dp, rm) {
   1990     var str,
   1991       x = this,
   1992       Ctor = x.constructor;
   1993 
   1994     if (dp === void 0) {
   1995       str = finiteToString(x, true);
   1996     } else {
   1997       checkInt32(dp, 0, MAX_DIGITS);
   1998 
   1999       if (rm === void 0) rm = Ctor.rounding;
   2000       else checkInt32(rm, 0, 8);
   2001 
   2002       x = finalise(new Ctor(x), dp + 1, rm);
   2003       str = finiteToString(x, true, dp + 1);
   2004     }
   2005 
   2006     return x.isNeg() && !x.isZero() ? '-' + str : str;
   2007   };
   2008 
   2009 
   2010   /*
   2011    * Return a string representing the value of this Decimal in normal (fixed-point) notation to
   2012    * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is
   2013    * omitted.
   2014    *
   2015    * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'.
   2016    *
   2017    * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
   2018    * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
   2019    *
   2020    * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'.
   2021    * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'.
   2022    * (-0).toFixed(3) is '0.000'.
   2023    * (-0.5).toFixed(0) is '-0'.
   2024    *
   2025    */
   2026   P.toFixed = function (dp, rm) {
   2027     var str, y,
   2028       x = this,
   2029       Ctor = x.constructor;
   2030 
   2031     if (dp === void 0) {
   2032       str = finiteToString(x);
   2033     } else {
   2034       checkInt32(dp, 0, MAX_DIGITS);
   2035 
   2036       if (rm === void 0) rm = Ctor.rounding;
   2037       else checkInt32(rm, 0, 8);
   2038 
   2039       y = finalise(new Ctor(x), dp + x.e + 1, rm);
   2040       str = finiteToString(y, false, dp + y.e + 1);
   2041     }
   2042 
   2043     // To determine whether to add the minus sign look at the value before it was rounded,
   2044     // i.e. look at `x` rather than `y`.
   2045     return x.isNeg() && !x.isZero() ? '-' + str : str;
   2046   };
   2047 
   2048 
   2049   /*
   2050    * Return an array representing the value of this Decimal as a simple fraction with an integer
   2051    * numerator and an integer denominator.
   2052    *
   2053    * The denominator will be a positive non-zero value less than or equal to the specified maximum
   2054    * denominator. If a maximum denominator is not specified, the denominator will be the lowest
   2055    * value necessary to represent the number exactly.
   2056    *
   2057    * [maxD] {number|string|Decimal} Maximum denominator. Integer >= 1 and < Infinity.
   2058    *
   2059    */
   2060   P.toFraction = function (maxD) {
   2061     var d, d0, d1, d2, e, k, n, n0, n1, pr, q, r,
   2062       x = this,
   2063       xd = x.d,
   2064       Ctor = x.constructor;
   2065 
   2066     if (!xd) return new Ctor(x);
   2067 
   2068     n1 = d0 = new Ctor(1);
   2069     d1 = n0 = new Ctor(0);
   2070 
   2071     d = new Ctor(d1);
   2072     e = d.e = getPrecision(xd) - x.e - 1;
   2073     k = e % LOG_BASE;
   2074     d.d[0] = mathpow(10, k < 0 ? LOG_BASE + k : k);
   2075 
   2076     if (maxD == null) {
   2077 
   2078       // d is 10**e, the minimum max-denominator needed.
   2079       maxD = e > 0 ? d : n1;
   2080     } else {
   2081       n = new Ctor(maxD);
   2082       if (!n.isInt() || n.lt(n1)) throw Error(invalidArgument + n);
   2083       maxD = n.gt(d) ? (e > 0 ? d : n1) : n;
   2084     }
   2085 
   2086     external = false;
   2087     n = new Ctor(digitsToString(xd));
   2088     pr = Ctor.precision;
   2089     Ctor.precision = e = xd.length * LOG_BASE * 2;
   2090 
   2091     for (;;)  {
   2092       q = divide(n, d, 0, 1, 1);
   2093       d2 = d0.plus(q.times(d1));
   2094       if (d2.cmp(maxD) == 1) break;
   2095       d0 = d1;
   2096       d1 = d2;
   2097       d2 = n1;
   2098       n1 = n0.plus(q.times(d2));
   2099       n0 = d2;
   2100       d2 = d;
   2101       d = n.minus(q.times(d2));
   2102       n = d2;
   2103     }
   2104 
   2105     d2 = divide(maxD.minus(d0), d1, 0, 1, 1);
   2106     n0 = n0.plus(d2.times(n1));
   2107     d0 = d0.plus(d2.times(d1));
   2108     n0.s = n1.s = x.s;
   2109 
   2110     // Determine which fraction is closer to x, n0/d0 or n1/d1?
   2111     r = divide(n1, d1, e, 1).minus(x).abs().cmp(divide(n0, d0, e, 1).minus(x).abs()) < 1
   2112         ? [n1, d1] : [n0, d0];
   2113 
   2114     Ctor.precision = pr;
   2115     external = true;
   2116 
   2117     return r;
   2118   };
   2119 
   2120 
   2121   /*
   2122    * Return a string representing the value of this Decimal in base 16, round to `sd` significant
   2123    * digits using rounding mode `rm`.
   2124    *
   2125    * If the optional `sd` argument is present then return binary exponential notation.
   2126    *
   2127    * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
   2128    * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
   2129    *
   2130    */
   2131   P.toHexadecimal = P.toHex = function (sd, rm) {
   2132     return toStringBinary(this, 16, sd, rm);
   2133   };
   2134 
   2135 
   2136   /*
   2137    * Returns a new Decimal whose value is the nearest multiple of `y` in the direction of rounding
   2138    * mode `rm`, or `Decimal.rounding` if `rm` is omitted, to the value of this Decimal.
   2139    *
   2140    * The return value will always have the same sign as this Decimal, unless either this Decimal
   2141    * or `y` is NaN, in which case the return value will be also be NaN.
   2142    *
   2143    * The return value is not affected by the value of `precision`.
   2144    *
   2145    * y {number|string|Decimal} The magnitude to round to a multiple of.
   2146    * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
   2147    *
   2148    * 'toNearest() rounding mode not an integer: {rm}'
   2149    * 'toNearest() rounding mode out of range: {rm}'
   2150    *
   2151    */
   2152   P.toNearest = function (y, rm) {
   2153     var x = this,
   2154       Ctor = x.constructor;
   2155 
   2156     x = new Ctor(x);
   2157 
   2158     if (y == null) {
   2159 
   2160       // If x is not finite, return x.
   2161       if (!x.d) return x;
   2162 
   2163       y = new Ctor(1);
   2164       rm = Ctor.rounding;
   2165     } else {
   2166       y = new Ctor(y);
   2167       if (rm === void 0) {
   2168         rm = Ctor.rounding;
   2169       } else {
   2170         checkInt32(rm, 0, 8);
   2171       }
   2172 
   2173       // If x is not finite, return x if y is not NaN, else NaN.
   2174       if (!x.d) return y.s ? x : y;
   2175 
   2176       // If y is not finite, return Infinity with the sign of x if y is Infinity, else NaN.
   2177       if (!y.d) {
   2178         if (y.s) y.s = x.s;
   2179         return y;
   2180       }
   2181     }
   2182 
   2183     // If y is not zero, calculate the nearest multiple of y to x.
   2184     if (y.d[0]) {
   2185       external = false;
   2186       x = divide(x, y, 0, rm, 1).times(y);
   2187       external = true;
   2188       finalise(x);
   2189 
   2190     // If y is zero, return zero with the sign of x.
   2191     } else {
   2192       y.s = x.s;
   2193       x = y;
   2194     }
   2195 
   2196     return x;
   2197   };
   2198 
   2199 
   2200   /*
   2201    * Return the value of this Decimal converted to a number primitive.
   2202    * Zero keeps its sign.
   2203    *
   2204    */
   2205   P.toNumber = function () {
   2206     return +this;
   2207   };
   2208 
   2209 
   2210   /*
   2211    * Return a string representing the value of this Decimal in base 8, round to `sd` significant
   2212    * digits using rounding mode `rm`.
   2213    *
   2214    * If the optional `sd` argument is present then return binary exponential notation.
   2215    *
   2216    * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
   2217    * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
   2218    *
   2219    */
   2220   P.toOctal = function (sd, rm) {
   2221     return toStringBinary(this, 8, sd, rm);
   2222   };
   2223 
   2224 
   2225   /*
   2226    * Return a new Decimal whose value is the value of this Decimal raised to the power `y`, rounded
   2227    * to `precision` significant digits using rounding mode `rounding`.
   2228    *
   2229    * ECMAScript compliant.
   2230    *
   2231    *   pow(x, NaN)                           = NaN
   2232    *   pow(x, ±0)                            = 1
   2233 
   2234    *   pow(NaN, non-zero)                    = NaN
   2235    *   pow(abs(x) > 1, +Infinity)            = +Infinity
   2236    *   pow(abs(x) > 1, -Infinity)            = +0
   2237    *   pow(abs(x) == 1, ±Infinity)           = NaN
   2238    *   pow(abs(x) < 1, +Infinity)            = +0
   2239    *   pow(abs(x) < 1, -Infinity)            = +Infinity
   2240    *   pow(+Infinity, y > 0)                 = +Infinity
   2241    *   pow(+Infinity, y < 0)                 = +0
   2242    *   pow(-Infinity, odd integer > 0)       = -Infinity
   2243    *   pow(-Infinity, even integer > 0)      = +Infinity
   2244    *   pow(-Infinity, odd integer < 0)       = -0
   2245    *   pow(-Infinity, even integer < 0)      = +0
   2246    *   pow(+0, y > 0)                        = +0
   2247    *   pow(+0, y < 0)                        = +Infinity
   2248    *   pow(-0, odd integer > 0)              = -0
   2249    *   pow(-0, even integer > 0)             = +0
   2250    *   pow(-0, odd integer < 0)              = -Infinity
   2251    *   pow(-0, even integer < 0)             = +Infinity
   2252    *   pow(finite x < 0, finite non-integer) = NaN
   2253    *
   2254    * For non-integer or very large exponents pow(x, y) is calculated using
   2255    *
   2256    *   x^y = exp(y*ln(x))
   2257    *
   2258    * Assuming the first 15 rounding digits are each equally likely to be any digit 0-9, the
   2259    * probability of an incorrectly rounded result
   2260    * P([49]9{14} | [50]0{14}) = 2 * 0.2 * 10^-14 = 4e-15 = 1/2.5e+14
   2261    * i.e. 1 in 250,000,000,000,000
   2262    *
   2263    * If a result is incorrectly rounded the maximum error will be 1 ulp (unit in last place).
   2264    *
   2265    * y {number|string|Decimal} The power to which to raise this Decimal.
   2266    *
   2267    */
   2268   P.toPower = P.pow = function (y) {
   2269     var e, k, pr, r, rm, s,
   2270       x = this,
   2271       Ctor = x.constructor,
   2272       yn = +(y = new Ctor(y));
   2273 
   2274     // Either ±Infinity, NaN or ±0?
   2275     if (!x.d || !y.d || !x.d[0] || !y.d[0]) return new Ctor(mathpow(+x, yn));
   2276 
   2277     x = new Ctor(x);
   2278 
   2279     if (x.eq(1)) return x;
   2280 
   2281     pr = Ctor.precision;
   2282     rm = Ctor.rounding;
   2283 
   2284     if (y.eq(1)) return finalise(x, pr, rm);
   2285 
   2286     // y exponent
   2287     e = mathfloor(y.e / LOG_BASE);
   2288 
   2289     // If y is a small integer use the 'exponentiation by squaring' algorithm.
   2290     if (e >= y.d.length - 1 && (k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) {
   2291       r = intPow(Ctor, x, k, pr);
   2292       return y.s < 0 ? new Ctor(1).div(r) : finalise(r, pr, rm);
   2293     }
   2294 
   2295     s = x.s;
   2296 
   2297     // if x is negative
   2298     if (s < 0) {
   2299 
   2300       // if y is not an integer
   2301       if (e < y.d.length - 1) return new Ctor(NaN);
   2302 
   2303       // Result is positive if x is negative and the last digit of integer y is even.
   2304       if ((y.d[e] & 1) == 0) s = 1;
   2305 
   2306       // if x.eq(-1)
   2307       if (x.e == 0 && x.d[0] == 1 && x.d.length == 1) {
   2308         x.s = s;
   2309         return x;
   2310       }
   2311     }
   2312 
   2313     // Estimate result exponent.
   2314     // x^y = 10^e,  where e = y * log10(x)
   2315     // log10(x) = log10(x_significand) + x_exponent
   2316     // log10(x_significand) = ln(x_significand) / ln(10)
   2317     k = mathpow(+x, yn);
   2318     e = k == 0 || !isFinite(k)
   2319       ? mathfloor(yn * (Math.log('0.' + digitsToString(x.d)) / Math.LN10 + x.e + 1))
   2320       : new Ctor(k + '').e;
   2321 
   2322     // Exponent estimate may be incorrect e.g. x: 0.999999999999999999, y: 2.29, e: 0, r.e: -1.
   2323 
   2324     // Overflow/underflow?
   2325     if (e > Ctor.maxE + 1 || e < Ctor.minE - 1) return new Ctor(e > 0 ? s / 0 : 0);
   2326 
   2327     external = false;
   2328     Ctor.rounding = x.s = 1;
   2329 
   2330     // Estimate the extra guard digits needed to ensure five correct rounding digits from
   2331     // naturalLogarithm(x). Example of failure without these extra digits (precision: 10):
   2332     // new Decimal(2.32456).pow('2087987436534566.46411')
   2333     // should be 1.162377823e+764914905173815, but is 1.162355823e+764914905173815
   2334     k = Math.min(12, (e + '').length);
   2335 
   2336     // r = x^y = exp(y*ln(x))
   2337     r = naturalExponential(y.times(naturalLogarithm(x, pr + k)), pr);
   2338 
   2339     // r may be Infinity, e.g. (0.9999999999999999).pow(-1e+40)
   2340     if (r.d) {
   2341 
   2342       // Truncate to the required precision plus five rounding digits.
   2343       r = finalise(r, pr + 5, 1);
   2344 
   2345       // If the rounding digits are [49]9999 or [50]0000 increase the precision by 10 and recalculate
   2346       // the result.
   2347       if (checkRoundingDigits(r.d, pr, rm)) {
   2348         e = pr + 10;
   2349 
   2350         // Truncate to the increased precision plus five rounding digits.
   2351         r = finalise(naturalExponential(y.times(naturalLogarithm(x, e + k)), e), e + 5, 1);
   2352 
   2353         // Check for 14 nines from the 2nd rounding digit (the first rounding digit may be 4 or 9).
   2354         if (+digitsToString(r.d).slice(pr + 1, pr + 15) + 1 == 1e14) {
   2355           r = finalise(r, pr + 1, 0);
   2356         }
   2357       }
   2358     }
   2359 
   2360     r.s = s;
   2361     external = true;
   2362     Ctor.rounding = rm;
   2363 
   2364     return finalise(r, pr, rm);
   2365   };
   2366 
   2367 
   2368   /*
   2369    * Return a string representing the value of this Decimal rounded to `sd` significant digits
   2370    * using rounding mode `rounding`.
   2371    *
   2372    * Return exponential notation if `sd` is less than the number of digits necessary to represent
   2373    * the integer part of the value in normal notation.
   2374    *
   2375    * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
   2376    * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
   2377    *
   2378    */
   2379   P.toPrecision = function (sd, rm) {
   2380     var str,
   2381       x = this,
   2382       Ctor = x.constructor;
   2383 
   2384     if (sd === void 0) {
   2385       str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
   2386     } else {
   2387       checkInt32(sd, 1, MAX_DIGITS);
   2388 
   2389       if (rm === void 0) rm = Ctor.rounding;
   2390       else checkInt32(rm, 0, 8);
   2391 
   2392       x = finalise(new Ctor(x), sd, rm);
   2393       str = finiteToString(x, sd <= x.e || x.e <= Ctor.toExpNeg, sd);
   2394     }
   2395 
   2396     return x.isNeg() && !x.isZero() ? '-' + str : str;
   2397   };
   2398 
   2399 
   2400   /*
   2401    * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd`
   2402    * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if
   2403    * omitted.
   2404    *
   2405    * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
   2406    * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
   2407    *
   2408    * 'toSD() digits out of range: {sd}'
   2409    * 'toSD() digits not an integer: {sd}'
   2410    * 'toSD() rounding mode not an integer: {rm}'
   2411    * 'toSD() rounding mode out of range: {rm}'
   2412    *
   2413    */
   2414   P.toSignificantDigits = P.toSD = function (sd, rm) {
   2415     var x = this,
   2416       Ctor = x.constructor;
   2417 
   2418     if (sd === void 0) {
   2419       sd = Ctor.precision;
   2420       rm = Ctor.rounding;
   2421     } else {
   2422       checkInt32(sd, 1, MAX_DIGITS);
   2423 
   2424       if (rm === void 0) rm = Ctor.rounding;
   2425       else checkInt32(rm, 0, 8);
   2426     }
   2427 
   2428     return finalise(new Ctor(x), sd, rm);
   2429   };
   2430 
   2431 
   2432   /*
   2433    * Return a string representing the value of this Decimal.
   2434    *
   2435    * Return exponential notation if this Decimal has a positive exponent equal to or greater than
   2436    * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`.
   2437    *
   2438    */
   2439   P.toString = function () {
   2440     var x = this,
   2441       Ctor = x.constructor,
   2442       str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
   2443 
   2444     return x.isNeg() && !x.isZero() ? '-' + str : str;
   2445   };
   2446 
   2447 
   2448   /*
   2449    * Return a new Decimal whose value is the value of this Decimal truncated to a whole number.
   2450    *
   2451    */
   2452   P.truncated = P.trunc = function () {
   2453     return finalise(new this.constructor(this), this.e + 1, 1);
   2454   };
   2455 
   2456 
   2457   /*
   2458    * Return a string representing the value of this Decimal.
   2459    * Unlike `toString`, negative zero will include the minus sign.
   2460    *
   2461    */
   2462   P.valueOf = P.toJSON = function () {
   2463     var x = this,
   2464       Ctor = x.constructor,
   2465       str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
   2466 
   2467     return x.isNeg() ? '-' + str : str;
   2468   };
   2469 
   2470 
   2471   // Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers.
   2472 
   2473 
   2474   /*
   2475    *  digitsToString           P.cubeRoot, P.logarithm, P.squareRoot, P.toFraction, P.toPower,
   2476    *                           finiteToString, naturalExponential, naturalLogarithm
   2477    *  checkInt32               P.toDecimalPlaces, P.toExponential, P.toFixed, P.toNearest,
   2478    *                           P.toPrecision, P.toSignificantDigits, toStringBinary, random
   2479    *  checkRoundingDigits      P.logarithm, P.toPower, naturalExponential, naturalLogarithm
   2480    *  convertBase              toStringBinary, parseOther
   2481    *  cos                      P.cos
   2482    *  divide                   P.atanh, P.cubeRoot, P.dividedBy, P.dividedToIntegerBy,
   2483    *                           P.logarithm, P.modulo, P.squareRoot, P.tan, P.tanh, P.toFraction,
   2484    *                           P.toNearest, toStringBinary, naturalExponential, naturalLogarithm,
   2485    *                           taylorSeries, atan2, parseOther
   2486    *  finalise                 P.absoluteValue, P.atan, P.atanh, P.ceil, P.cos, P.cosh,
   2487    *                           P.cubeRoot, P.dividedToIntegerBy, P.floor, P.logarithm, P.minus,
   2488    *                           P.modulo, P.negated, P.plus, P.round, P.sin, P.sinh, P.squareRoot,
   2489    *                           P.tan, P.times, P.toDecimalPlaces, P.toExponential, P.toFixed,
   2490    *                           P.toNearest, P.toPower, P.toPrecision, P.toSignificantDigits,
   2491    *                           P.truncated, divide, getLn10, getPi, naturalExponential,
   2492    *                           naturalLogarithm, ceil, floor, round, trunc
   2493    *  finiteToString           P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf,
   2494    *                           toStringBinary
   2495    *  getBase10Exponent        P.minus, P.plus, P.times, parseOther
   2496    *  getLn10                  P.logarithm, naturalLogarithm
   2497    *  getPi                    P.acos, P.asin, P.atan, toLessThanHalfPi, atan2
   2498    *  getPrecision             P.precision, P.toFraction
   2499    *  getZeroString            digitsToString, finiteToString
   2500    *  intPow                   P.toPower, parseOther
   2501    *  isOdd                    toLessThanHalfPi
   2502    *  maxOrMin                 max, min
   2503    *  naturalExponential       P.naturalExponential, P.toPower
   2504    *  naturalLogarithm         P.acosh, P.asinh, P.atanh, P.logarithm, P.naturalLogarithm,
   2505    *                           P.toPower, naturalExponential
   2506    *  nonFiniteToString        finiteToString, toStringBinary
   2507    *  parseDecimal             Decimal
   2508    *  parseOther               Decimal
   2509    *  sin                      P.sin
   2510    *  taylorSeries             P.cosh, P.sinh, cos, sin
   2511    *  toLessThanHalfPi         P.cos, P.sin
   2512    *  toStringBinary           P.toBinary, P.toHexadecimal, P.toOctal
   2513    *  truncate                 intPow
   2514    *
   2515    *  Throws:                  P.logarithm, P.precision, P.toFraction, checkInt32, getLn10, getPi,
   2516    *                           naturalLogarithm, config, parseOther, random, Decimal
   2517    */
   2518 
   2519 
   2520   function digitsToString(d) {
   2521     var i, k, ws,
   2522       indexOfLastWord = d.length - 1,
   2523       str = '',
   2524       w = d[0];
   2525 
   2526     if (indexOfLastWord > 0) {
   2527       str += w;
   2528       for (i = 1; i < indexOfLastWord; i++) {
   2529         ws = d[i] + '';
   2530         k = LOG_BASE - ws.length;
   2531         if (k) str += getZeroString(k);
   2532         str += ws;
   2533       }
   2534 
   2535       w = d[i];
   2536       ws = w + '';
   2537       k = LOG_BASE - ws.length;
   2538       if (k) str += getZeroString(k);
   2539     } else if (w === 0) {
   2540       return '0';
   2541     }
   2542 
   2543     // Remove trailing zeros of last w.
   2544     for (; w % 10 === 0;) w /= 10;
   2545 
   2546     return str + w;
   2547   }
   2548 
   2549 
   2550   function checkInt32(i, min, max) {
   2551     if (i !== ~~i || i < min || i > max) {
   2552       throw Error(invalidArgument + i);
   2553     }
   2554   }
   2555 
   2556 
   2557   /*
   2558    * Check 5 rounding digits if `repeating` is null, 4 otherwise.
   2559    * `repeating == null` if caller is `log` or `pow`,
   2560    * `repeating != null` if caller is `naturalLogarithm` or `naturalExponential`.
   2561    */
   2562   function checkRoundingDigits(d, i, rm, repeating) {
   2563     var di, k, r, rd;
   2564 
   2565     // Get the length of the first word of the array d.
   2566     for (k = d[0]; k >= 10; k /= 10) --i;
   2567 
   2568     // Is the rounding digit in the first word of d?
   2569     if (--i < 0) {
   2570       i += LOG_BASE;
   2571       di = 0;
   2572     } else {
   2573       di = Math.ceil((i + 1) / LOG_BASE);
   2574       i %= LOG_BASE;
   2575     }
   2576 
   2577     // i is the index (0 - 6) of the rounding digit.
   2578     // E.g. if within the word 3487563 the first rounding digit is 5,
   2579     // then i = 4, k = 1000, rd = 3487563 % 1000 = 563
   2580     k = mathpow(10, LOG_BASE - i);
   2581     rd = d[di] % k | 0;
   2582 
   2583     if (repeating == null) {
   2584       if (i < 3) {
   2585         if (i == 0) rd = rd / 100 | 0;
   2586         else if (i == 1) rd = rd / 10 | 0;
   2587         r = rm < 4 && rd == 99999 || rm > 3 && rd == 49999 || rd == 50000 || rd == 0;
   2588       } else {
   2589         r = (rm < 4 && rd + 1 == k || rm > 3 && rd + 1 == k / 2) &&
   2590           (d[di + 1] / k / 100 | 0) == mathpow(10, i - 2) - 1 ||
   2591             (rd == k / 2 || rd == 0) && (d[di + 1] / k / 100 | 0) == 0;
   2592       }
   2593     } else {
   2594       if (i < 4) {
   2595         if (i == 0) rd = rd / 1000 | 0;
   2596         else if (i == 1) rd = rd / 100 | 0;
   2597         else if (i == 2) rd = rd / 10 | 0;
   2598         r = (repeating || rm < 4) && rd == 9999 || !repeating && rm > 3 && rd == 4999;
   2599       } else {
   2600         r = ((repeating || rm < 4) && rd + 1 == k ||
   2601         (!repeating && rm > 3) && rd + 1 == k / 2) &&
   2602           (d[di + 1] / k / 1000 | 0) == mathpow(10, i - 3) - 1;
   2603       }
   2604     }
   2605 
   2606     return r;
   2607   }
   2608 
   2609 
   2610   // Convert string of `baseIn` to an array of numbers of `baseOut`.
   2611   // Eg. convertBase('255', 10, 16) returns [15, 15].
   2612   // Eg. convertBase('ff', 16, 10) returns [2, 5, 5].
   2613   function convertBase(str, baseIn, baseOut) {
   2614     var j,
   2615       arr = [0],
   2616       arrL,
   2617       i = 0,
   2618       strL = str.length;
   2619 
   2620     for (; i < strL;) {
   2621       for (arrL = arr.length; arrL--;) arr[arrL] *= baseIn;
   2622       arr[0] += NUMERALS.indexOf(str.charAt(i++));
   2623       for (j = 0; j < arr.length; j++) {
   2624         if (arr[j] > baseOut - 1) {
   2625           if (arr[j + 1] === void 0) arr[j + 1] = 0;
   2626           arr[j + 1] += arr[j] / baseOut | 0;
   2627           arr[j] %= baseOut;
   2628         }
   2629       }
   2630     }
   2631 
   2632     return arr.reverse();
   2633   }
   2634 
   2635 
   2636   /*
   2637    * cos(x) = 1 - x^2/2! + x^4/4! - ...
   2638    * |x| < pi/2
   2639    *
   2640    */
   2641   function cosine(Ctor, x) {
   2642     var k, len, y;
   2643 
   2644     if (x.isZero()) return x;
   2645 
   2646     // Argument reduction: cos(4x) = 8*(cos^4(x) - cos^2(x)) + 1
   2647     // i.e. cos(x) = 8*(cos^4(x/4) - cos^2(x/4)) + 1
   2648 
   2649     // Estimate the optimum number of times to use the argument reduction.
   2650     len = x.d.length;
   2651     if (len < 32) {
   2652       k = Math.ceil(len / 3);
   2653       y = (1 / tinyPow(4, k)).toString();
   2654     } else {
   2655       k = 16;
   2656       y = '2.3283064365386962890625e-10';
   2657     }
   2658 
   2659     Ctor.precision += k;
   2660 
   2661     x = taylorSeries(Ctor, 1, x.times(y), new Ctor(1));
   2662 
   2663     // Reverse argument reduction
   2664     for (var i = k; i--;) {
   2665       var cos2x = x.times(x);
   2666       x = cos2x.times(cos2x).minus(cos2x).times(8).plus(1);
   2667     }
   2668 
   2669     Ctor.precision -= k;
   2670 
   2671     return x;
   2672   }
   2673 
   2674 
   2675   /*
   2676    * Perform division in the specified base.
   2677    */
   2678   var divide = (function () {
   2679 
   2680     // Assumes non-zero x and k, and hence non-zero result.
   2681     function multiplyInteger(x, k, base) {
   2682       var temp,
   2683         carry = 0,
   2684         i = x.length;
   2685 
   2686       for (x = x.slice(); i--;) {
   2687         temp = x[i] * k + carry;
   2688         x[i] = temp % base | 0;
   2689         carry = temp / base | 0;
   2690       }
   2691 
   2692       if (carry) x.unshift(carry);
   2693 
   2694       return x;
   2695     }
   2696 
   2697     function compare(a, b, aL, bL) {
   2698       var i, r;
   2699 
   2700       if (aL != bL) {
   2701         r = aL > bL ? 1 : -1;
   2702       } else {
   2703         for (i = r = 0; i < aL; i++) {
   2704           if (a[i] != b[i]) {
   2705             r = a[i] > b[i] ? 1 : -1;
   2706             break;
   2707           }
   2708         }
   2709       }
   2710 
   2711       return r;
   2712     }
   2713 
   2714     function subtract(a, b, aL, base) {
   2715       var i = 0;
   2716 
   2717       // Subtract b from a.
   2718       for (; aL--;) {
   2719         a[aL] -= i;
   2720         i = a[aL] < b[aL] ? 1 : 0;
   2721         a[aL] = i * base + a[aL] - b[aL];
   2722       }
   2723 
   2724       // Remove leading zeros.
   2725       for (; !a[0] && a.length > 1;) a.shift();
   2726     }
   2727 
   2728     return function (x, y, pr, rm, dp, base) {
   2729       var cmp, e, i, k, logBase, more, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0,
   2730         yL, yz,
   2731         Ctor = x.constructor,
   2732         sign = x.s == y.s ? 1 : -1,
   2733         xd = x.d,
   2734         yd = y.d;
   2735 
   2736       // Either NaN, Infinity or 0?
   2737       if (!xd || !xd[0] || !yd || !yd[0]) {
   2738 
   2739         return new Ctor(// Return NaN if either NaN, or both Infinity or 0.
   2740           !x.s || !y.s || (xd ? yd && xd[0] == yd[0] : !yd) ? NaN :
   2741 
   2742           // Return ±0 if x is 0 or y is ±Infinity, or return ±Infinity as y is 0.
   2743           xd && xd[0] == 0 || !yd ? sign * 0 : sign / 0);
   2744       }
   2745 
   2746       if (base) {
   2747         logBase = 1;
   2748         e = x.e - y.e;
   2749       } else {
   2750         base = BASE;
   2751         logBase = LOG_BASE;
   2752         e = mathfloor(x.e / logBase) - mathfloor(y.e / logBase);
   2753       }
   2754 
   2755       yL = yd.length;
   2756       xL = xd.length;
   2757       q = new Ctor(sign);
   2758       qd = q.d = [];
   2759 
   2760       // Result exponent may be one less than e.
   2761       // The digit array of a Decimal from toStringBinary may have trailing zeros.
   2762       for (i = 0; yd[i] == (xd[i] || 0); i++);
   2763 
   2764       if (yd[i] > (xd[i] || 0)) e--;
   2765 
   2766       if (pr == null) {
   2767         sd = pr = Ctor.precision;
   2768         rm = Ctor.rounding;
   2769       } else if (dp) {
   2770         sd = pr + (x.e - y.e) + 1;
   2771       } else {
   2772         sd = pr;
   2773       }
   2774 
   2775       if (sd < 0) {
   2776         qd.push(1);
   2777         more = true;
   2778       } else {
   2779 
   2780         // Convert precision in number of base 10 digits to base 1e7 digits.
   2781         sd = sd / logBase + 2 | 0;
   2782         i = 0;
   2783 
   2784         // divisor < 1e7
   2785         if (yL == 1) {
   2786           k = 0;
   2787           yd = yd[0];
   2788           sd++;
   2789 
   2790           // k is the carry.
   2791           for (; (i < xL || k) && sd--; i++) {
   2792             t = k * base + (xd[i] || 0);
   2793             qd[i] = t / yd | 0;
   2794             k = t % yd | 0;
   2795           }
   2796 
   2797           more = k || i < xL;
   2798 
   2799         // divisor >= 1e7
   2800         } else {
   2801 
   2802           // Normalise xd and yd so highest order digit of yd is >= base/2
   2803           k = base / (yd[0] + 1) | 0;
   2804 
   2805           if (k > 1) {
   2806             yd = multiplyInteger(yd, k, base);
   2807             xd = multiplyInteger(xd, k, base);
   2808             yL = yd.length;
   2809             xL = xd.length;
   2810           }
   2811 
   2812           xi = yL;
   2813           rem = xd.slice(0, yL);
   2814           remL = rem.length;
   2815 
   2816           // Add zeros to make remainder as long as divisor.
   2817           for (; remL < yL;) rem[remL++] = 0;
   2818 
   2819           yz = yd.slice();
   2820           yz.unshift(0);
   2821           yd0 = yd[0];
   2822 
   2823           if (yd[1] >= base / 2) ++yd0;
   2824 
   2825           do {
   2826             k = 0;
   2827 
   2828             // Compare divisor and remainder.
   2829             cmp = compare(yd, rem, yL, remL);
   2830 
   2831             // If divisor < remainder.
   2832             if (cmp < 0) {
   2833 
   2834               // Calculate trial digit, k.
   2835               rem0 = rem[0];
   2836               if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);
   2837 
   2838               // k will be how many times the divisor goes into the current remainder.
   2839               k = rem0 / yd0 | 0;
   2840 
   2841               //  Algorithm:
   2842               //  1. product = divisor * trial digit (k)
   2843               //  2. if product > remainder: product -= divisor, k--
   2844               //  3. remainder -= product
   2845               //  4. if product was < remainder at 2:
   2846               //    5. compare new remainder and divisor
   2847               //    6. If remainder > divisor: remainder -= divisor, k++
   2848 
   2849               if (k > 1) {
   2850                 if (k >= base) k = base - 1;
   2851 
   2852                 // product = divisor * trial digit.
   2853                 prod = multiplyInteger(yd, k, base);
   2854                 prodL = prod.length;
   2855                 remL = rem.length;
   2856 
   2857                 // Compare product and remainder.
   2858                 cmp = compare(prod, rem, prodL, remL);
   2859 
   2860                 // product > remainder.
   2861                 if (cmp == 1) {
   2862                   k--;
   2863 
   2864                   // Subtract divisor from product.
   2865                   subtract(prod, yL < prodL ? yz : yd, prodL, base);
   2866                 }
   2867               } else {
   2868 
   2869                 // cmp is -1.
   2870                 // If k is 0, there is no need to compare yd and rem again below, so change cmp to 1
   2871                 // to avoid it. If k is 1 there is a need to compare yd and rem again below.
   2872                 if (k == 0) cmp = k = 1;
   2873                 prod = yd.slice();
   2874               }
   2875 
   2876               prodL = prod.length;
   2877               if (prodL < remL) prod.unshift(0);
   2878 
   2879               // Subtract product from remainder.
   2880               subtract(rem, prod, remL, base);
   2881 
   2882               // If product was < previous remainder.
   2883               if (cmp == -1) {
   2884                 remL = rem.length;
   2885 
   2886                 // Compare divisor and new remainder.
   2887                 cmp = compare(yd, rem, yL, remL);
   2888 
   2889                 // If divisor < new remainder, subtract divisor from remainder.
   2890                 if (cmp < 1) {
   2891                   k++;
   2892 
   2893                   // Subtract divisor from remainder.
   2894                   subtract(rem, yL < remL ? yz : yd, remL, base);
   2895                 }
   2896               }
   2897 
   2898               remL = rem.length;
   2899             } else if (cmp === 0) {
   2900               k++;
   2901               rem = [0];
   2902             }    // if cmp === 1, k will be 0
   2903 
   2904             // Add the next digit, k, to the result array.
   2905             qd[i++] = k;
   2906 
   2907             // Update the remainder.
   2908             if (cmp && rem[0]) {
   2909               rem[remL++] = xd[xi] || 0;
   2910             } else {
   2911               rem = [xd[xi]];
   2912               remL = 1;
   2913             }
   2914 
   2915           } while ((xi++ < xL || rem[0] !== void 0) && sd--);
   2916 
   2917           more = rem[0] !== void 0;
   2918         }
   2919 
   2920         // Leading zero?
   2921         if (!qd[0]) qd.shift();
   2922       }
   2923 
   2924       // logBase is 1 when divide is being used for base conversion.
   2925       if (logBase == 1) {
   2926         q.e = e;
   2927         inexact = more;
   2928       } else {
   2929 
   2930         // To calculate q.e, first get the number of digits of qd[0].
   2931         for (i = 1, k = qd[0]; k >= 10; k /= 10) i++;
   2932         q.e = i + e * logBase - 1;
   2933 
   2934         finalise(q, dp ? pr + q.e + 1 : pr, rm, more);
   2935       }
   2936 
   2937       return q;
   2938     };
   2939   })();
   2940 
   2941 
   2942   /*
   2943    * Round `x` to `sd` significant digits using rounding mode `rm`.
   2944    * Check for over/under-flow.
   2945    */
   2946    function finalise(x, sd, rm, isTruncated) {
   2947     var digits, i, j, k, rd, roundUp, w, xd, xdi,
   2948       Ctor = x.constructor;
   2949 
   2950     // Don't round if sd is null or undefined.
   2951     out: if (sd != null) {
   2952       xd = x.d;
   2953 
   2954       // Infinity/NaN.
   2955       if (!xd) return x;
   2956 
   2957       // rd: the rounding digit, i.e. the digit after the digit that may be rounded up.
   2958       // w: the word of xd containing rd, a base 1e7 number.
   2959       // xdi: the index of w within xd.
   2960       // digits: the number of digits of w.
   2961       // i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if
   2962       // they had leading zeros)
   2963       // j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero).
   2964 
   2965       // Get the length of the first word of the digits array xd.
   2966       for (digits = 1, k = xd[0]; k >= 10; k /= 10) digits++;
   2967       i = sd - digits;
   2968 
   2969       // Is the rounding digit in the first word of xd?
   2970       if (i < 0) {
   2971         i += LOG_BASE;
   2972         j = sd;
   2973         w = xd[xdi = 0];
   2974 
   2975         // Get the rounding digit at index j of w.
   2976         rd = w / mathpow(10, digits - j - 1) % 10 | 0;
   2977       } else {
   2978         xdi = Math.ceil((i + 1) / LOG_BASE);
   2979         k = xd.length;
   2980         if (xdi >= k) {
   2981           if (isTruncated) {
   2982 
   2983             // Needed by `naturalExponential`, `naturalLogarithm` and `squareRoot`.
   2984             for (; k++ <= xdi;) xd.push(0);
   2985             w = rd = 0;
   2986             digits = 1;
   2987             i %= LOG_BASE;
   2988             j = i - LOG_BASE + 1;
   2989           } else {
   2990             break out;
   2991           }
   2992         } else {
   2993           w = k = xd[xdi];
   2994 
   2995           // Get the number of digits of w.
   2996           for (digits = 1; k >= 10; k /= 10) digits++;
   2997 
   2998           // Get the index of rd within w.
   2999           i %= LOG_BASE;
   3000 
   3001           // Get the index of rd within w, adjusted for leading zeros.
   3002           // The number of leading zeros of w is given by LOG_BASE - digits.
   3003           j = i - LOG_BASE + digits;
   3004 
   3005           // Get the rounding digit at index j of w.
   3006           rd = j < 0 ? 0 : w / mathpow(10, digits - j - 1) % 10 | 0;
   3007         }
   3008       }
   3009 
   3010       // Are there any non-zero digits after the rounding digit?
   3011       isTruncated = isTruncated || sd < 0 ||
   3012         xd[xdi + 1] !== void 0 || (j < 0 ? w : w % mathpow(10, digits - j - 1));
   3013 
   3014       // The expression `w % mathpow(10, digits - j - 1)` returns all the digits of w to the right
   3015       // of the digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression
   3016       // will give 714.
   3017 
   3018       roundUp = rm < 4
   3019         ? (rd || isTruncated) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))
   3020         : rd > 5 || rd == 5 && (rm == 4 || isTruncated || rm == 6 &&
   3021 
   3022           // Check whether the digit to the left of the rounding digit is odd.
   3023           ((i > 0 ? j > 0 ? w / mathpow(10, digits - j) : 0 : xd[xdi - 1]) % 10) & 1 ||
   3024             rm == (x.s < 0 ? 8 : 7));
   3025 
   3026       if (sd < 1 || !xd[0]) {
   3027         xd.length = 0;
   3028         if (roundUp) {
   3029 
   3030           // Convert sd to decimal places.
   3031           sd -= x.e + 1;
   3032 
   3033           // 1, 0.1, 0.01, 0.001, 0.0001 etc.
   3034           xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE);
   3035           x.e = -sd || 0;
   3036         } else {
   3037 
   3038           // Zero.
   3039           xd[0] = x.e = 0;
   3040         }
   3041 
   3042         return x;
   3043       }
   3044 
   3045       // Remove excess digits.
   3046       if (i == 0) {
   3047         xd.length = xdi;
   3048         k = 1;
   3049         xdi--;
   3050       } else {
   3051         xd.length = xdi + 1;
   3052         k = mathpow(10, LOG_BASE - i);
   3053 
   3054         // E.g. 56700 becomes 56000 if 7 is the rounding digit.
   3055         // j > 0 means i > number of leading zeros of w.
   3056         xd[xdi] = j > 0 ? (w / mathpow(10, digits - j) % mathpow(10, j) | 0) * k : 0;
   3057       }
   3058 
   3059       if (roundUp) {
   3060         for (;;) {
   3061 
   3062           // Is the digit to be rounded up in the first word of xd?
   3063           if (xdi == 0) {
   3064 
   3065             // i will be the length of xd[0] before k is added.
   3066             for (i = 1, j = xd[0]; j >= 10; j /= 10) i++;
   3067             j = xd[0] += k;
   3068             for (k = 1; j >= 10; j /= 10) k++;
   3069 
   3070             // if i != k the length has increased.
   3071             if (i != k) {
   3072               x.e++;
   3073               if (xd[0] == BASE) xd[0] = 1;
   3074             }
   3075 
   3076             break;
   3077           } else {
   3078             xd[xdi] += k;
   3079             if (xd[xdi] != BASE) break;
   3080             xd[xdi--] = 0;
   3081             k = 1;
   3082           }
   3083         }
   3084       }
   3085 
   3086       // Remove trailing zeros.
   3087       for (i = xd.length; xd[--i] === 0;) xd.pop();
   3088     }
   3089 
   3090     if (external) {
   3091 
   3092       // Overflow?
   3093       if (x.e > Ctor.maxE) {
   3094 
   3095         // Infinity.
   3096         x.d = null;
   3097         x.e = NaN;
   3098 
   3099       // Underflow?
   3100       } else if (x.e < Ctor.minE) {
   3101 
   3102         // Zero.
   3103         x.e = 0;
   3104         x.d = [0];
   3105         // Ctor.underflow = true;
   3106       } // else Ctor.underflow = false;
   3107     }
   3108 
   3109     return x;
   3110   }
   3111 
   3112 
   3113   function finiteToString(x, isExp, sd) {
   3114     if (!x.isFinite()) return nonFiniteToString(x);
   3115     var k,
   3116       e = x.e,
   3117       str = digitsToString(x.d),
   3118       len = str.length;
   3119 
   3120     if (isExp) {
   3121       if (sd && (k = sd - len) > 0) {
   3122         str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k);
   3123       } else if (len > 1) {
   3124         str = str.charAt(0) + '.' + str.slice(1);
   3125       }
   3126 
   3127       str = str + (x.e < 0 ? 'e' : 'e+') + x.e;
   3128     } else if (e < 0) {
   3129       str = '0.' + getZeroString(-e - 1) + str;
   3130       if (sd && (k = sd - len) > 0) str += getZeroString(k);
   3131     } else if (e >= len) {
   3132       str += getZeroString(e + 1 - len);
   3133       if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k);
   3134     } else {
   3135       if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k);
   3136       if (sd && (k = sd - len) > 0) {
   3137         if (e + 1 === len) str += '.';
   3138         str += getZeroString(k);
   3139       }
   3140     }
   3141 
   3142     return str;
   3143   }
   3144 
   3145 
   3146   // Calculate the base 10 exponent from the base 1e7 exponent.
   3147   function getBase10Exponent(digits, e) {
   3148     var w = digits[0];
   3149 
   3150     // Add the number of digits of the first word of the digits array.
   3151     for ( e *= LOG_BASE; w >= 10; w /= 10) e++;
   3152     return e;
   3153   }
   3154 
   3155 
   3156   function getLn10(Ctor, sd, pr) {
   3157     if (sd > LN10_PRECISION) {
   3158 
   3159       // Reset global state in case the exception is caught.
   3160       external = true;
   3161       if (pr) Ctor.precision = pr;
   3162       throw Error(precisionLimitExceeded);
   3163     }
   3164     return finalise(new Ctor(LN10), sd, 1, true);
   3165   }
   3166 
   3167 
   3168   function getPi(Ctor, sd, rm) {
   3169     if (sd > PI_PRECISION) throw Error(precisionLimitExceeded);
   3170     return finalise(new Ctor(PI), sd, rm, true);
   3171   }
   3172 
   3173 
   3174   function getPrecision(digits) {
   3175     var w = digits.length - 1,
   3176       len = w * LOG_BASE + 1;
   3177 
   3178     w = digits[w];
   3179 
   3180     // If non-zero...
   3181     if (w) {
   3182 
   3183       // Subtract the number of trailing zeros of the last word.
   3184       for (; w % 10 == 0; w /= 10) len--;
   3185 
   3186       // Add the number of digits of the first word.
   3187       for (w = digits[0]; w >= 10; w /= 10) len++;
   3188     }
   3189 
   3190     return len;
   3191   }
   3192 
   3193 
   3194   function getZeroString(k) {
   3195     var zs = '';
   3196     for (; k--;) zs += '0';
   3197     return zs;
   3198   }
   3199 
   3200 
   3201   /*
   3202    * Return a new Decimal whose value is the value of Decimal `x` to the power `n`, where `n` is an
   3203    * integer of type number.
   3204    *
   3205    * Implements 'exponentiation by squaring'. Called by `pow` and `parseOther`.
   3206    *
   3207    */
   3208   function intPow(Ctor, x, n, pr) {
   3209     var isTruncated,
   3210       r = new Ctor(1),
   3211 
   3212       // Max n of 9007199254740991 takes 53 loop iterations.
   3213       // Maximum digits array length; leaves [28, 34] guard digits.
   3214       k = Math.ceil(pr / LOG_BASE + 4);
   3215 
   3216     external = false;
   3217 
   3218     for (;;) {
   3219       if (n % 2) {
   3220         r = r.times(x);
   3221         if (truncate(r.d, k)) isTruncated = true;
   3222       }
   3223 
   3224       n = mathfloor(n / 2);
   3225       if (n === 0) {
   3226 
   3227         // To ensure correct rounding when r.d is truncated, increment the last word if it is zero.
   3228         n = r.d.length - 1;
   3229         if (isTruncated && r.d[n] === 0) ++r.d[n];
   3230         break;
   3231       }
   3232 
   3233       x = x.times(x);
   3234       truncate(x.d, k);
   3235     }
   3236 
   3237     external = true;
   3238 
   3239     return r;
   3240   }
   3241 
   3242 
   3243   function isOdd(n) {
   3244     return n.d[n.d.length - 1] & 1;
   3245   }
   3246 
   3247 
   3248   /*
   3249    * Handle `max` and `min`. `ltgt` is 'lt' or 'gt'.
   3250    */
   3251   function maxOrMin(Ctor, args, ltgt) {
   3252     var y,
   3253       x = new Ctor(args[0]),
   3254       i = 0;
   3255 
   3256     for (; ++i < args.length;) {
   3257       y = new Ctor(args[i]);
   3258       if (!y.s) {
   3259         x = y;
   3260         break;
   3261       } else if (x[ltgt](y)) {
   3262         x = y;
   3263       }
   3264     }
   3265 
   3266     return x;
   3267   }
   3268 
   3269 
   3270   /*
   3271    * Return a new Decimal whose value is the natural exponential of `x` rounded to `sd` significant
   3272    * digits.
   3273    *
   3274    * Taylor/Maclaurin series.
   3275    *
   3276    * exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ...
   3277    *
   3278    * Argument reduction:
   3279    *   Repeat x = x / 32, k += 5, until |x| < 0.1
   3280    *   exp(x) = exp(x / 2^k)^(2^k)
   3281    *
   3282    * Previously, the argument was initially reduced by
   3283    * exp(x) = exp(r) * 10^k  where r = x - k * ln10, k = floor(x / ln10)
   3284    * to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was
   3285    * found to be slower than just dividing repeatedly by 32 as above.
   3286    *
   3287    * Max integer argument: exp('20723265836946413') = 6.3e+9000000000000000
   3288    * Min integer argument: exp('-20723265836946411') = 1.2e-9000000000000000
   3289    * (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324)
   3290    *
   3291    *  exp(Infinity)  = Infinity
   3292    *  exp(-Infinity) = 0
   3293    *  exp(NaN)       = NaN
   3294    *  exp(±0)        = 1
   3295    *
   3296    *  exp(x) is non-terminating for any finite, non-zero x.
   3297    *
   3298    *  The result will always be correctly rounded.
   3299    *
   3300    */
   3301   function naturalExponential(x, sd) {
   3302     var denominator, guard, j, pow, sum, t, wpr,
   3303       rep = 0,
   3304       i = 0,
   3305       k = 0,
   3306       Ctor = x.constructor,
   3307       rm = Ctor.rounding,
   3308       pr = Ctor.precision;
   3309 
   3310     // 0/NaN/Infinity?
   3311     if (!x.d || !x.d[0] || x.e > 17) {
   3312 
   3313       return new Ctor(x.d
   3314         ? !x.d[0] ? 1 : x.s < 0 ? 0 : 1 / 0
   3315         : x.s ? x.s < 0 ? 0 : x : 0 / 0);
   3316     }
   3317 
   3318     if (sd == null) {
   3319       external = false;
   3320       wpr = pr;
   3321     } else {
   3322       wpr = sd;
   3323     }
   3324 
   3325     t = new Ctor(0.03125);
   3326 
   3327     // while abs(x) >= 0.1
   3328     while (x.e > -2) {
   3329 
   3330       // x = x / 2^5
   3331       x = x.times(t);
   3332       k += 5;
   3333     }
   3334 
   3335     // Use 2 * log10(2^k) + 5 (empirically derived) to estimate the increase in precision
   3336     // necessary to ensure the first 4 rounding digits are correct.
   3337     guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0;
   3338     wpr += guard;
   3339     denominator = pow = sum = new Ctor(1);
   3340     Ctor.precision = wpr;
   3341 
   3342     for (;;) {
   3343       pow = finalise(pow.times(x), wpr, 1);
   3344       denominator = denominator.times(++i);
   3345       t = sum.plus(divide(pow, denominator, wpr, 1));
   3346 
   3347       if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
   3348         j = k;
   3349         while (j--) sum = finalise(sum.times(sum), wpr, 1);
   3350 
   3351         // Check to see if the first 4 rounding digits are [49]999.
   3352         // If so, repeat the summation with a higher precision, otherwise
   3353         // e.g. with precision: 18, rounding: 1
   3354         // exp(18.404272462595034083567793919843761) = 98372560.1229999999 (should be 98372560.123)
   3355         // `wpr - guard` is the index of first rounding digit.
   3356         if (sd == null) {
   3357 
   3358           if (rep < 3 && checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {
   3359             Ctor.precision = wpr += 10;
   3360             denominator = pow = t = new Ctor(1);
   3361             i = 0;
   3362             rep++;
   3363           } else {
   3364             return finalise(sum, Ctor.precision = pr, rm, external = true);
   3365           }
   3366         } else {
   3367           Ctor.precision = pr;
   3368           return sum;
   3369         }
   3370       }
   3371 
   3372       sum = t;
   3373     }
   3374   }
   3375 
   3376 
   3377   /*
   3378    * Return a new Decimal whose value is the natural logarithm of `x` rounded to `sd` significant
   3379    * digits.
   3380    *
   3381    *  ln(-n)        = NaN
   3382    *  ln(0)         = -Infinity
   3383    *  ln(-0)        = -Infinity
   3384    *  ln(1)         = 0
   3385    *  ln(Infinity)  = Infinity
   3386    *  ln(-Infinity) = NaN
   3387    *  ln(NaN)       = NaN
   3388    *
   3389    *  ln(n) (n != 1) is non-terminating.
   3390    *
   3391    */
   3392   function naturalLogarithm(y, sd) {
   3393     var c, c0, denominator, e, numerator, rep, sum, t, wpr, x1, x2,
   3394       n = 1,
   3395       guard = 10,
   3396       x = y,
   3397       xd = x.d,
   3398       Ctor = x.constructor,
   3399       rm = Ctor.rounding,
   3400       pr = Ctor.precision;
   3401 
   3402     // Is x negative or Infinity, NaN, 0 or 1?
   3403     if (x.s < 0 || !xd || !xd[0] || !x.e && xd[0] == 1 && xd.length == 1) {
   3404       return new Ctor(xd && !xd[0] ? -1 / 0 : x.s != 1 ? NaN : xd ? 0 : x);
   3405     }
   3406 
   3407     if (sd == null) {
   3408       external = false;
   3409       wpr = pr;
   3410     } else {
   3411       wpr = sd;
   3412     }
   3413 
   3414     Ctor.precision = wpr += guard;
   3415     c = digitsToString(xd);
   3416     c0 = c.charAt(0);
   3417 
   3418     if (Math.abs(e = x.e) < 1.5e15) {
   3419 
   3420       // Argument reduction.
   3421       // The series converges faster the closer the argument is to 1, so using
   3422       // ln(a^b) = b * ln(a),   ln(a) = ln(a^b) / b
   3423       // multiply the argument by itself until the leading digits of the significand are 7, 8, 9,
   3424       // 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can
   3425       // later be divided by this number, then separate out the power of 10 using
   3426       // ln(a*10^b) = ln(a) + b*ln(10).
   3427 
   3428       // max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14).
   3429       //while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) {
   3430       // max n is 6 (gives 0.7 - 1.3)
   3431       while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) {
   3432         x = x.times(y);
   3433         c = digitsToString(x.d);
   3434         c0 = c.charAt(0);
   3435         n++;
   3436       }
   3437 
   3438       e = x.e;
   3439 
   3440       if (c0 > 1) {
   3441         x = new Ctor('0.' + c);
   3442         e++;
   3443       } else {
   3444         x = new Ctor(c0 + '.' + c.slice(1));
   3445       }
   3446     } else {
   3447 
   3448       // The argument reduction method above may result in overflow if the argument y is a massive
   3449       // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this
   3450       // function using ln(x*10^e) = ln(x) + e*ln(10).
   3451       t = getLn10(Ctor, wpr + 2, pr).times(e + '');
   3452       x = naturalLogarithm(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t);
   3453       Ctor.precision = pr;
   3454 
   3455       return sd == null ? finalise(x, pr, rm, external = true) : x;
   3456     }
   3457 
   3458     // x1 is x reduced to a value near 1.
   3459     x1 = x;
   3460 
   3461     // Taylor series.
   3462     // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...)
   3463     // where x = (y - 1)/(y + 1)    (|x| < 1)
   3464     sum = numerator = x = divide(x.minus(1), x.plus(1), wpr, 1);
   3465     x2 = finalise(x.times(x), wpr, 1);
   3466     denominator = 3;
   3467 
   3468     for (;;) {
   3469       numerator = finalise(numerator.times(x2), wpr, 1);
   3470       t = sum.plus(divide(numerator, new Ctor(denominator), wpr, 1));
   3471 
   3472       if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
   3473         sum = sum.times(2);
   3474 
   3475         // Reverse the argument reduction. Check that e is not 0 because, besides preventing an
   3476         // unnecessary calculation, -0 + 0 = +0 and to ensure correct rounding -0 needs to stay -0.
   3477         if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + ''));
   3478         sum = divide(sum, new Ctor(n), wpr, 1);
   3479 
   3480         // Is rm > 3 and the first 4 rounding digits 4999, or rm < 4 (or the summation has
   3481         // been repeated previously) and the first 4 rounding digits 9999?
   3482         // If so, restart the summation with a higher precision, otherwise
   3483         // e.g. with precision: 12, rounding: 1
   3484         // ln(135520028.6126091714265381533) = 18.7246299999 when it should be 18.72463.
   3485         // `wpr - guard` is the index of first rounding digit.
   3486         if (sd == null) {
   3487           if (checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {
   3488             Ctor.precision = wpr += guard;
   3489             t = numerator = x = divide(x1.minus(1), x1.plus(1), wpr, 1);
   3490             x2 = finalise(x.times(x), wpr, 1);
   3491             denominator = rep = 1;
   3492           } else {
   3493             return finalise(sum, Ctor.precision = pr, rm, external = true);
   3494           }
   3495         } else {
   3496           Ctor.precision = pr;
   3497           return sum;
   3498         }
   3499       }
   3500 
   3501       sum = t;
   3502       denominator += 2;
   3503     }
   3504   }
   3505 
   3506 
   3507   // ±Infinity, NaN.
   3508   function nonFiniteToString(x) {
   3509     // Unsigned.
   3510     return String(x.s * x.s / 0);
   3511   }
   3512 
   3513 
   3514   /*
   3515    * Parse the value of a new Decimal `x` from string `str`.
   3516    */
   3517   function parseDecimal(x, str) {
   3518     var e, i, len;
   3519 
   3520     // Decimal point?
   3521     if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');
   3522 
   3523     // Exponential form?
   3524     if ((i = str.search(/e/i)) > 0) {
   3525 
   3526       // Determine exponent.
   3527       if (e < 0) e = i;
   3528       e += +str.slice(i + 1);
   3529       str = str.substring(0, i);
   3530     } else if (e < 0) {
   3531 
   3532       // Integer.
   3533       e = str.length;
   3534     }
   3535 
   3536     // Determine leading zeros.
   3537     for (i = 0; str.charCodeAt(i) === 48; i++);
   3538 
   3539     // Determine trailing zeros.
   3540     for (len = str.length; str.charCodeAt(len - 1) === 48; --len);
   3541     str = str.slice(i, len);
   3542 
   3543     if (str) {
   3544       len -= i;
   3545       x.e = e = e - i - 1;
   3546       x.d = [];
   3547 
   3548       // Transform base
   3549 
   3550       // e is the base 10 exponent.
   3551       // i is where to slice str to get the first word of the digits array.
   3552       i = (e + 1) % LOG_BASE;
   3553       if (e < 0) i += LOG_BASE;
   3554 
   3555       if (i < len) {
   3556         if (i) x.d.push(+str.slice(0, i));
   3557         for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE));
   3558         str = str.slice(i);
   3559         i = LOG_BASE - str.length;
   3560       } else {
   3561         i -= len;
   3562       }
   3563 
   3564       for (; i--;) str += '0';
   3565       x.d.push(+str);
   3566 
   3567       if (external) {
   3568 
   3569         // Overflow?
   3570         if (x.e > x.constructor.maxE) {
   3571 
   3572           // Infinity.
   3573           x.d = null;
   3574           x.e = NaN;
   3575 
   3576         // Underflow?
   3577         } else if (x.e < x.constructor.minE) {
   3578 
   3579           // Zero.
   3580           x.e = 0;
   3581           x.d = [0];
   3582           // x.constructor.underflow = true;
   3583         } // else x.constructor.underflow = false;
   3584       }
   3585     } else {
   3586 
   3587       // Zero.
   3588       x.e = 0;
   3589       x.d = [0];
   3590     }
   3591 
   3592     return x;
   3593   }
   3594 
   3595 
   3596   /*
   3597    * Parse the value of a new Decimal `x` from a string `str`, which is not a decimal value.
   3598    */
   3599   function parseOther(x, str) {
   3600     var base, Ctor, divisor, i, isFloat, len, p, xd, xe;
   3601 
   3602     if (str.indexOf('_') > -1) {
   3603       str = str.replace(/(\d)_(?=\d)/g, '$1');
   3604       if (isDecimal.test(str)) return parseDecimal(x, str);
   3605     } else if (str === 'Infinity' || str === 'NaN') {
   3606       if (!+str) x.s = NaN;
   3607       x.e = NaN;
   3608       x.d = null;
   3609       return x;
   3610     }
   3611 
   3612     if (isHex.test(str))  {
   3613       base = 16;
   3614       str = str.toLowerCase();
   3615     } else if (isBinary.test(str))  {
   3616       base = 2;
   3617     } else if (isOctal.test(str))  {
   3618       base = 8;
   3619     } else {
   3620       throw Error(invalidArgument + str);
   3621     }
   3622 
   3623     // Is there a binary exponent part?
   3624     i = str.search(/p/i);
   3625 
   3626     if (i > 0) {
   3627       p = +str.slice(i + 1);
   3628       str = str.substring(2, i);
   3629     } else {
   3630       str = str.slice(2);
   3631     }
   3632 
   3633     // Convert `str` as an integer then divide the result by `base` raised to a power such that the
   3634     // fraction part will be restored.
   3635     i = str.indexOf('.');
   3636     isFloat = i >= 0;
   3637     Ctor = x.constructor;
   3638 
   3639     if (isFloat) {
   3640       str = str.replace('.', '');
   3641       len = str.length;
   3642       i = len - i;
   3643 
   3644       // log[10](16) = 1.2041... , log[10](88) = 1.9444....
   3645       divisor = intPow(Ctor, new Ctor(base), i, i * 2);
   3646     }
   3647 
   3648     xd = convertBase(str, base, BASE);
   3649     xe = xd.length - 1;
   3650 
   3651     // Remove trailing zeros.
   3652     for (i = xe; xd[i] === 0; --i) xd.pop();
   3653     if (i < 0) return new Ctor(x.s * 0);
   3654     x.e = getBase10Exponent(xd, xe);
   3655     x.d = xd;
   3656     external = false;
   3657 
   3658     // At what precision to perform the division to ensure exact conversion?
   3659     // maxDecimalIntegerPartDigitCount = ceil(log[10](b) * otherBaseIntegerPartDigitCount)
   3660     // log[10](2) = 0.30103, log[10](8) = 0.90309, log[10](16) = 1.20412
   3661     // E.g. ceil(1.2 * 3) = 4, so up to 4 decimal digits are needed to represent 3 hex int digits.
   3662     // maxDecimalFractionPartDigitCount = {Hex:4|Oct:3|Bin:1} * otherBaseFractionPartDigitCount
   3663     // Therefore using 4 * the number of digits of str will always be enough.
   3664     if (isFloat) x = divide(x, divisor, len * 4);
   3665 
   3666     // Multiply by the binary exponent part if present.
   3667     if (p) x = x.times(Math.abs(p) < 54 ? mathpow(2, p) : Decimal.pow(2, p));
   3668     external = true;
   3669 
   3670     return x;
   3671   }
   3672 
   3673 
   3674   /*
   3675    * sin(x) = x - x^3/3! + x^5/5! - ...
   3676    * |x| < pi/2
   3677    *
   3678    */
   3679   function sine(Ctor, x) {
   3680     var k,
   3681       len = x.d.length;
   3682 
   3683     if (len < 3) {
   3684       return x.isZero() ? x : taylorSeries(Ctor, 2, x, x);
   3685     }
   3686 
   3687     // Argument reduction: sin(5x) = 16*sin^5(x) - 20*sin^3(x) + 5*sin(x)
   3688     // i.e. sin(x) = 16*sin^5(x/5) - 20*sin^3(x/5) + 5*sin(x/5)
   3689     // and  sin(x) = sin(x/5)(5 + sin^2(x/5)(16sin^2(x/5) - 20))
   3690 
   3691     // Estimate the optimum number of times to use the argument reduction.
   3692     k = 1.4 * Math.sqrt(len);
   3693     k = k > 16 ? 16 : k | 0;
   3694 
   3695     x = x.times(1 / tinyPow(5, k));
   3696     x = taylorSeries(Ctor, 2, x, x);
   3697 
   3698     // Reverse argument reduction
   3699     var sin2_x,
   3700       d5 = new Ctor(5),
   3701       d16 = new Ctor(16),
   3702       d20 = new Ctor(20);
   3703     for (; k--;) {
   3704       sin2_x = x.times(x);
   3705       x = x.times(d5.plus(sin2_x.times(d16.times(sin2_x).minus(d20))));
   3706     }
   3707 
   3708     return x;
   3709   }
   3710 
   3711 
   3712   // Calculate Taylor series for `cos`, `cosh`, `sin` and `sinh`.
   3713   function taylorSeries(Ctor, n, x, y, isHyperbolic) {
   3714     var j, t, u, x2,
   3715       i = 1,
   3716       pr = Ctor.precision,
   3717       k = Math.ceil(pr / LOG_BASE);
   3718 
   3719     external = false;
   3720     x2 = x.times(x);
   3721     u = new Ctor(y);
   3722 
   3723     for (;;) {
   3724       t = divide(u.times(x2), new Ctor(n++ * n++), pr, 1);
   3725       u = isHyperbolic ? y.plus(t) : y.minus(t);
   3726       y = divide(t.times(x2), new Ctor(n++ * n++), pr, 1);
   3727       t = u.plus(y);
   3728 
   3729       if (t.d[k] !== void 0) {
   3730         for (j = k; t.d[j] === u.d[j] && j--;);
   3731         if (j == -1) break;
   3732       }
   3733 
   3734       j = u;
   3735       u = y;
   3736       y = t;
   3737       t = j;
   3738       i++;
   3739     }
   3740 
   3741     external = true;
   3742     t.d.length = k + 1;
   3743 
   3744     return t;
   3745   }
   3746 
   3747 
   3748   // Exponent e must be positive and non-zero.
   3749   function tinyPow(b, e) {
   3750     var n = b;
   3751     while (--e) n *= b;
   3752     return n;
   3753   }
   3754 
   3755 
   3756   // Return the absolute value of `x` reduced to less than or equal to half pi.
   3757   function toLessThanHalfPi(Ctor, x) {
   3758     var t,
   3759       isNeg = x.s < 0,
   3760       pi = getPi(Ctor, Ctor.precision, 1),
   3761       halfPi = pi.times(0.5);
   3762 
   3763     x = x.abs();
   3764 
   3765     if (x.lte(halfPi)) {
   3766       quadrant = isNeg ? 4 : 1;
   3767       return x;
   3768     }
   3769 
   3770     t = x.divToInt(pi);
   3771 
   3772     if (t.isZero()) {
   3773       quadrant = isNeg ? 3 : 2;
   3774     } else {
   3775       x = x.minus(t.times(pi));
   3776 
   3777       // 0 <= x < pi
   3778       if (x.lte(halfPi)) {
   3779         quadrant = isOdd(t) ? (isNeg ? 2 : 3) : (isNeg ? 4 : 1);
   3780         return x;
   3781       }
   3782 
   3783       quadrant = isOdd(t) ? (isNeg ? 1 : 4) : (isNeg ? 3 : 2);
   3784     }
   3785 
   3786     return x.minus(pi).abs();
   3787   }
   3788 
   3789 
   3790   /*
   3791    * Return the value of Decimal `x` as a string in base `baseOut`.
   3792    *
   3793    * If the optional `sd` argument is present include a binary exponent suffix.
   3794    */
   3795   function toStringBinary(x, baseOut, sd, rm) {
   3796     var base, e, i, k, len, roundUp, str, xd, y,
   3797       Ctor = x.constructor,
   3798       isExp = sd !== void 0;
   3799 
   3800     if (isExp) {
   3801       checkInt32(sd, 1, MAX_DIGITS);
   3802       if (rm === void 0) rm = Ctor.rounding;
   3803       else checkInt32(rm, 0, 8);
   3804     } else {
   3805       sd = Ctor.precision;
   3806       rm = Ctor.rounding;
   3807     }
   3808 
   3809     if (!x.isFinite()) {
   3810       str = nonFiniteToString(x);
   3811     } else {
   3812       str = finiteToString(x);
   3813       i = str.indexOf('.');
   3814 
   3815       // Use exponential notation according to `toExpPos` and `toExpNeg`? No, but if required:
   3816       // maxBinaryExponent = floor((decimalExponent + 1) * log[2](10))
   3817       // minBinaryExponent = floor(decimalExponent * log[2](10))
   3818       // log[2](10) = 3.321928094887362347870319429489390175864
   3819 
   3820       if (isExp) {
   3821         base = 2;
   3822         if (baseOut == 16) {
   3823           sd = sd * 4 - 3;
   3824         } else if (baseOut == 8) {
   3825           sd = sd * 3 - 2;
   3826         }
   3827       } else {
   3828         base = baseOut;
   3829       }
   3830 
   3831       // Convert the number as an integer then divide the result by its base raised to a power such
   3832       // that the fraction part will be restored.
   3833 
   3834       // Non-integer.
   3835       if (i >= 0) {
   3836         str = str.replace('.', '');
   3837         y = new Ctor(1);
   3838         y.e = str.length - i;
   3839         y.d = convertBase(finiteToString(y), 10, base);
   3840         y.e = y.d.length;
   3841       }
   3842 
   3843       xd = convertBase(str, 10, base);
   3844       e = len = xd.length;
   3845 
   3846       // Remove trailing zeros.
   3847       for (; xd[--len] == 0;) xd.pop();
   3848 
   3849       if (!xd[0]) {
   3850         str = isExp ? '0p+0' : '0';
   3851       } else {
   3852         if (i < 0) {
   3853           e--;
   3854         } else {
   3855           x = new Ctor(x);
   3856           x.d = xd;
   3857           x.e = e;
   3858           x = divide(x, y, sd, rm, 0, base);
   3859           xd = x.d;
   3860           e = x.e;
   3861           roundUp = inexact;
   3862         }
   3863 
   3864         // The rounding digit, i.e. the digit after the digit that may be rounded up.
   3865         i = xd[sd];
   3866         k = base / 2;
   3867         roundUp = roundUp || xd[sd + 1] !== void 0;
   3868 
   3869         roundUp = rm < 4
   3870           ? (i !== void 0 || roundUp) && (rm === 0 || rm === (x.s < 0 ? 3 : 2))
   3871           : i > k || i === k && (rm === 4 || roundUp || rm === 6 && xd[sd - 1] & 1 ||
   3872             rm === (x.s < 0 ? 8 : 7));
   3873 
   3874         xd.length = sd;
   3875 
   3876         if (roundUp) {
   3877 
   3878           // Rounding up may mean the previous digit has to be rounded up and so on.
   3879           for (; ++xd[--sd] > base - 1;) {
   3880             xd[sd] = 0;
   3881             if (!sd) {
   3882               ++e;
   3883               xd.unshift(1);
   3884             }
   3885           }
   3886         }
   3887 
   3888         // Determine trailing zeros.
   3889         for (len = xd.length; !xd[len - 1]; --len);
   3890 
   3891         // E.g. [4, 11, 15] becomes 4bf.
   3892         for (i = 0, str = ''; i < len; i++) str += NUMERALS.charAt(xd[i]);
   3893 
   3894         // Add binary exponent suffix?
   3895         if (isExp) {
   3896           if (len > 1) {
   3897             if (baseOut == 16 || baseOut == 8) {
   3898               i = baseOut == 16 ? 4 : 3;
   3899               for (--len; len % i; len++) str += '0';
   3900               xd = convertBase(str, base, baseOut);
   3901               for (len = xd.length; !xd[len - 1]; --len);
   3902 
   3903               // xd[0] will always be be 1
   3904               for (i = 1, str = '1.'; i < len; i++) str += NUMERALS.charAt(xd[i]);
   3905             } else {
   3906               str = str.charAt(0) + '.' + str.slice(1);
   3907             }
   3908           }
   3909 
   3910           str =  str + (e < 0 ? 'p' : 'p+') + e;
   3911         } else if (e < 0) {
   3912           for (; ++e;) str = '0' + str;
   3913           str = '0.' + str;
   3914         } else {
   3915           if (++e > len) for (e -= len; e-- ;) str += '0';
   3916           else if (e < len) str = str.slice(0, e) + '.' + str.slice(e);
   3917         }
   3918       }
   3919 
   3920       str = (baseOut == 16 ? '0x' : baseOut == 2 ? '0b' : baseOut == 8 ? '0o' : '') + str;
   3921     }
   3922 
   3923     return x.s < 0 ? '-' + str : str;
   3924   }
   3925 
   3926 
   3927   // Does not strip trailing zeros.
   3928   function truncate(arr, len) {
   3929     if (arr.length > len) {
   3930       arr.length = len;
   3931       return true;
   3932     }
   3933   }
   3934 
   3935 
   3936   // Decimal methods
   3937 
   3938 
   3939   /*
   3940    *  abs
   3941    *  acos
   3942    *  acosh
   3943    *  add
   3944    *  asin
   3945    *  asinh
   3946    *  atan
   3947    *  atanh
   3948    *  atan2
   3949    *  cbrt
   3950    *  ceil
   3951    *  clamp
   3952    *  clone
   3953    *  config
   3954    *  cos
   3955    *  cosh
   3956    *  div
   3957    *  exp
   3958    *  floor
   3959    *  hypot
   3960    *  ln
   3961    *  log
   3962    *  log2
   3963    *  log10
   3964    *  max
   3965    *  min
   3966    *  mod
   3967    *  mul
   3968    *  pow
   3969    *  random
   3970    *  round
   3971    *  set
   3972    *  sign
   3973    *  sin
   3974    *  sinh
   3975    *  sqrt
   3976    *  sub
   3977    *  sum
   3978    *  tan
   3979    *  tanh
   3980    *  trunc
   3981    */
   3982 
   3983 
   3984   /*
   3985    * Return a new Decimal whose value is the absolute value of `x`.
   3986    *
   3987    * x {number|string|Decimal}
   3988    *
   3989    */
   3990   function abs(x) {
   3991     return new this(x).abs();
   3992   }
   3993 
   3994 
   3995   /*
   3996    * Return a new Decimal whose value is the arccosine in radians of `x`.
   3997    *
   3998    * x {number|string|Decimal}
   3999    *
   4000    */
   4001   function acos(x) {
   4002     return new this(x).acos();
   4003   }
   4004 
   4005 
   4006   /*
   4007    * Return a new Decimal whose value is the inverse of the hyperbolic cosine of `x`, rounded to
   4008    * `precision` significant digits using rounding mode `rounding`.
   4009    *
   4010    * x {number|string|Decimal} A value in radians.
   4011    *
   4012    */
   4013   function acosh(x) {
   4014     return new this(x).acosh();
   4015   }
   4016 
   4017 
   4018   /*
   4019    * Return a new Decimal whose value is the sum of `x` and `y`, rounded to `precision` significant
   4020    * digits using rounding mode `rounding`.
   4021    *
   4022    * x {number|string|Decimal}
   4023    * y {number|string|Decimal}
   4024    *
   4025    */
   4026   function add(x, y) {
   4027     return new this(x).plus(y);
   4028   }
   4029 
   4030 
   4031   /*
   4032    * Return a new Decimal whose value is the arcsine in radians of `x`, rounded to `precision`
   4033    * significant digits using rounding mode `rounding`.
   4034    *
   4035    * x {number|string|Decimal}
   4036    *
   4037    */
   4038   function asin(x) {
   4039     return new this(x).asin();
   4040   }
   4041 
   4042 
   4043   /*
   4044    * Return a new Decimal whose value is the inverse of the hyperbolic sine of `x`, rounded to
   4045    * `precision` significant digits using rounding mode `rounding`.
   4046    *
   4047    * x {number|string|Decimal} A value in radians.
   4048    *
   4049    */
   4050   function asinh(x) {
   4051     return new this(x).asinh();
   4052   }
   4053 
   4054 
   4055   /*
   4056    * Return a new Decimal whose value is the arctangent in radians of `x`, rounded to `precision`
   4057    * significant digits using rounding mode `rounding`.
   4058    *
   4059    * x {number|string|Decimal}
   4060    *
   4061    */
   4062   function atan(x) {
   4063     return new this(x).atan();
   4064   }
   4065 
   4066 
   4067   /*
   4068    * Return a new Decimal whose value is the inverse of the hyperbolic tangent of `x`, rounded to
   4069    * `precision` significant digits using rounding mode `rounding`.
   4070    *
   4071    * x {number|string|Decimal} A value in radians.
   4072    *
   4073    */
   4074   function atanh(x) {
   4075     return new this(x).atanh();
   4076   }
   4077 
   4078 
   4079   /*
   4080    * Return a new Decimal whose value is the arctangent in radians of `y/x` in the range -pi to pi
   4081    * (inclusive), rounded to `precision` significant digits using rounding mode `rounding`.
   4082    *
   4083    * Domain: [-Infinity, Infinity]
   4084    * Range: [-pi, pi]
   4085    *
   4086    * y {number|string|Decimal} The y-coordinate.
   4087    * x {number|string|Decimal} The x-coordinate.
   4088    *
   4089    * atan2(±0, -0)               = ±pi
   4090    * atan2(±0, +0)               = ±0
   4091    * atan2(±0, -x)               = ±pi for x > 0
   4092    * atan2(±0, x)                = ±0 for x > 0
   4093    * atan2(-y, ±0)               = -pi/2 for y > 0
   4094    * atan2(y, ±0)                = pi/2 for y > 0
   4095    * atan2(±y, -Infinity)        = ±pi for finite y > 0
   4096    * atan2(±y, +Infinity)        = ±0 for finite y > 0
   4097    * atan2(±Infinity, x)         = ±pi/2 for finite x
   4098    * atan2(±Infinity, -Infinity) = ±3*pi/4
   4099    * atan2(±Infinity, +Infinity) = ±pi/4
   4100    * atan2(NaN, x) = NaN
   4101    * atan2(y, NaN) = NaN
   4102    *
   4103    */
   4104   function atan2(y, x) {
   4105     y = new this(y);
   4106     x = new this(x);
   4107     var r,
   4108       pr = this.precision,
   4109       rm = this.rounding,
   4110       wpr = pr + 4;
   4111 
   4112     // Either NaN
   4113     if (!y.s || !x.s) {
   4114       r = new this(NaN);
   4115 
   4116     // Both ±Infinity
   4117     } else if (!y.d && !x.d) {
   4118       r = getPi(this, wpr, 1).times(x.s > 0 ? 0.25 : 0.75);
   4119       r.s = y.s;
   4120 
   4121     // x is ±Infinity or y is ±0
   4122     } else if (!x.d || y.isZero()) {
   4123       r = x.s < 0 ? getPi(this, pr, rm) : new this(0);
   4124       r.s = y.s;
   4125 
   4126     // y is ±Infinity or x is ±0
   4127     } else if (!y.d || x.isZero()) {
   4128       r = getPi(this, wpr, 1).times(0.5);
   4129       r.s = y.s;
   4130 
   4131     // Both non-zero and finite
   4132     } else if (x.s < 0) {
   4133       this.precision = wpr;
   4134       this.rounding = 1;
   4135       r = this.atan(divide(y, x, wpr, 1));
   4136       x = getPi(this, wpr, 1);
   4137       this.precision = pr;
   4138       this.rounding = rm;
   4139       r = y.s < 0 ? r.minus(x) : r.plus(x);
   4140     } else {
   4141       r = this.atan(divide(y, x, wpr, 1));
   4142     }
   4143 
   4144     return r;
   4145   }
   4146 
   4147 
   4148   /*
   4149    * Return a new Decimal whose value is the cube root of `x`, rounded to `precision` significant
   4150    * digits using rounding mode `rounding`.
   4151    *
   4152    * x {number|string|Decimal}
   4153    *
   4154    */
   4155   function cbrt(x) {
   4156     return new this(x).cbrt();
   4157   }
   4158 
   4159 
   4160   /*
   4161    * Return a new Decimal whose value is `x` rounded to an integer using `ROUND_CEIL`.
   4162    *
   4163    * x {number|string|Decimal}
   4164    *
   4165    */
   4166   function ceil(x) {
   4167     return finalise(x = new this(x), x.e + 1, 2);
   4168   }
   4169 
   4170 
   4171   /*
   4172    * Return a new Decimal whose value is `x` clamped to the range delineated by `min` and `max`.
   4173    *
   4174    * x {number|string|Decimal}
   4175    * min {number|string|Decimal}
   4176    * max {number|string|Decimal}
   4177    *
   4178    */
   4179   function clamp(x, min, max) {
   4180     return new this(x).clamp(min, max);
   4181   }
   4182 
   4183 
   4184   /*
   4185    * Configure global settings for a Decimal constructor.
   4186    *
   4187    * `obj` is an object with one or more of the following properties,
   4188    *
   4189    *   precision  {number}
   4190    *   rounding   {number}
   4191    *   toExpNeg   {number}
   4192    *   toExpPos   {number}
   4193    *   maxE       {number}
   4194    *   minE       {number}
   4195    *   modulo     {number}
   4196    *   crypto     {boolean|number}
   4197    *   defaults   {true}
   4198    *
   4199    * E.g. Decimal.config({ precision: 20, rounding: 4 })
   4200    *
   4201    */
   4202   function config(obj) {
   4203     if (!obj || typeof obj !== 'object') throw Error(decimalError + 'Object expected');
   4204     var i, p, v,
   4205       useDefaults = obj.defaults === true,
   4206       ps = [
   4207         'precision', 1, MAX_DIGITS,
   4208         'rounding', 0, 8,
   4209         'toExpNeg', -EXP_LIMIT, 0,
   4210         'toExpPos', 0, EXP_LIMIT,
   4211         'maxE', 0, EXP_LIMIT,
   4212         'minE', -EXP_LIMIT, 0,
   4213         'modulo', 0, 9
   4214       ];
   4215 
   4216     for (i = 0; i < ps.length; i += 3) {
   4217       if (p = ps[i], useDefaults) this[p] = DEFAULTS[p];
   4218       if ((v = obj[p]) !== void 0) {
   4219         if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v;
   4220         else throw Error(invalidArgument + p + ': ' + v);
   4221       }
   4222     }
   4223 
   4224     if (p = 'crypto', useDefaults) this[p] = DEFAULTS[p];
   4225     if ((v = obj[p]) !== void 0) {
   4226       if (v === true || v === false || v === 0 || v === 1) {
   4227         if (v) {
   4228           if (typeof crypto != 'undefined' && crypto &&
   4229             (crypto.getRandomValues || crypto.randomBytes)) {
   4230             this[p] = true;
   4231           } else {
   4232             throw Error(cryptoUnavailable);
   4233           }
   4234         } else {
   4235           this[p] = false;
   4236         }
   4237       } else {
   4238         throw Error(invalidArgument + p + ': ' + v);
   4239       }
   4240     }
   4241 
   4242     return this;
   4243   }
   4244 
   4245 
   4246   /*
   4247    * Return a new Decimal whose value is the cosine of `x`, rounded to `precision` significant
   4248    * digits using rounding mode `rounding`.
   4249    *
   4250    * x {number|string|Decimal} A value in radians.
   4251    *
   4252    */
   4253   function cos(x) {
   4254     return new this(x).cos();
   4255   }
   4256 
   4257 
   4258   /*
   4259    * Return a new Decimal whose value is the hyperbolic cosine of `x`, rounded to precision
   4260    * significant digits using rounding mode `rounding`.
   4261    *
   4262    * x {number|string|Decimal} A value in radians.
   4263    *
   4264    */
   4265   function cosh(x) {
   4266     return new this(x).cosh();
   4267   }
   4268 
   4269 
   4270   /*
   4271    * Create and return a Decimal constructor with the same configuration properties as this Decimal
   4272    * constructor.
   4273    *
   4274    */
   4275   function clone(obj) {
   4276     var i, p, ps;
   4277 
   4278     /*
   4279      * The Decimal constructor and exported function.
   4280      * Return a new Decimal instance.
   4281      *
   4282      * v {number|string|Decimal} A numeric value.
   4283      *
   4284      */
   4285     function Decimal(v) {
   4286       var e, i, t,
   4287         x = this;
   4288 
   4289       // Decimal called without new.
   4290       if (!(x instanceof Decimal)) return new Decimal(v);
   4291 
   4292       // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor
   4293       // which points to Object.
   4294       x.constructor = Decimal;
   4295 
   4296       // Duplicate.
   4297       if (isDecimalInstance(v)) {
   4298         x.s = v.s;
   4299 
   4300         if (external) {
   4301           if (!v.d || v.e > Decimal.maxE) {
   4302 
   4303             // Infinity.
   4304             x.e = NaN;
   4305             x.d = null;
   4306           } else if (v.e < Decimal.minE) {
   4307 
   4308             // Zero.
   4309             x.e = 0;
   4310             x.d = [0];
   4311           } else {
   4312             x.e = v.e;
   4313             x.d = v.d.slice();
   4314           }
   4315         } else {
   4316           x.e = v.e;
   4317           x.d = v.d ? v.d.slice() : v.d;
   4318         }
   4319 
   4320         return;
   4321       }
   4322 
   4323       t = typeof v;
   4324 
   4325       if (t === 'number') {
   4326         if (v === 0) {
   4327           x.s = 1 / v < 0 ? -1 : 1;
   4328           x.e = 0;
   4329           x.d = [0];
   4330           return;
   4331         }
   4332 
   4333         if (v < 0) {
   4334           v = -v;
   4335           x.s = -1;
   4336         } else {
   4337           x.s = 1;
   4338         }
   4339 
   4340         // Fast path for small integers.
   4341         if (v === ~~v && v < 1e7) {
   4342           for (e = 0, i = v; i >= 10; i /= 10) e++;
   4343 
   4344           if (external) {
   4345             if (e > Decimal.maxE) {
   4346               x.e = NaN;
   4347               x.d = null;
   4348             } else if (e < Decimal.minE) {
   4349               x.e = 0;
   4350               x.d = [0];
   4351             } else {
   4352               x.e = e;
   4353               x.d = [v];
   4354             }
   4355           } else {
   4356             x.e = e;
   4357             x.d = [v];
   4358           }
   4359 
   4360           return;
   4361 
   4362         // Infinity, NaN.
   4363         } else if (v * 0 !== 0) {
   4364           if (!v) x.s = NaN;
   4365           x.e = NaN;
   4366           x.d = null;
   4367           return;
   4368         }
   4369 
   4370         return parseDecimal(x, v.toString());
   4371 
   4372       } else if (t !== 'string') {
   4373         throw Error(invalidArgument + v);
   4374       }
   4375 
   4376       // Minus sign?
   4377       if ((i = v.charCodeAt(0)) === 45) {
   4378         v = v.slice(1);
   4379         x.s = -1;
   4380       } else {
   4381         // Plus sign?
   4382         if (i === 43) v = v.slice(1);
   4383         x.s = 1;
   4384       }
   4385 
   4386       return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v);
   4387     }
   4388 
   4389     Decimal.prototype = P;
   4390 
   4391     Decimal.ROUND_UP = 0;
   4392     Decimal.ROUND_DOWN = 1;
   4393     Decimal.ROUND_CEIL = 2;
   4394     Decimal.ROUND_FLOOR = 3;
   4395     Decimal.ROUND_HALF_UP = 4;
   4396     Decimal.ROUND_HALF_DOWN = 5;
   4397     Decimal.ROUND_HALF_EVEN = 6;
   4398     Decimal.ROUND_HALF_CEIL = 7;
   4399     Decimal.ROUND_HALF_FLOOR = 8;
   4400     Decimal.EUCLID = 9;
   4401 
   4402     Decimal.config = Decimal.set = config;
   4403     Decimal.clone = clone;
   4404     Decimal.isDecimal = isDecimalInstance;
   4405 
   4406     Decimal.abs = abs;
   4407     Decimal.acos = acos;
   4408     Decimal.acosh = acosh;        // ES6
   4409     Decimal.add = add;
   4410     Decimal.asin = asin;
   4411     Decimal.asinh = asinh;        // ES6
   4412     Decimal.atan = atan;
   4413     Decimal.atanh = atanh;        // ES6
   4414     Decimal.atan2 = atan2;
   4415     Decimal.cbrt = cbrt;          // ES6
   4416     Decimal.ceil = ceil;
   4417     Decimal.clamp = clamp;
   4418     Decimal.cos = cos;
   4419     Decimal.cosh = cosh;          // ES6
   4420     Decimal.div = div;
   4421     Decimal.exp = exp;
   4422     Decimal.floor = floor;
   4423     Decimal.hypot = hypot;        // ES6
   4424     Decimal.ln = ln;
   4425     Decimal.log = log;
   4426     Decimal.log10 = log10;        // ES6
   4427     Decimal.log2 = log2;          // ES6
   4428     Decimal.max = max;
   4429     Decimal.min = min;
   4430     Decimal.mod = mod;
   4431     Decimal.mul = mul;
   4432     Decimal.pow = pow;
   4433     Decimal.random = random;
   4434     Decimal.round = round;
   4435     Decimal.sign = sign;          // ES6
   4436     Decimal.sin = sin;
   4437     Decimal.sinh = sinh;          // ES6
   4438     Decimal.sqrt = sqrt;
   4439     Decimal.sub = sub;
   4440     Decimal.sum = sum;
   4441     Decimal.tan = tan;
   4442     Decimal.tanh = tanh;          // ES6
   4443     Decimal.trunc = trunc;        // ES6
   4444 
   4445     if (obj === void 0) obj = {};
   4446     if (obj) {
   4447       if (obj.defaults !== true) {
   4448         ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'maxE', 'minE', 'modulo', 'crypto'];
   4449         for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p];
   4450       }
   4451     }
   4452 
   4453     Decimal.config(obj);
   4454 
   4455     return Decimal;
   4456   }
   4457 
   4458 
   4459   /*
   4460    * Return a new Decimal whose value is `x` divided by `y`, rounded to `precision` significant
   4461    * digits using rounding mode `rounding`.
   4462    *
   4463    * x {number|string|Decimal}
   4464    * y {number|string|Decimal}
   4465    *
   4466    */
   4467   function div(x, y) {
   4468     return new this(x).div(y);
   4469   }
   4470 
   4471 
   4472   /*
   4473    * Return a new Decimal whose value is the natural exponential of `x`, rounded to `precision`
   4474    * significant digits using rounding mode `rounding`.
   4475    *
   4476    * x {number|string|Decimal} The power to which to raise the base of the natural log.
   4477    *
   4478    */
   4479   function exp(x) {
   4480     return new this(x).exp();
   4481   }
   4482 
   4483 
   4484   /*
   4485    * Return a new Decimal whose value is `x` round to an integer using `ROUND_FLOOR`.
   4486    *
   4487    * x {number|string|Decimal}
   4488    *
   4489    */
   4490   function floor(x) {
   4491     return finalise(x = new this(x), x.e + 1, 3);
   4492   }
   4493 
   4494 
   4495   /*
   4496    * Return a new Decimal whose value is the square root of the sum of the squares of the arguments,
   4497    * rounded to `precision` significant digits using rounding mode `rounding`.
   4498    *
   4499    * hypot(a, b, ...) = sqrt(a^2 + b^2 + ...)
   4500    *
   4501    * arguments {number|string|Decimal}
   4502    *
   4503    */
   4504   function hypot() {
   4505     var i, n,
   4506       t = new this(0);
   4507 
   4508     external = false;
   4509 
   4510     for (i = 0; i < arguments.length;) {
   4511       n = new this(arguments[i++]);
   4512       if (!n.d) {
   4513         if (n.s) {
   4514           external = true;
   4515           return new this(1 / 0);
   4516         }
   4517         t = n;
   4518       } else if (t.d) {
   4519         t = t.plus(n.times(n));
   4520       }
   4521     }
   4522 
   4523     external = true;
   4524 
   4525     return t.sqrt();
   4526   }
   4527 
   4528 
   4529   /*
   4530    * Return true if object is a Decimal instance (where Decimal is any Decimal constructor),
   4531    * otherwise return false.
   4532    *
   4533    */
   4534   function isDecimalInstance(obj) {
   4535     return obj instanceof Decimal || obj && obj.toStringTag === tag || false;
   4536   }
   4537 
   4538 
   4539   /*
   4540    * Return a new Decimal whose value is the natural logarithm of `x`, rounded to `precision`
   4541    * significant digits using rounding mode `rounding`.
   4542    *
   4543    * x {number|string|Decimal}
   4544    *
   4545    */
   4546   function ln(x) {
   4547     return new this(x).ln();
   4548   }
   4549 
   4550 
   4551   /*
   4552    * Return a new Decimal whose value is the log of `x` to the base `y`, or to base 10 if no base
   4553    * is specified, rounded to `precision` significant digits using rounding mode `rounding`.
   4554    *
   4555    * log[y](x)
   4556    *
   4557    * x {number|string|Decimal} The argument of the logarithm.
   4558    * y {number|string|Decimal} The base of the logarithm.
   4559    *
   4560    */
   4561   function log(x, y) {
   4562     return new this(x).log(y);
   4563   }
   4564 
   4565 
   4566   /*
   4567    * Return a new Decimal whose value is the base 2 logarithm of `x`, rounded to `precision`
   4568    * significant digits using rounding mode `rounding`.
   4569    *
   4570    * x {number|string|Decimal}
   4571    *
   4572    */
   4573   function log2(x) {
   4574     return new this(x).log(2);
   4575   }
   4576 
   4577 
   4578   /*
   4579    * Return a new Decimal whose value is the base 10 logarithm of `x`, rounded to `precision`
   4580    * significant digits using rounding mode `rounding`.
   4581    *
   4582    * x {number|string|Decimal}
   4583    *
   4584    */
   4585   function log10(x) {
   4586     return new this(x).log(10);
   4587   }
   4588 
   4589 
   4590   /*
   4591    * Return a new Decimal whose value is the maximum of the arguments.
   4592    *
   4593    * arguments {number|string|Decimal}
   4594    *
   4595    */
   4596   function max() {
   4597     return maxOrMin(this, arguments, 'lt');
   4598   }
   4599 
   4600 
   4601   /*
   4602    * Return a new Decimal whose value is the minimum of the arguments.
   4603    *
   4604    * arguments {number|string|Decimal}
   4605    *
   4606    */
   4607   function min() {
   4608     return maxOrMin(this, arguments, 'gt');
   4609   }
   4610 
   4611 
   4612   /*
   4613    * Return a new Decimal whose value is `x` modulo `y`, rounded to `precision` significant digits
   4614    * using rounding mode `rounding`.
   4615    *
   4616    * x {number|string|Decimal}
   4617    * y {number|string|Decimal}
   4618    *
   4619    */
   4620   function mod(x, y) {
   4621     return new this(x).mod(y);
   4622   }
   4623 
   4624 
   4625   /*
   4626    * Return a new Decimal whose value is `x` multiplied by `y`, rounded to `precision` significant
   4627    * digits using rounding mode `rounding`.
   4628    *
   4629    * x {number|string|Decimal}
   4630    * y {number|string|Decimal}
   4631    *
   4632    */
   4633   function mul(x, y) {
   4634     return new this(x).mul(y);
   4635   }
   4636 
   4637 
   4638   /*
   4639    * Return a new Decimal whose value is `x` raised to the power `y`, rounded to precision
   4640    * significant digits using rounding mode `rounding`.
   4641    *
   4642    * x {number|string|Decimal} The base.
   4643    * y {number|string|Decimal} The exponent.
   4644    *
   4645    */
   4646   function pow(x, y) {
   4647     return new this(x).pow(y);
   4648   }
   4649 
   4650 
   4651   /*
   4652    * Returns a new Decimal with a random value equal to or greater than 0 and less than 1, and with
   4653    * `sd`, or `Decimal.precision` if `sd` is omitted, significant digits (or less if trailing zeros
   4654    * are produced).
   4655    *
   4656    * [sd] {number} Significant digits. Integer, 0 to MAX_DIGITS inclusive.
   4657    *
   4658    */
   4659   function random(sd) {
   4660     var d, e, k, n,
   4661       i = 0,
   4662       r = new this(1),
   4663       rd = [];
   4664 
   4665     if (sd === void 0) sd = this.precision;
   4666     else checkInt32(sd, 1, MAX_DIGITS);
   4667 
   4668     k = Math.ceil(sd / LOG_BASE);
   4669 
   4670     if (!this.crypto) {
   4671       for (; i < k;) rd[i++] = Math.random() * 1e7 | 0;
   4672 
   4673     // Browsers supporting crypto.getRandomValues.
   4674     } else if (crypto.getRandomValues) {
   4675       d = crypto.getRandomValues(new Uint32Array(k));
   4676 
   4677       for (; i < k;) {
   4678         n = d[i];
   4679 
   4680         // 0 <= n < 4294967296
   4681         // Probability n >= 4.29e9, is 4967296 / 4294967296 = 0.00116 (1 in 865).
   4682         if (n >= 4.29e9) {
   4683           d[i] = crypto.getRandomValues(new Uint32Array(1))[0];
   4684         } else {
   4685 
   4686           // 0 <= n <= 4289999999
   4687           // 0 <= (n % 1e7) <= 9999999
   4688           rd[i++] = n % 1e7;
   4689         }
   4690       }
   4691 
   4692     // Node.js supporting crypto.randomBytes.
   4693     } else if (crypto.randomBytes) {
   4694 
   4695       // buffer
   4696       d = crypto.randomBytes(k *= 4);
   4697 
   4698       for (; i < k;) {
   4699 
   4700         // 0 <= n < 2147483648
   4701         n = d[i] + (d[i + 1] << 8) + (d[i + 2] << 16) + ((d[i + 3] & 0x7f) << 24);
   4702 
   4703         // Probability n >= 2.14e9, is 7483648 / 2147483648 = 0.0035 (1 in 286).
   4704         if (n >= 2.14e9) {
   4705           crypto.randomBytes(4).copy(d, i);
   4706         } else {
   4707 
   4708           // 0 <= n <= 2139999999
   4709           // 0 <= (n % 1e7) <= 9999999
   4710           rd.push(n % 1e7);
   4711           i += 4;
   4712         }
   4713       }
   4714 
   4715       i = k / 4;
   4716     } else {
   4717       throw Error(cryptoUnavailable);
   4718     }
   4719 
   4720     k = rd[--i];
   4721     sd %= LOG_BASE;
   4722 
   4723     // Convert trailing digits to zeros according to sd.
   4724     if (k && sd) {
   4725       n = mathpow(10, LOG_BASE - sd);
   4726       rd[i] = (k / n | 0) * n;
   4727     }
   4728 
   4729     // Remove trailing words which are zero.
   4730     for (; rd[i] === 0; i--) rd.pop();
   4731 
   4732     // Zero?
   4733     if (i < 0) {
   4734       e = 0;
   4735       rd = [0];
   4736     } else {
   4737       e = -1;
   4738 
   4739       // Remove leading words which are zero and adjust exponent accordingly.
   4740       for (; rd[0] === 0; e -= LOG_BASE) rd.shift();
   4741 
   4742       // Count the digits of the first word of rd to determine leading zeros.
   4743       for (k = 1, n = rd[0]; n >= 10; n /= 10) k++;
   4744 
   4745       // Adjust the exponent for leading zeros of the first word of rd.
   4746       if (k < LOG_BASE) e -= LOG_BASE - k;
   4747     }
   4748 
   4749     r.e = e;
   4750     r.d = rd;
   4751 
   4752     return r;
   4753   }
   4754 
   4755 
   4756   /*
   4757    * Return a new Decimal whose value is `x` rounded to an integer using rounding mode `rounding`.
   4758    *
   4759    * To emulate `Math.round`, set rounding to 7 (ROUND_HALF_CEIL).
   4760    *
   4761    * x {number|string|Decimal}
   4762    *
   4763    */
   4764   function round(x) {
   4765     return finalise(x = new this(x), x.e + 1, this.rounding);
   4766   }
   4767 
   4768 
   4769   /*
   4770    * Return
   4771    *   1    if x > 0,
   4772    *  -1    if x < 0,
   4773    *   0    if x is 0,
   4774    *  -0    if x is -0,
   4775    *   NaN  otherwise
   4776    *
   4777    * x {number|string|Decimal}
   4778    *
   4779    */
   4780   function sign(x) {
   4781     x = new this(x);
   4782     return x.d ? (x.d[0] ? x.s : 0 * x.s) : x.s || NaN;
   4783   }
   4784 
   4785 
   4786   /*
   4787    * Return a new Decimal whose value is the sine of `x`, rounded to `precision` significant digits
   4788    * using rounding mode `rounding`.
   4789    *
   4790    * x {number|string|Decimal} A value in radians.
   4791    *
   4792    */
   4793   function sin(x) {
   4794     return new this(x).sin();
   4795   }
   4796 
   4797 
   4798   /*
   4799    * Return a new Decimal whose value is the hyperbolic sine of `x`, rounded to `precision`
   4800    * significant digits using rounding mode `rounding`.
   4801    *
   4802    * x {number|string|Decimal} A value in radians.
   4803    *
   4804    */
   4805   function sinh(x) {
   4806     return new this(x).sinh();
   4807   }
   4808 
   4809 
   4810   /*
   4811    * Return a new Decimal whose value is the square root of `x`, rounded to `precision` significant
   4812    * digits using rounding mode `rounding`.
   4813    *
   4814    * x {number|string|Decimal}
   4815    *
   4816    */
   4817   function sqrt(x) {
   4818     return new this(x).sqrt();
   4819   }
   4820 
   4821 
   4822   /*
   4823    * Return a new Decimal whose value is `x` minus `y`, rounded to `precision` significant digits
   4824    * using rounding mode `rounding`.
   4825    *
   4826    * x {number|string|Decimal}
   4827    * y {number|string|Decimal}
   4828    *
   4829    */
   4830   function sub(x, y) {
   4831     return new this(x).sub(y);
   4832   }
   4833 
   4834 
   4835   /*
   4836    * Return a new Decimal whose value is the sum of the arguments, rounded to `precision`
   4837    * significant digits using rounding mode `rounding`.
   4838    *
   4839    * Only the result is rounded, not the intermediate calculations.
   4840    *
   4841    * arguments {number|string|Decimal}
   4842    *
   4843    */
   4844   function sum() {
   4845     var i = 0,
   4846       args = arguments,
   4847       x = new this(args[i]);
   4848 
   4849     external = false;
   4850     for (; x.s && ++i < args.length;) x = x.plus(args[i]);
   4851     external = true;
   4852 
   4853     return finalise(x, this.precision, this.rounding);
   4854   }
   4855 
   4856 
   4857   /*
   4858    * Return a new Decimal whose value is the tangent of `x`, rounded to `precision` significant
   4859    * digits using rounding mode `rounding`.
   4860    *
   4861    * x {number|string|Decimal} A value in radians.
   4862    *
   4863    */
   4864   function tan(x) {
   4865     return new this(x).tan();
   4866   }
   4867 
   4868 
   4869   /*
   4870    * Return a new Decimal whose value is the hyperbolic tangent of `x`, rounded to `precision`
   4871    * significant digits using rounding mode `rounding`.
   4872    *
   4873    * x {number|string|Decimal} A value in radians.
   4874    *
   4875    */
   4876   function tanh(x) {
   4877     return new this(x).tanh();
   4878   }
   4879 
   4880 
   4881   /*
   4882    * Return a new Decimal whose value is `x` truncated to an integer.
   4883    *
   4884    * x {number|string|Decimal}
   4885    *
   4886    */
   4887   function trunc(x) {
   4888     return finalise(x = new this(x), x.e + 1, 1);
   4889   }
   4890 
   4891 
   4892   // Create and configure initial Decimal constructor.
   4893   Decimal = clone(DEFAULTS);
   4894   Decimal.prototype.constructor = Decimal;
   4895   Decimal['default'] = Decimal.Decimal = Decimal;
   4896 
   4897   // Create the internal constants from their string values.
   4898   LN10 = new Decimal(LN10);
   4899   PI = new Decimal(PI);
   4900 
   4901 
   4902   // Export.
   4903 
   4904 
   4905   // AMD.
   4906   if (typeof define == 'function' && define.amd) {
   4907     define(function () {
   4908       return Decimal;
   4909     });
   4910 
   4911   // Node and other environments that support module.exports.
   4912   } else if (typeof module != 'undefined' && module.exports) {
   4913     if (typeof Symbol == 'function' && typeof Symbol.iterator == 'symbol') {
   4914       P[Symbol['for']('nodejs.util.inspect.custom')] = P.toString;
   4915       P[Symbol.toStringTag] = 'Decimal';
   4916     }
   4917 
   4918     module.exports = Decimal;
   4919 
   4920   // Browser.
   4921   } else {
   4922     if (!globalScope) {
   4923       globalScope = typeof self != 'undefined' && self && self.self == self ? self : window;
   4924     }
   4925 
   4926     noConflict = globalScope.Decimal;
   4927     Decimal.noConflict = function () {
   4928       globalScope.Decimal = noConflict;
   4929       return Decimal;
   4930     };
   4931 
   4932     globalScope.Decimal = Decimal;
   4933   }
   4934 })(this);