source: node_modules/decimal.js-light/decimal.js@ ba17441

Last change on this file since ba17441 was a762898, checked in by istevanoska <ilinastevanoska@…>, 5 months ago

Added visualizations

  • Property mode set to 100644
File size: 50.2 KB
Line 
1/*! decimal.js-light v2.5.1 https://github.com/MikeMcl/decimal.js-light/LICENCE */
2;(function (globalScope) {
3 'use strict';
4
5
6 /*
7 * decimal.js-light v2.5.1
8 * An arbitrary-precision Decimal type for JavaScript.
9 * https://github.com/MikeMcl/decimal.js-light
10 * Copyright (c) 2020 Michael Mclaughlin <M8ch88l@gmail.com>
11 * MIT Expat Licence
12 */
13
14
15 // ----------------------------------- EDITABLE DEFAULTS ------------------------------------ //
16
17
18 // The limit on the value of `precision`, and on the value of the first argument to
19 // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`.
20 var MAX_DIGITS = 1e9, // 0 to 1e9
21
22
23 // The initial configuration properties of the Decimal constructor.
24 Decimal = {
25
26 // These values must be integers within the stated ranges (inclusive).
27 // Most of these values can be changed during run-time using `Decimal.config`.
28
29 // The maximum number of significant digits of the result of a calculation or base conversion.
30 // E.g. `Decimal.config({ precision: 20 });`
31 precision: 20, // 1 to MAX_DIGITS
32
33 // The rounding mode used by default by `toInteger`, `toDecimalPlaces`, `toExponential`,
34 // `toFixed`, `toPrecision` and `toSignificantDigits`.
35 //
36 // ROUND_UP 0 Away from zero.
37 // ROUND_DOWN 1 Towards zero.
38 // ROUND_CEIL 2 Towards +Infinity.
39 // ROUND_FLOOR 3 Towards -Infinity.
40 // ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up.
41 // ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
42 // ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
43 // ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
44 // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
45 //
46 // E.g.
47 // `Decimal.rounding = 4;`
48 // `Decimal.rounding = Decimal.ROUND_HALF_UP;`
49 rounding: 4, // 0 to 8
50
51 // The exponent value at and beneath which `toString` returns exponential notation.
52 // JavaScript numbers: -7
53 toExpNeg: -7, // 0 to -MAX_E
54
55 // The exponent value at and above which `toString` returns exponential notation.
56 // JavaScript numbers: 21
57 toExpPos: 21, // 0 to MAX_E
58
59 // The natural logarithm of 10.
60 // 115 digits
61 LN10: '2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286'
62 },
63
64
65 // ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- //
66
67
68 external = true,
69
70 decimalError = '[DecimalError] ',
71 invalidArgument = decimalError + 'Invalid argument: ',
72 exponentOutOfRange = decimalError + 'Exponent out of range: ',
73
74 mathfloor = Math.floor,
75 mathpow = Math.pow,
76
77 isDecimal = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
78
79 ONE,
80 BASE = 1e7,
81 LOG_BASE = 7,
82 MAX_SAFE_INTEGER = 9007199254740991,
83 MAX_E = mathfloor(MAX_SAFE_INTEGER / LOG_BASE), // 1286742750677284
84
85 // Decimal.prototype object
86 P = {};
87
88
89 // Decimal prototype methods
90
91
92 /*
93 * absoluteValue abs
94 * comparedTo cmp
95 * decimalPlaces dp
96 * dividedBy div
97 * dividedToIntegerBy idiv
98 * equals eq
99 * exponent
100 * greaterThan gt
101 * greaterThanOrEqualTo gte
102 * isInteger isint
103 * isNegative isneg
104 * isPositive ispos
105 * isZero
106 * lessThan lt
107 * lessThanOrEqualTo lte
108 * logarithm log
109 * minus sub
110 * modulo mod
111 * naturalExponential exp
112 * naturalLogarithm ln
113 * negated neg
114 * plus add
115 * precision sd
116 * squareRoot sqrt
117 * times mul
118 * toDecimalPlaces todp
119 * toExponential
120 * toFixed
121 * toInteger toint
122 * toNumber
123 * toPower pow
124 * toPrecision
125 * toSignificantDigits tosd
126 * toString
127 * valueOf val
128 */
129
130
131 /*
132 * Return a new Decimal whose value is the absolute value of this Decimal.
133 *
134 */
135 P.absoluteValue = P.abs = function () {
136 var x = new this.constructor(this);
137 if (x.s) x.s = 1;
138 return x;
139 };
140
141
142 /*
143 * Return
144 * 1 if the value of this Decimal is greater than the value of `y`,
145 * -1 if the value of this Decimal is less than the value of `y`,
146 * 0 if they have the same value
147 *
148 */
149 P.comparedTo = P.cmp = function (y) {
150 var i, j, xdL, ydL,
151 x = this;
152
153 y = new x.constructor(y);
154
155 // Signs differ?
156 if (x.s !== y.s) return x.s || -y.s;
157
158 // Compare exponents.
159 if (x.e !== y.e) return x.e > y.e ^ x.s < 0 ? 1 : -1;
160
161 xdL = x.d.length;
162 ydL = y.d.length;
163
164 // Compare digit by digit.
165 for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) {
166 if (x.d[i] !== y.d[i]) return x.d[i] > y.d[i] ^ x.s < 0 ? 1 : -1;
167 }
168
169 // Compare lengths.
170 return xdL === ydL ? 0 : xdL > ydL ^ x.s < 0 ? 1 : -1;
171 };
172
173
174 /*
175 * Return the number of decimal places of the value of this Decimal.
176 *
177 */
178 P.decimalPlaces = P.dp = function () {
179 var x = this,
180 w = x.d.length - 1,
181 dp = (w - x.e) * LOG_BASE;
182
183 // Subtract the number of trailing zeros of the last word.
184 w = x.d[w];
185 if (w) for (; w % 10 == 0; w /= 10) dp--;
186
187 return dp < 0 ? 0 : dp;
188 };
189
190
191 /*
192 * Return a new Decimal whose value is the value of this Decimal divided by `y`, truncated to
193 * `precision` significant digits.
194 *
195 */
196 P.dividedBy = P.div = function (y) {
197 return divide(this, new this.constructor(y));
198 };
199
200
201 /*
202 * Return a new Decimal whose value is the integer part of dividing the value of this Decimal
203 * by the value of `y`, truncated to `precision` significant digits.
204 *
205 */
206 P.dividedToIntegerBy = P.idiv = function (y) {
207 var x = this,
208 Ctor = x.constructor;
209 return round(divide(x, new Ctor(y), 0, 1), Ctor.precision);
210 };
211
212
213 /*
214 * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false.
215 *
216 */
217 P.equals = P.eq = function (y) {
218 return !this.cmp(y);
219 };
220
221
222 /*
223 * Return the (base 10) exponent value of this Decimal (this.e is the base 10000000 exponent).
224 *
225 */
226 P.exponent = function () {
227 return getBase10Exponent(this);
228 };
229
230
231 /*
232 * Return true if the value of this Decimal is greater than the value of `y`, otherwise return
233 * false.
234 *
235 */
236 P.greaterThan = P.gt = function (y) {
237 return this.cmp(y) > 0;
238 };
239
240
241 /*
242 * Return true if the value of this Decimal is greater than or equal to the value of `y`,
243 * otherwise return false.
244 *
245 */
246 P.greaterThanOrEqualTo = P.gte = function (y) {
247 return this.cmp(y) >= 0;
248 };
249
250
251 /*
252 * Return true if the value of this Decimal is an integer, otherwise return false.
253 *
254 */
255 P.isInteger = P.isint = function () {
256 return this.e > this.d.length - 2;
257 };
258
259
260 /*
261 * Return true if the value of this Decimal is negative, otherwise return false.
262 *
263 */
264 P.isNegative = P.isneg = function () {
265 return this.s < 0;
266 };
267
268
269 /*
270 * Return true if the value of this Decimal is positive, otherwise return false.
271 *
272 */
273 P.isPositive = P.ispos = function () {
274 return this.s > 0;
275 };
276
277
278 /*
279 * Return true if the value of this Decimal is 0, otherwise return false.
280 *
281 */
282 P.isZero = function () {
283 return this.s === 0;
284 };
285
286
287 /*
288 * Return true if the value of this Decimal is less than `y`, otherwise return false.
289 *
290 */
291 P.lessThan = P.lt = function (y) {
292 return this.cmp(y) < 0;
293 };
294
295
296 /*
297 * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false.
298 *
299 */
300 P.lessThanOrEqualTo = P.lte = function (y) {
301 return this.cmp(y) < 1;
302 };
303
304
305 /*
306 * Return the logarithm of the value of this Decimal to the specified base, truncated to
307 * `precision` significant digits.
308 *
309 * If no base is specified, return log[10](x).
310 *
311 * log[base](x) = ln(x) / ln(base)
312 *
313 * The maximum error of the result is 1 ulp (unit in the last place).
314 *
315 * [base] {number|string|Decimal} The base of the logarithm.
316 *
317 */
318 P.logarithm = P.log = function (base) {
319 var r,
320 x = this,
321 Ctor = x.constructor,
322 pr = Ctor.precision,
323 wpr = pr + 5;
324
325 // Default base is 10.
326 if (base === void 0) {
327 base = new Ctor(10);
328 } else {
329 base = new Ctor(base);
330
331 // log[-b](x) = NaN
332 // log[0](x) = NaN
333 // log[1](x) = NaN
334 if (base.s < 1 || base.eq(ONE)) throw Error(decimalError + 'NaN');
335 }
336
337 // log[b](-x) = NaN
338 // log[b](0) = -Infinity
339 if (x.s < 1) throw Error(decimalError + (x.s ? 'NaN' : '-Infinity'));
340
341 // log[b](1) = 0
342 if (x.eq(ONE)) return new Ctor(0);
343
344 external = false;
345 r = divide(ln(x, wpr), ln(base, wpr), wpr);
346 external = true;
347
348 return round(r, pr);
349 };
350
351
352 /*
353 * Return a new Decimal whose value is the value of this Decimal minus `y`, truncated to
354 * `precision` significant digits.
355 *
356 */
357 P.minus = P.sub = function (y) {
358 var x = this;
359 y = new x.constructor(y);
360 return x.s == y.s ? subtract(x, y) : add(x, (y.s = -y.s, y));
361 };
362
363
364 /*
365 * Return a new Decimal whose value is the value of this Decimal modulo `y`, truncated to
366 * `precision` significant digits.
367 *
368 */
369 P.modulo = P.mod = function (y) {
370 var q,
371 x = this,
372 Ctor = x.constructor,
373 pr = Ctor.precision;
374
375 y = new Ctor(y);
376
377 // x % 0 = NaN
378 if (!y.s) throw Error(decimalError + 'NaN');
379
380 // Return x if x is 0.
381 if (!x.s) return round(new Ctor(x), pr);
382
383 // Prevent rounding of intermediate calculations.
384 external = false;
385 q = divide(x, y, 0, 1).times(y);
386 external = true;
387
388 return x.minus(q);
389 };
390
391
392 /*
393 * Return a new Decimal whose value is the natural exponential of the value of this Decimal,
394 * i.e. the base e raised to the power the value of this Decimal, truncated to `precision`
395 * significant digits.
396 *
397 */
398 P.naturalExponential = P.exp = function () {
399 return exp(this);
400 };
401
402
403 /*
404 * Return a new Decimal whose value is the natural logarithm of the value of this Decimal,
405 * truncated to `precision` significant digits.
406 *
407 */
408 P.naturalLogarithm = P.ln = function () {
409 return ln(this);
410 };
411
412
413 /*
414 * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by
415 * -1.
416 *
417 */
418 P.negated = P.neg = function () {
419 var x = new this.constructor(this);
420 x.s = -x.s || 0;
421 return x;
422 };
423
424
425 /*
426 * Return a new Decimal whose value is the value of this Decimal plus `y`, truncated to
427 * `precision` significant digits.
428 *
429 */
430 P.plus = P.add = function (y) {
431 var x = this;
432 y = new x.constructor(y);
433 return x.s == y.s ? add(x, y) : subtract(x, (y.s = -y.s, y));
434 };
435
436
437 /*
438 * Return the number of significant digits of the value of this Decimal.
439 *
440 * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
441 *
442 */
443 P.precision = P.sd = function (z) {
444 var e, sd, w,
445 x = this;
446
447 if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z);
448
449 e = getBase10Exponent(x) + 1;
450 w = x.d.length - 1;
451 sd = w * LOG_BASE + 1;
452 w = x.d[w];
453
454 // If non-zero...
455 if (w) {
456
457 // Subtract the number of trailing zeros of the last word.
458 for (; w % 10 == 0; w /= 10) sd--;
459
460 // Add the number of digits of the first word.
461 for (w = x.d[0]; w >= 10; w /= 10) sd++;
462 }
463
464 return z && e > sd ? e : sd;
465 };
466
467
468 /*
469 * Return a new Decimal whose value is the square root of this Decimal, truncated to `precision`
470 * significant digits.
471 *
472 */
473 P.squareRoot = P.sqrt = function () {
474 var e, n, pr, r, s, t, wpr,
475 x = this,
476 Ctor = x.constructor;
477
478 // Negative or zero?
479 if (x.s < 1) {
480 if (!x.s) return new Ctor(0);
481
482 // sqrt(-x) = NaN
483 throw Error(decimalError + 'NaN');
484 }
485
486 e = getBase10Exponent(x);
487 external = false;
488
489 // Initial estimate.
490 s = Math.sqrt(+x);
491
492 // Math.sqrt underflow/overflow?
493 // Pass x to Math.sqrt as integer, then adjust the exponent of the result.
494 if (s == 0 || s == 1 / 0) {
495 n = digitsToString(x.d);
496 if ((n.length + e) % 2 == 0) n += '0';
497 s = Math.sqrt(n);
498 e = mathfloor((e + 1) / 2) - (e < 0 || e % 2);
499
500 if (s == 1 / 0) {
501 n = '5e' + e;
502 } else {
503 n = s.toExponential();
504 n = n.slice(0, n.indexOf('e') + 1) + e;
505 }
506
507 r = new Ctor(n);
508 } else {
509 r = new Ctor(s.toString());
510 }
511
512 pr = Ctor.precision;
513 s = wpr = pr + 3;
514
515 // Newton-Raphson iteration.
516 for (;;) {
517 t = r;
518 r = t.plus(divide(x, t, wpr + 2)).times(0.5);
519
520 if (digitsToString(t.d).slice(0, wpr) === (n = digitsToString(r.d)).slice(0, wpr)) {
521 n = n.slice(wpr - 3, wpr + 1);
522
523 // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or
524 // 4999, i.e. approaching a rounding boundary, continue the iteration.
525 if (s == wpr && n == '4999') {
526
527 // On the first iteration only, check to see if rounding up gives the exact result as the
528 // nines may infinitely repeat.
529 round(t, pr + 1, 0);
530
531 if (t.times(t).eq(x)) {
532 r = t;
533 break;
534 }
535 } else if (n != '9999') {
536 break;
537 }
538
539 wpr += 4;
540 }
541 }
542
543 external = true;
544
545 return round(r, pr);
546 };
547
548
549 /*
550 * Return a new Decimal whose value is the value of this Decimal times `y`, truncated to
551 * `precision` significant digits.
552 *
553 */
554 P.times = P.mul = function (y) {
555 var carry, e, i, k, r, rL, t, xdL, ydL,
556 x = this,
557 Ctor = x.constructor,
558 xd = x.d,
559 yd = (y = new Ctor(y)).d;
560
561 // Return 0 if either is 0.
562 if (!x.s || !y.s) return new Ctor(0);
563
564 y.s *= x.s;
565 e = x.e + y.e;
566 xdL = xd.length;
567 ydL = yd.length;
568
569 // Ensure xd points to the longer array.
570 if (xdL < ydL) {
571 r = xd;
572 xd = yd;
573 yd = r;
574 rL = xdL;
575 xdL = ydL;
576 ydL = rL;
577 }
578
579 // Initialise the result array with zeros.
580 r = [];
581 rL = xdL + ydL;
582 for (i = rL; i--;) r.push(0);
583
584 // Multiply!
585 for (i = ydL; --i >= 0;) {
586 carry = 0;
587 for (k = xdL + i; k > i;) {
588 t = r[k] + yd[i] * xd[k - i - 1] + carry;
589 r[k--] = t % BASE | 0;
590 carry = t / BASE | 0;
591 }
592
593 r[k] = (r[k] + carry) % BASE | 0;
594 }
595
596 // Remove trailing zeros.
597 for (; !r[--rL];) r.pop();
598
599 if (carry) ++e;
600 else r.shift();
601
602 y.d = r;
603 y.e = e;
604
605 return external ? round(y, Ctor.precision) : y;
606 };
607
608
609 /*
610 * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp`
611 * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted.
612 *
613 * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal.
614 *
615 * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
616 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
617 *
618 */
619 P.toDecimalPlaces = P.todp = function (dp, rm) {
620 var x = this,
621 Ctor = x.constructor;
622
623 x = new Ctor(x);
624 if (dp === void 0) return x;
625
626 checkInt32(dp, 0, MAX_DIGITS);
627
628 if (rm === void 0) rm = Ctor.rounding;
629 else checkInt32(rm, 0, 8);
630
631 return round(x, dp + getBase10Exponent(x) + 1, rm);
632 };
633
634
635 /*
636 * Return a string representing the value of this Decimal in exponential notation rounded to
637 * `dp` fixed decimal places using rounding mode `rounding`.
638 *
639 * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
640 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
641 *
642 */
643 P.toExponential = function (dp, rm) {
644 var str,
645 x = this,
646 Ctor = x.constructor;
647
648 if (dp === void 0) {
649 str = toString(x, true);
650 } else {
651 checkInt32(dp, 0, MAX_DIGITS);
652
653 if (rm === void 0) rm = Ctor.rounding;
654 else checkInt32(rm, 0, 8);
655
656 x = round(new Ctor(x), dp + 1, rm);
657 str = toString(x, true, dp + 1);
658 }
659
660 return str;
661 };
662
663
664 /*
665 * Return a string representing the value of this Decimal in normal (fixed-point) notation to
666 * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is
667 * omitted.
668 *
669 * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'.
670 *
671 * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
672 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
673 *
674 * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'.
675 * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'.
676 * (-0).toFixed(3) is '0.000'.
677 * (-0.5).toFixed(0) is '-0'.
678 *
679 */
680 P.toFixed = function (dp, rm) {
681 var str, y,
682 x = this,
683 Ctor = x.constructor;
684
685 if (dp === void 0) return toString(x);
686
687 checkInt32(dp, 0, MAX_DIGITS);
688
689 if (rm === void 0) rm = Ctor.rounding;
690 else checkInt32(rm, 0, 8);
691
692 y = round(new Ctor(x), dp + getBase10Exponent(x) + 1, rm);
693 str = toString(y.abs(), false, dp + getBase10Exponent(y) + 1);
694
695 // To determine whether to add the minus sign look at the value before it was rounded,
696 // i.e. look at `x` rather than `y`.
697 return x.isneg() && !x.isZero() ? '-' + str : str;
698 };
699
700
701 /*
702 * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using
703 * rounding mode `rounding`.
704 *
705 */
706 P.toInteger = P.toint = function () {
707 var x = this,
708 Ctor = x.constructor;
709 return round(new Ctor(x), getBase10Exponent(x) + 1, Ctor.rounding);
710 };
711
712
713 /*
714 * Return the value of this Decimal converted to a number primitive.
715 *
716 */
717 P.toNumber = function () {
718 return +this;
719 };
720
721
722 /*
723 * Return a new Decimal whose value is the value of this Decimal raised to the power `y`,
724 * truncated to `precision` significant digits.
725 *
726 * For non-integer or very large exponents pow(x, y) is calculated using
727 *
728 * x^y = exp(y*ln(x))
729 *
730 * The maximum error is 1 ulp (unit in last place).
731 *
732 * y {number|string|Decimal} The power to which to raise this Decimal.
733 *
734 */
735 P.toPower = P.pow = function (y) {
736 var e, k, pr, r, sign, yIsInt,
737 x = this,
738 Ctor = x.constructor,
739 guard = 12,
740 yn = +(y = new Ctor(y));
741
742 // pow(x, 0) = 1
743 if (!y.s) return new Ctor(ONE);
744
745 x = new Ctor(x);
746
747 // pow(0, y > 0) = 0
748 // pow(0, y < 0) = Infinity
749 if (!x.s) {
750 if (y.s < 1) throw Error(decimalError + 'Infinity');
751 return x;
752 }
753
754 // pow(1, y) = 1
755 if (x.eq(ONE)) return x;
756
757 pr = Ctor.precision;
758
759 // pow(x, 1) = x
760 if (y.eq(ONE)) return round(x, pr);
761
762 e = y.e;
763 k = y.d.length - 1;
764 yIsInt = e >= k;
765 sign = x.s;
766
767 if (!yIsInt) {
768
769 // pow(x < 0, y non-integer) = NaN
770 if (sign < 0) throw Error(decimalError + 'NaN');
771
772 // If y is a small integer use the 'exponentiation by squaring' algorithm.
773 } else if ((k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) {
774 r = new Ctor(ONE);
775
776 // Max k of 9007199254740991 takes 53 loop iterations.
777 // Maximum digits array length; leaves [28, 34] guard digits.
778 e = Math.ceil(pr / LOG_BASE + 4);
779
780 external = false;
781
782 for (;;) {
783 if (k % 2) {
784 r = r.times(x);
785 truncate(r.d, e);
786 }
787
788 k = mathfloor(k / 2);
789 if (k === 0) break;
790
791 x = x.times(x);
792 truncate(x.d, e);
793 }
794
795 external = true;
796
797 return y.s < 0 ? new Ctor(ONE).div(r) : round(r, pr);
798 }
799
800 // Result is negative if x is negative and the last digit of integer y is odd.
801 sign = sign < 0 && y.d[Math.max(e, k)] & 1 ? -1 : 1;
802
803 x.s = 1;
804 external = false;
805 r = y.times(ln(x, pr + guard));
806 external = true;
807 r = exp(r);
808 r.s = sign;
809
810 return r;
811 };
812
813
814 /*
815 * Return a string representing the value of this Decimal rounded to `sd` significant digits
816 * using rounding mode `rounding`.
817 *
818 * Return exponential notation if `sd` is less than the number of digits necessary to represent
819 * the integer part of the value in normal notation.
820 *
821 * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
822 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
823 *
824 */
825 P.toPrecision = function (sd, rm) {
826 var e, str,
827 x = this,
828 Ctor = x.constructor;
829
830 if (sd === void 0) {
831 e = getBase10Exponent(x);
832 str = toString(x, e <= Ctor.toExpNeg || e >= Ctor.toExpPos);
833 } else {
834 checkInt32(sd, 1, MAX_DIGITS);
835
836 if (rm === void 0) rm = Ctor.rounding;
837 else checkInt32(rm, 0, 8);
838
839 x = round(new Ctor(x), sd, rm);
840 e = getBase10Exponent(x);
841 str = toString(x, sd <= e || e <= Ctor.toExpNeg, sd);
842 }
843
844 return str;
845 };
846
847
848 /*
849 * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd`
850 * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if
851 * omitted.
852 *
853 * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
854 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
855 *
856 */
857 P.toSignificantDigits = P.tosd = function (sd, rm) {
858 var x = this,
859 Ctor = x.constructor;
860
861 if (sd === void 0) {
862 sd = Ctor.precision;
863 rm = Ctor.rounding;
864 } else {
865 checkInt32(sd, 1, MAX_DIGITS);
866
867 if (rm === void 0) rm = Ctor.rounding;
868 else checkInt32(rm, 0, 8);
869 }
870
871 return round(new Ctor(x), sd, rm);
872 };
873
874
875 /*
876 * Return a string representing the value of this Decimal.
877 *
878 * Return exponential notation if this Decimal has a positive exponent equal to or greater than
879 * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`.
880 *
881 */
882 P.toString = P.valueOf = P.val = P.toJSON = function () {
883 var x = this,
884 e = getBase10Exponent(x),
885 Ctor = x.constructor;
886
887 return toString(x, e <= Ctor.toExpNeg || e >= Ctor.toExpPos);
888 };
889
890
891 // Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers.
892
893
894 /*
895 * add P.minus, P.plus
896 * checkInt32 P.todp, P.toExponential, P.toFixed, P.toPrecision, P.tosd
897 * digitsToString P.log, P.sqrt, P.pow, toString, exp, ln
898 * divide P.div, P.idiv, P.log, P.mod, P.sqrt, exp, ln
899 * exp P.exp, P.pow
900 * getBase10Exponent P.exponent, P.sd, P.toint, P.sqrt, P.todp, P.toFixed, P.toPrecision,
901 * P.toString, divide, round, toString, exp, ln
902 * getLn10 P.log, ln
903 * getZeroString digitsToString, toString
904 * ln P.log, P.ln, P.pow, exp
905 * parseDecimal Decimal
906 * round P.abs, P.idiv, P.log, P.minus, P.mod, P.neg, P.plus, P.toint, P.sqrt,
907 * P.times, P.todp, P.toExponential, P.toFixed, P.pow, P.toPrecision, P.tosd,
908 * divide, getLn10, exp, ln
909 * subtract P.minus, P.plus
910 * toString P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf
911 * truncate P.pow
912 *
913 * Throws: P.log, P.mod, P.sd, P.sqrt, P.pow, checkInt32, divide, round,
914 * getLn10, exp, ln, parseDecimal, Decimal, config
915 */
916
917
918 function add(x, y) {
919 var carry, d, e, i, k, len, xd, yd,
920 Ctor = x.constructor,
921 pr = Ctor.precision;
922
923 // If either is zero...
924 if (!x.s || !y.s) {
925
926 // Return x if y is zero.
927 // Return y if y is non-zero.
928 if (!y.s) y = new Ctor(x);
929 return external ? round(y, pr) : y;
930 }
931
932 xd = x.d;
933 yd = y.d;
934
935 // x and y are finite, non-zero numbers with the same sign.
936
937 k = x.e;
938 e = y.e;
939 xd = xd.slice();
940 i = k - e;
941
942 // If base 1e7 exponents differ...
943 if (i) {
944 if (i < 0) {
945 d = xd;
946 i = -i;
947 len = yd.length;
948 } else {
949 d = yd;
950 e = k;
951 len = xd.length;
952 }
953
954 // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1.
955 k = Math.ceil(pr / LOG_BASE);
956 len = k > len ? k + 1 : len + 1;
957
958 if (i > len) {
959 i = len;
960 d.length = 1;
961 }
962
963 // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts.
964 d.reverse();
965 for (; i--;) d.push(0);
966 d.reverse();
967 }
968
969 len = xd.length;
970 i = yd.length;
971
972 // If yd is longer than xd, swap xd and yd so xd points to the longer array.
973 if (len - i < 0) {
974 i = len;
975 d = yd;
976 yd = xd;
977 xd = d;
978 }
979
980 // Only start adding at yd.length - 1 as the further digits of xd can be left as they are.
981 for (carry = 0; i;) {
982 carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0;
983 xd[i] %= BASE;
984 }
985
986 if (carry) {
987 xd.unshift(carry);
988 ++e;
989 }
990
991 // Remove trailing zeros.
992 // No need to check for zero, as +x + +y != 0 && -x + -y != 0
993 for (len = xd.length; xd[--len] == 0;) xd.pop();
994
995 y.d = xd;
996 y.e = e;
997
998 return external ? round(y, pr) : y;
999 }
1000
1001
1002 function checkInt32(i, min, max) {
1003 if (i !== ~~i || i < min || i > max) {
1004 throw Error(invalidArgument + i);
1005 }
1006 }
1007
1008
1009 function digitsToString(d) {
1010 var i, k, ws,
1011 indexOfLastWord = d.length - 1,
1012 str = '',
1013 w = d[0];
1014
1015 if (indexOfLastWord > 0) {
1016 str += w;
1017 for (i = 1; i < indexOfLastWord; i++) {
1018 ws = d[i] + '';
1019 k = LOG_BASE - ws.length;
1020 if (k) str += getZeroString(k);
1021 str += ws;
1022 }
1023
1024 w = d[i];
1025 ws = w + '';
1026 k = LOG_BASE - ws.length;
1027 if (k) str += getZeroString(k);
1028 } else if (w === 0) {
1029 return '0';
1030 }
1031
1032 // Remove trailing zeros of last w.
1033 for (; w % 10 === 0;) w /= 10;
1034
1035 return str + w;
1036 }
1037
1038
1039 var divide = (function () {
1040
1041 // Assumes non-zero x and k, and hence non-zero result.
1042 function multiplyInteger(x, k) {
1043 var temp,
1044 carry = 0,
1045 i = x.length;
1046
1047 for (x = x.slice(); i--;) {
1048 temp = x[i] * k + carry;
1049 x[i] = temp % BASE | 0;
1050 carry = temp / BASE | 0;
1051 }
1052
1053 if (carry) x.unshift(carry);
1054
1055 return x;
1056 }
1057
1058 function compare(a, b, aL, bL) {
1059 var i, r;
1060
1061 if (aL != bL) {
1062 r = aL > bL ? 1 : -1;
1063 } else {
1064 for (i = r = 0; i < aL; i++) {
1065 if (a[i] != b[i]) {
1066 r = a[i] > b[i] ? 1 : -1;
1067 break;
1068 }
1069 }
1070 }
1071
1072 return r;
1073 }
1074
1075 function subtract(a, b, aL) {
1076 var i = 0;
1077
1078 // Subtract b from a.
1079 for (; aL--;) {
1080 a[aL] -= i;
1081 i = a[aL] < b[aL] ? 1 : 0;
1082 a[aL] = i * BASE + a[aL] - b[aL];
1083 }
1084
1085 // Remove leading zeros.
1086 for (; !a[0] && a.length > 1;) a.shift();
1087 }
1088
1089 return function (x, y, pr, dp) {
1090 var cmp, e, i, k, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0, yL, yz,
1091 Ctor = x.constructor,
1092 sign = x.s == y.s ? 1 : -1,
1093 xd = x.d,
1094 yd = y.d;
1095
1096 // Either 0?
1097 if (!x.s) return new Ctor(x);
1098 if (!y.s) throw Error(decimalError + 'Division by zero');
1099
1100 e = x.e - y.e;
1101 yL = yd.length;
1102 xL = xd.length;
1103 q = new Ctor(sign);
1104 qd = q.d = [];
1105
1106 // Result exponent may be one less than e.
1107 for (i = 0; yd[i] == (xd[i] || 0); ) ++i;
1108 if (yd[i] > (xd[i] || 0)) --e;
1109
1110 if (pr == null) {
1111 sd = pr = Ctor.precision;
1112 } else if (dp) {
1113 sd = pr + (getBase10Exponent(x) - getBase10Exponent(y)) + 1;
1114 } else {
1115 sd = pr;
1116 }
1117
1118 if (sd < 0) return new Ctor(0);
1119
1120 // Convert precision in number of base 10 digits to base 1e7 digits.
1121 sd = sd / LOG_BASE + 2 | 0;
1122 i = 0;
1123
1124 // divisor < 1e7
1125 if (yL == 1) {
1126 k = 0;
1127 yd = yd[0];
1128 sd++;
1129
1130 // k is the carry.
1131 for (; (i < xL || k) && sd--; i++) {
1132 t = k * BASE + (xd[i] || 0);
1133 qd[i] = t / yd | 0;
1134 k = t % yd | 0;
1135 }
1136
1137 // divisor >= 1e7
1138 } else {
1139
1140 // Normalise xd and yd so highest order digit of yd is >= BASE/2
1141 k = BASE / (yd[0] + 1) | 0;
1142
1143 if (k > 1) {
1144 yd = multiplyInteger(yd, k);
1145 xd = multiplyInteger(xd, k);
1146 yL = yd.length;
1147 xL = xd.length;
1148 }
1149
1150 xi = yL;
1151 rem = xd.slice(0, yL);
1152 remL = rem.length;
1153
1154 // Add zeros to make remainder as long as divisor.
1155 for (; remL < yL;) rem[remL++] = 0;
1156
1157 yz = yd.slice();
1158 yz.unshift(0);
1159 yd0 = yd[0];
1160
1161 if (yd[1] >= BASE / 2) ++yd0;
1162
1163 do {
1164 k = 0;
1165
1166 // Compare divisor and remainder.
1167 cmp = compare(yd, rem, yL, remL);
1168
1169 // If divisor < remainder.
1170 if (cmp < 0) {
1171
1172 // Calculate trial digit, k.
1173 rem0 = rem[0];
1174 if (yL != remL) rem0 = rem0 * BASE + (rem[1] || 0);
1175
1176 // k will be how many times the divisor goes into the current remainder.
1177 k = rem0 / yd0 | 0;
1178
1179 // Algorithm:
1180 // 1. product = divisor * trial digit (k)
1181 // 2. if product > remainder: product -= divisor, k--
1182 // 3. remainder -= product
1183 // 4. if product was < remainder at 2:
1184 // 5. compare new remainder and divisor
1185 // 6. If remainder > divisor: remainder -= divisor, k++
1186
1187 if (k > 1) {
1188 if (k >= BASE) k = BASE - 1;
1189
1190 // product = divisor * trial digit.
1191 prod = multiplyInteger(yd, k);
1192 prodL = prod.length;
1193 remL = rem.length;
1194
1195 // Compare product and remainder.
1196 cmp = compare(prod, rem, prodL, remL);
1197
1198 // product > remainder.
1199 if (cmp == 1) {
1200 k--;
1201
1202 // Subtract divisor from product.
1203 subtract(prod, yL < prodL ? yz : yd, prodL);
1204 }
1205 } else {
1206
1207 // cmp is -1.
1208 // If k is 0, there is no need to compare yd and rem again below, so change cmp to 1
1209 // to avoid it. If k is 1 there is a need to compare yd and rem again below.
1210 if (k == 0) cmp = k = 1;
1211 prod = yd.slice();
1212 }
1213
1214 prodL = prod.length;
1215 if (prodL < remL) prod.unshift(0);
1216
1217 // Subtract product from remainder.
1218 subtract(rem, prod, remL);
1219
1220 // If product was < previous remainder.
1221 if (cmp == -1) {
1222 remL = rem.length;
1223
1224 // Compare divisor and new remainder.
1225 cmp = compare(yd, rem, yL, remL);
1226
1227 // If divisor < new remainder, subtract divisor from remainder.
1228 if (cmp < 1) {
1229 k++;
1230
1231 // Subtract divisor from remainder.
1232 subtract(rem, yL < remL ? yz : yd, remL);
1233 }
1234 }
1235
1236 remL = rem.length;
1237 } else if (cmp === 0) {
1238 k++;
1239 rem = [0];
1240 } // if cmp === 1, k will be 0
1241
1242 // Add the next digit, k, to the result array.
1243 qd[i++] = k;
1244
1245 // Update the remainder.
1246 if (cmp && rem[0]) {
1247 rem[remL++] = xd[xi] || 0;
1248 } else {
1249 rem = [xd[xi]];
1250 remL = 1;
1251 }
1252
1253 } while ((xi++ < xL || rem[0] !== void 0) && sd--);
1254 }
1255
1256 // Leading zero?
1257 if (!qd[0]) qd.shift();
1258
1259 q.e = e;
1260
1261 return round(q, dp ? pr + getBase10Exponent(q) + 1 : pr);
1262 };
1263 })();
1264
1265
1266 /*
1267 * Return a new Decimal whose value is the natural exponential of `x` truncated to `sd`
1268 * significant digits.
1269 *
1270 * Taylor/Maclaurin series.
1271 *
1272 * exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ...
1273 *
1274 * Argument reduction:
1275 * Repeat x = x / 32, k += 5, until |x| < 0.1
1276 * exp(x) = exp(x / 2^k)^(2^k)
1277 *
1278 * Previously, the argument was initially reduced by
1279 * exp(x) = exp(r) * 10^k where r = x - k * ln10, k = floor(x / ln10)
1280 * to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was
1281 * found to be slower than just dividing repeatedly by 32 as above.
1282 *
1283 * (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324)
1284 *
1285 * exp(x) is non-terminating for any finite, non-zero x.
1286 *
1287 */
1288 function exp(x, sd) {
1289 var denominator, guard, pow, sum, t, wpr,
1290 i = 0,
1291 k = 0,
1292 Ctor = x.constructor,
1293 pr = Ctor.precision;
1294
1295 if (getBase10Exponent(x) > 16) throw Error(exponentOutOfRange + getBase10Exponent(x));
1296
1297 // exp(0) = 1
1298 if (!x.s) return new Ctor(ONE);
1299
1300 if (sd == null) {
1301 external = false;
1302 wpr = pr;
1303 } else {
1304 wpr = sd;
1305 }
1306
1307 t = new Ctor(0.03125);
1308
1309 while (x.abs().gte(0.1)) {
1310 x = x.times(t); // x = x / 2^5
1311 k += 5;
1312 }
1313
1314 // Estimate the precision increase necessary to ensure the first 4 rounding digits are correct.
1315 guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0;
1316 wpr += guard;
1317 denominator = pow = sum = new Ctor(ONE);
1318 Ctor.precision = wpr;
1319
1320 for (;;) {
1321 pow = round(pow.times(x), wpr);
1322 denominator = denominator.times(++i);
1323 t = sum.plus(divide(pow, denominator, wpr));
1324
1325 if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
1326 while (k--) sum = round(sum.times(sum), wpr);
1327 Ctor.precision = pr;
1328 return sd == null ? (external = true, round(sum, pr)) : sum;
1329 }
1330
1331 sum = t;
1332 }
1333 }
1334
1335
1336 // Calculate the base 10 exponent from the base 1e7 exponent.
1337 function getBase10Exponent(x) {
1338 var e = x.e * LOG_BASE,
1339 w = x.d[0];
1340
1341 // Add the number of digits of the first word of the digits array.
1342 for (; w >= 10; w /= 10) e++;
1343 return e;
1344 }
1345
1346
1347 function getLn10(Ctor, sd, pr) {
1348
1349 if (sd > Ctor.LN10.sd()) {
1350
1351
1352 // Reset global state in case the exception is caught.
1353 external = true;
1354 if (pr) Ctor.precision = pr;
1355 throw Error(decimalError + 'LN10 precision limit exceeded');
1356 }
1357
1358 return round(new Ctor(Ctor.LN10), sd);
1359 }
1360
1361
1362 function getZeroString(k) {
1363 var zs = '';
1364 for (; k--;) zs += '0';
1365 return zs;
1366 }
1367
1368
1369 /*
1370 * Return a new Decimal whose value is the natural logarithm of `x` truncated to `sd` significant
1371 * digits.
1372 *
1373 * ln(n) is non-terminating (n != 1)
1374 *
1375 */
1376 function ln(y, sd) {
1377 var c, c0, denominator, e, numerator, sum, t, wpr, x2,
1378 n = 1,
1379 guard = 10,
1380 x = y,
1381 xd = x.d,
1382 Ctor = x.constructor,
1383 pr = Ctor.precision;
1384
1385 // ln(-x) = NaN
1386 // ln(0) = -Infinity
1387 if (x.s < 1) throw Error(decimalError + (x.s ? 'NaN' : '-Infinity'));
1388
1389 // ln(1) = 0
1390 if (x.eq(ONE)) return new Ctor(0);
1391
1392 if (sd == null) {
1393 external = false;
1394 wpr = pr;
1395 } else {
1396 wpr = sd;
1397 }
1398
1399 if (x.eq(10)) {
1400 if (sd == null) external = true;
1401 return getLn10(Ctor, wpr);
1402 }
1403
1404 wpr += guard;
1405 Ctor.precision = wpr;
1406 c = digitsToString(xd);
1407 c0 = c.charAt(0);
1408 e = getBase10Exponent(x);
1409
1410 if (Math.abs(e) < 1.5e15) {
1411
1412 // Argument reduction.
1413 // The series converges faster the closer the argument is to 1, so using
1414 // ln(a^b) = b * ln(a), ln(a) = ln(a^b) / b
1415 // multiply the argument by itself until the leading digits of the significand are 7, 8, 9,
1416 // 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can
1417 // later be divided by this number, then separate out the power of 10 using
1418 // ln(a*10^b) = ln(a) + b*ln(10).
1419
1420 // max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14).
1421 //while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) {
1422 // max n is 6 (gives 0.7 - 1.3)
1423 while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) {
1424 x = x.times(y);
1425 c = digitsToString(x.d);
1426 c0 = c.charAt(0);
1427 n++;
1428 }
1429
1430 e = getBase10Exponent(x);
1431
1432 if (c0 > 1) {
1433 x = new Ctor('0.' + c);
1434 e++;
1435 } else {
1436 x = new Ctor(c0 + '.' + c.slice(1));
1437 }
1438 } else {
1439
1440 // The argument reduction method above may result in overflow if the argument y is a massive
1441 // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this
1442 // function using ln(x*10^e) = ln(x) + e*ln(10).
1443 t = getLn10(Ctor, wpr + 2, pr).times(e + '');
1444 x = ln(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t);
1445
1446 Ctor.precision = pr;
1447 return sd == null ? (external = true, round(x, pr)) : x;
1448 }
1449
1450 // x is reduced to a value near 1.
1451
1452 // Taylor series.
1453 // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...)
1454 // where x = (y - 1)/(y + 1) (|x| < 1)
1455 sum = numerator = x = divide(x.minus(ONE), x.plus(ONE), wpr);
1456 x2 = round(x.times(x), wpr);
1457 denominator = 3;
1458
1459 for (;;) {
1460 numerator = round(numerator.times(x2), wpr);
1461 t = sum.plus(divide(numerator, new Ctor(denominator), wpr));
1462
1463 if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
1464 sum = sum.times(2);
1465
1466 // Reverse the argument reduction.
1467 if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + ''));
1468 sum = divide(sum, new Ctor(n), wpr);
1469
1470 Ctor.precision = pr;
1471 return sd == null ? (external = true, round(sum, pr)) : sum;
1472 }
1473
1474 sum = t;
1475 denominator += 2;
1476 }
1477 }
1478
1479
1480 /*
1481 * Parse the value of a new Decimal `x` from string `str`.
1482 */
1483 function parseDecimal(x, str) {
1484 var e, i, len;
1485
1486 // Decimal point?
1487 if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');
1488
1489 // Exponential form?
1490 if ((i = str.search(/e/i)) > 0) {
1491
1492 // Determine exponent.
1493 if (e < 0) e = i;
1494 e += +str.slice(i + 1);
1495 str = str.substring(0, i);
1496 } else if (e < 0) {
1497
1498 // Integer.
1499 e = str.length;
1500 }
1501
1502 // Determine leading zeros.
1503 for (i = 0; str.charCodeAt(i) === 48;) ++i;
1504
1505 // Determine trailing zeros.
1506 for (len = str.length; str.charCodeAt(len - 1) === 48;) --len;
1507 str = str.slice(i, len);
1508
1509 if (str) {
1510 len -= i;
1511 e = e - i - 1;
1512 x.e = mathfloor(e / LOG_BASE);
1513 x.d = [];
1514
1515 // Transform base
1516
1517 // e is the base 10 exponent.
1518 // i is where to slice str to get the first word of the digits array.
1519 i = (e + 1) % LOG_BASE;
1520 if (e < 0) i += LOG_BASE;
1521
1522 if (i < len) {
1523 if (i) x.d.push(+str.slice(0, i));
1524 for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE));
1525 str = str.slice(i);
1526 i = LOG_BASE - str.length;
1527 } else {
1528 i -= len;
1529 }
1530
1531 for (; i--;) str += '0';
1532 x.d.push(+str);
1533
1534 if (external && (x.e > MAX_E || x.e < -MAX_E)) throw Error(exponentOutOfRange + e);
1535 } else {
1536
1537 // Zero.
1538 x.s = 0;
1539 x.e = 0;
1540 x.d = [0];
1541 }
1542
1543 return x;
1544 }
1545
1546
1547 /*
1548 * Round `x` to `sd` significant digits, using rounding mode `rm` if present (truncate otherwise).
1549 */
1550 function round(x, sd, rm) {
1551 var i, j, k, n, rd, doRound, w, xdi,
1552 xd = x.d;
1553
1554 // rd: the rounding digit, i.e. the digit after the digit that may be rounded up.
1555 // w: the word of xd which contains the rounding digit, a base 1e7 number.
1556 // xdi: the index of w within xd.
1557 // n: the number of digits of w.
1558 // i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if
1559 // they had leading zeros)
1560 // j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero).
1561
1562 // Get the length of the first word of the digits array xd.
1563 for (n = 1, k = xd[0]; k >= 10; k /= 10) n++;
1564 i = sd - n;
1565
1566 // Is the rounding digit in the first word of xd?
1567 if (i < 0) {
1568 i += LOG_BASE;
1569 j = sd;
1570 w = xd[xdi = 0];
1571 } else {
1572 xdi = Math.ceil((i + 1) / LOG_BASE);
1573 k = xd.length;
1574 if (xdi >= k) return x;
1575 w = k = xd[xdi];
1576
1577 // Get the number of digits of w.
1578 for (n = 1; k >= 10; k /= 10) n++;
1579
1580 // Get the index of rd within w.
1581 i %= LOG_BASE;
1582
1583 // Get the index of rd within w, adjusted for leading zeros.
1584 // The number of leading zeros of w is given by LOG_BASE - n.
1585 j = i - LOG_BASE + n;
1586 }
1587
1588 if (rm !== void 0) {
1589 k = mathpow(10, n - j - 1);
1590
1591 // Get the rounding digit at index j of w.
1592 rd = w / k % 10 | 0;
1593
1594 // Are there any non-zero digits after the rounding digit?
1595 doRound = sd < 0 || xd[xdi + 1] !== void 0 || w % k;
1596
1597 // The expression `w % mathpow(10, n - j - 1)` returns all the digits of w to the right of the
1598 // digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression will give
1599 // 714.
1600
1601 doRound = rm < 4
1602 ? (rd || doRound) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))
1603 : rd > 5 || rd == 5 && (rm == 4 || doRound || rm == 6 &&
1604
1605 // Check whether the digit to the left of the rounding digit is odd.
1606 ((i > 0 ? j > 0 ? w / mathpow(10, n - j) : 0 : xd[xdi - 1]) % 10) & 1 ||
1607 rm == (x.s < 0 ? 8 : 7));
1608 }
1609
1610 if (sd < 1 || !xd[0]) {
1611 if (doRound) {
1612 k = getBase10Exponent(x);
1613 xd.length = 1;
1614
1615 // Convert sd to decimal places.
1616 sd = sd - k - 1;
1617
1618 // 1, 0.1, 0.01, 0.001, 0.0001 etc.
1619 xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE);
1620 x.e = mathfloor(-sd / LOG_BASE) || 0;
1621 } else {
1622 xd.length = 1;
1623
1624 // Zero.
1625 xd[0] = x.e = x.s = 0;
1626 }
1627
1628 return x;
1629 }
1630
1631 // Remove excess digits.
1632 if (i == 0) {
1633 xd.length = xdi;
1634 k = 1;
1635 xdi--;
1636 } else {
1637 xd.length = xdi + 1;
1638 k = mathpow(10, LOG_BASE - i);
1639
1640 // E.g. 56700 becomes 56000 if 7 is the rounding digit.
1641 // j > 0 means i > number of leading zeros of w.
1642 xd[xdi] = j > 0 ? (w / mathpow(10, n - j) % mathpow(10, j) | 0) * k : 0;
1643 }
1644
1645 if (doRound) {
1646 for (;;) {
1647
1648 // Is the digit to be rounded up in the first word of xd?
1649 if (xdi == 0) {
1650 if ((xd[0] += k) == BASE) {
1651 xd[0] = 1;
1652 ++x.e;
1653 }
1654
1655 break;
1656 } else {
1657 xd[xdi] += k;
1658 if (xd[xdi] != BASE) break;
1659 xd[xdi--] = 0;
1660 k = 1;
1661 }
1662 }
1663 }
1664
1665 // Remove trailing zeros.
1666 for (i = xd.length; xd[--i] === 0;) xd.pop();
1667
1668 if (external && (x.e > MAX_E || x.e < -MAX_E)) {
1669 throw Error(exponentOutOfRange + getBase10Exponent(x));
1670 }
1671
1672 return x;
1673 }
1674
1675
1676 function subtract(x, y) {
1677 var d, e, i, j, k, len, xd, xe, xLTy, yd,
1678 Ctor = x.constructor,
1679 pr = Ctor.precision;
1680
1681 // Return y negated if x is zero.
1682 // Return x if y is zero and x is non-zero.
1683 if (!x.s || !y.s) {
1684 if (y.s) y.s = -y.s;
1685 else y = new Ctor(x);
1686 return external ? round(y, pr) : y;
1687 }
1688
1689 xd = x.d;
1690 yd = y.d;
1691
1692 // x and y are non-zero numbers with the same sign.
1693
1694 e = y.e;
1695 xe = x.e;
1696 xd = xd.slice();
1697 k = xe - e;
1698
1699 // If exponents differ...
1700 if (k) {
1701 xLTy = k < 0;
1702
1703 if (xLTy) {
1704 d = xd;
1705 k = -k;
1706 len = yd.length;
1707 } else {
1708 d = yd;
1709 e = xe;
1710 len = xd.length;
1711 }
1712
1713 // Numbers with massively different exponents would result in a very high number of zeros
1714 // needing to be prepended, but this can be avoided while still ensuring correct rounding by
1715 // limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`.
1716 i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2;
1717
1718 if (k > i) {
1719 k = i;
1720 d.length = 1;
1721 }
1722
1723 // Prepend zeros to equalise exponents.
1724 d.reverse();
1725 for (i = k; i--;) d.push(0);
1726 d.reverse();
1727
1728 // Base 1e7 exponents equal.
1729 } else {
1730
1731 // Check digits to determine which is the bigger number.
1732
1733 i = xd.length;
1734 len = yd.length;
1735 xLTy = i < len;
1736 if (xLTy) len = i;
1737
1738 for (i = 0; i < len; i++) {
1739 if (xd[i] != yd[i]) {
1740 xLTy = xd[i] < yd[i];
1741 break;
1742 }
1743 }
1744
1745 k = 0;
1746 }
1747
1748 if (xLTy) {
1749 d = xd;
1750 xd = yd;
1751 yd = d;
1752 y.s = -y.s;
1753 }
1754
1755 len = xd.length;
1756
1757 // Append zeros to xd if shorter.
1758 // Don't add zeros to yd if shorter as subtraction only needs to start at yd length.
1759 for (i = yd.length - len; i > 0; --i) xd[len++] = 0;
1760
1761 // Subtract yd from xd.
1762 for (i = yd.length; i > k;) {
1763 if (xd[--i] < yd[i]) {
1764 for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1;
1765 --xd[j];
1766 xd[i] += BASE;
1767 }
1768
1769 xd[i] -= yd[i];
1770 }
1771
1772 // Remove trailing zeros.
1773 for (; xd[--len] === 0;) xd.pop();
1774
1775 // Remove leading zeros and adjust exponent accordingly.
1776 for (; xd[0] === 0; xd.shift()) --e;
1777
1778 // Zero?
1779 if (!xd[0]) return new Ctor(0);
1780
1781 y.d = xd;
1782 y.e = e;
1783
1784 //return external && xd.length >= pr / LOG_BASE ? round(y, pr) : y;
1785 return external ? round(y, pr) : y;
1786 }
1787
1788
1789 function toString(x, isExp, sd) {
1790 var k,
1791 e = getBase10Exponent(x),
1792 str = digitsToString(x.d),
1793 len = str.length;
1794
1795 if (isExp) {
1796 if (sd && (k = sd - len) > 0) {
1797 str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k);
1798 } else if (len > 1) {
1799 str = str.charAt(0) + '.' + str.slice(1);
1800 }
1801
1802 str = str + (e < 0 ? 'e' : 'e+') + e;
1803 } else if (e < 0) {
1804 str = '0.' + getZeroString(-e - 1) + str;
1805 if (sd && (k = sd - len) > 0) str += getZeroString(k);
1806 } else if (e >= len) {
1807 str += getZeroString(e + 1 - len);
1808 if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k);
1809 } else {
1810 if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k);
1811 if (sd && (k = sd - len) > 0) {
1812 if (e + 1 === len) str += '.';
1813 str += getZeroString(k);
1814 }
1815 }
1816
1817 return x.s < 0 ? '-' + str : str;
1818 }
1819
1820
1821 // Does not strip trailing zeros.
1822 function truncate(arr, len) {
1823 if (arr.length > len) {
1824 arr.length = len;
1825 return true;
1826 }
1827 }
1828
1829
1830 // Decimal methods
1831
1832
1833 /*
1834 * clone
1835 * config/set
1836 */
1837
1838
1839 /*
1840 * Create and return a Decimal constructor with the same configuration properties as this Decimal
1841 * constructor.
1842 *
1843 */
1844 function clone(obj) {
1845 var i, p, ps;
1846
1847 /*
1848 * The Decimal constructor and exported function.
1849 * Return a new Decimal instance.
1850 *
1851 * value {number|string|Decimal} A numeric value.
1852 *
1853 */
1854 function Decimal(value) {
1855 var x = this;
1856
1857 // Decimal called without new.
1858 if (!(x instanceof Decimal)) return new Decimal(value);
1859
1860 // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor
1861 // which points to Object.
1862 x.constructor = Decimal;
1863
1864 // Duplicate.
1865 if (value instanceof Decimal) {
1866 x.s = value.s;
1867 x.e = value.e;
1868 x.d = (value = value.d) ? value.slice() : value;
1869 return;
1870 }
1871
1872 if (typeof value === 'number') {
1873
1874 // Reject Infinity/NaN.
1875 if (value * 0 !== 0) {
1876 throw Error(invalidArgument + value);
1877 }
1878
1879 if (value > 0) {
1880 x.s = 1;
1881 } else if (value < 0) {
1882 value = -value;
1883 x.s = -1;
1884 } else {
1885 x.s = 0;
1886 x.e = 0;
1887 x.d = [0];
1888 return;
1889 }
1890
1891 // Fast path for small integers.
1892 if (value === ~~value && value < 1e7) {
1893 x.e = 0;
1894 x.d = [value];
1895 return;
1896 }
1897
1898 return parseDecimal(x, value.toString());
1899 } else if (typeof value !== 'string') {
1900 throw Error(invalidArgument + value);
1901 }
1902
1903 // Minus sign?
1904 if (value.charCodeAt(0) === 45) {
1905 value = value.slice(1);
1906 x.s = -1;
1907 } else {
1908 x.s = 1;
1909 }
1910
1911 if (isDecimal.test(value)) parseDecimal(x, value);
1912 else throw Error(invalidArgument + value);
1913 }
1914
1915 Decimal.prototype = P;
1916
1917 Decimal.ROUND_UP = 0;
1918 Decimal.ROUND_DOWN = 1;
1919 Decimal.ROUND_CEIL = 2;
1920 Decimal.ROUND_FLOOR = 3;
1921 Decimal.ROUND_HALF_UP = 4;
1922 Decimal.ROUND_HALF_DOWN = 5;
1923 Decimal.ROUND_HALF_EVEN = 6;
1924 Decimal.ROUND_HALF_CEIL = 7;
1925 Decimal.ROUND_HALF_FLOOR = 8;
1926
1927 Decimal.clone = clone;
1928 Decimal.config = Decimal.set = config;
1929
1930 if (obj === void 0) obj = {};
1931 if (obj) {
1932 ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'LN10'];
1933 for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p];
1934 }
1935
1936 Decimal.config(obj);
1937
1938 return Decimal;
1939 }
1940
1941
1942 /*
1943 * Configure global settings for a Decimal constructor.
1944 *
1945 * `obj` is an object with one or more of the following properties,
1946 *
1947 * precision {number}
1948 * rounding {number}
1949 * toExpNeg {number}
1950 * toExpPos {number}
1951 *
1952 * E.g. Decimal.config({ precision: 20, rounding: 4 })
1953 *
1954 */
1955 function config(obj) {
1956 if (!obj || typeof obj !== 'object') {
1957 throw Error(decimalError + 'Object expected');
1958 }
1959 var i, p, v,
1960 ps = [
1961 'precision', 1, MAX_DIGITS,
1962 'rounding', 0, 8,
1963 'toExpNeg', -1 / 0, 0,
1964 'toExpPos', 0, 1 / 0
1965 ];
1966
1967 for (i = 0; i < ps.length; i += 3) {
1968 if ((v = obj[p = ps[i]]) !== void 0) {
1969 if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v;
1970 else throw Error(invalidArgument + p + ': ' + v);
1971 }
1972 }
1973
1974 if ((v = obj[p = 'LN10']) !== void 0) {
1975 if (v == Math.LN10) this[p] = new this(v);
1976 else throw Error(invalidArgument + p + ': ' + v);
1977 }
1978
1979 return this;
1980 }
1981
1982
1983 // Create and configure initial Decimal constructor.
1984 Decimal = clone(Decimal);
1985
1986 Decimal['default'] = Decimal.Decimal = Decimal;
1987
1988 // Internal constant.
1989 ONE = new Decimal(1);
1990
1991
1992 // Export.
1993
1994
1995 // AMD.
1996 if (typeof define == 'function' && define.amd) {
1997 define(function () {
1998 return Decimal;
1999 });
2000
2001 // Node and other environments that support module.exports.
2002 } else if (typeof module != 'undefined' && module.exports) {
2003 module.exports = Decimal;
2004
2005 // Browser.
2006 } else {
2007 if (!globalScope) {
2008 globalScope = typeof self != 'undefined' && self && self.self == self
2009 ? self : Function('return this')();
2010 }
2011
2012 globalScope.Decimal = Decimal;
2013 }
2014})(this);
Note: See TracBrowser for help on using the repository browser.