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