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