-
Notifications
You must be signed in to change notification settings - Fork 48
/
decimal.js
2014 lines (1586 loc) · 50.2 KB
/
decimal.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*! decimal.js-light v2.5.1 https://github.com/MikeMcl/decimal.js-light/LICENCE */
;(function (globalScope) {
'use strict';
/*
* decimal.js-light v2.5.1
* An arbitrary-precision Decimal type for JavaScript.
* https://github.com/MikeMcl/decimal.js-light
* Copyright (c) 2020 Michael Mclaughlin <M8ch88l@gmail.com>
* MIT Expat Licence
*/
// ----------------------------------- EDITABLE DEFAULTS ------------------------------------ //
// The limit on the value of `precision`, and on the value of the first argument to
// `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`.
var MAX_DIGITS = 1e9, // 0 to 1e9
// The initial configuration properties of the Decimal constructor.
Decimal = {
// These values must be integers within the stated ranges (inclusive).
// Most of these values can be changed during run-time using `Decimal.config`.
// The maximum number of significant digits of the result of a calculation or base conversion.
// E.g. `Decimal.config({ precision: 20 });`
precision: 20, // 1 to MAX_DIGITS
// The rounding mode used by default by `toInteger`, `toDecimalPlaces`, `toExponential`,
// `toFixed`, `toPrecision` and `toSignificantDigits`.
//
// ROUND_UP 0 Away from zero.
// ROUND_DOWN 1 Towards zero.
// ROUND_CEIL 2 Towards +Infinity.
// ROUND_FLOOR 3 Towards -Infinity.
// ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up.
// ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
// ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
// ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
// ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
//
// E.g.
// `Decimal.rounding = 4;`
// `Decimal.rounding = Decimal.ROUND_HALF_UP;`
rounding: 4, // 0 to 8
// The exponent value at and beneath which `toString` returns exponential notation.
// JavaScript numbers: -7
toExpNeg: -7, // 0 to -MAX_E
// The exponent value at and above which `toString` returns exponential notation.
// JavaScript numbers: 21
toExpPos: 21, // 0 to MAX_E
// The natural logarithm of 10.
// 115 digits
LN10: '2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286'
},
// ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- //
external = true,
decimalError = '[DecimalError] ',
invalidArgument = decimalError + 'Invalid argument: ',
exponentOutOfRange = decimalError + 'Exponent out of range: ',
mathfloor = Math.floor,
mathpow = Math.pow,
isDecimal = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
ONE,
BASE = 1e7,
LOG_BASE = 7,
MAX_SAFE_INTEGER = 9007199254740991,
MAX_E = mathfloor(MAX_SAFE_INTEGER / LOG_BASE), // 1286742750677284
// Decimal.prototype object
P = {};
// Decimal prototype methods
/*
* absoluteValue abs
* comparedTo cmp
* decimalPlaces dp
* dividedBy div
* dividedToIntegerBy idiv
* equals eq
* exponent
* greaterThan gt
* greaterThanOrEqualTo gte
* isInteger isint
* isNegative isneg
* isPositive ispos
* isZero
* lessThan lt
* lessThanOrEqualTo lte
* logarithm log
* minus sub
* modulo mod
* naturalExponential exp
* naturalLogarithm ln
* negated neg
* plus add
* precision sd
* squareRoot sqrt
* times mul
* toDecimalPlaces todp
* toExponential
* toFixed
* toInteger toint
* toNumber
* toPower pow
* toPrecision
* toSignificantDigits tosd
* toString
* valueOf val
*/
/*
* Return a new Decimal whose value is the absolute value of this Decimal.
*
*/
P.absoluteValue = P.abs = function () {
var x = new this.constructor(this);
if (x.s) x.s = 1;
return x;
};
/*
* Return
* 1 if the value of this Decimal is greater than the value of `y`,
* -1 if the value of this Decimal is less than the value of `y`,
* 0 if they have the same value
*
*/
P.comparedTo = P.cmp = function (y) {
var i, j, xdL, ydL,
x = this;
y = new x.constructor(y);
// Signs differ?
if (x.s !== y.s) return x.s || -y.s;
// Compare exponents.
if (x.e !== y.e) return x.e > y.e ^ x.s < 0 ? 1 : -1;
xdL = x.d.length;
ydL = y.d.length;
// Compare digit by digit.
for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) {
if (x.d[i] !== y.d[i]) return x.d[i] > y.d[i] ^ x.s < 0 ? 1 : -1;
}
// Compare lengths.
return xdL === ydL ? 0 : xdL > ydL ^ x.s < 0 ? 1 : -1;
};
/*
* Return the number of decimal places of the value of this Decimal.
*
*/
P.decimalPlaces = P.dp = function () {
var x = this,
w = x.d.length - 1,
dp = (w - x.e) * LOG_BASE;
// Subtract the number of trailing zeros of the last word.
w = x.d[w];
if (w) for (; w % 10 == 0; w /= 10) dp--;
return dp < 0 ? 0 : dp;
};
/*
* Return a new Decimal whose value is the value of this Decimal divided by `y`, truncated to
* `precision` significant digits.
*
*/
P.dividedBy = P.div = function (y) {
return divide(this, new this.constructor(y));
};
/*
* Return a new Decimal whose value is the integer part of dividing the value of this Decimal
* by the value of `y`, truncated to `precision` significant digits.
*
*/
P.dividedToIntegerBy = P.idiv = function (y) {
var x = this,
Ctor = x.constructor;
return round(divide(x, new Ctor(y), 0, 1), Ctor.precision);
};
/*
* Return true if the value of this Decimal is equal to the value of `y`, otherwise return false.
*
*/
P.equals = P.eq = function (y) {
return !this.cmp(y);
};
/*
* Return the (base 10) exponent value of this Decimal (this.e is the base 10000000 exponent).
*
*/
P.exponent = function () {
return getBase10Exponent(this);
};
/*
* Return true if the value of this Decimal is greater than the value of `y`, otherwise return
* false.
*
*/
P.greaterThan = P.gt = function (y) {
return this.cmp(y) > 0;
};
/*
* Return true if the value of this Decimal is greater than or equal to the value of `y`,
* otherwise return false.
*
*/
P.greaterThanOrEqualTo = P.gte = function (y) {
return this.cmp(y) >= 0;
};
/*
* Return true if the value of this Decimal is an integer, otherwise return false.
*
*/
P.isInteger = P.isint = function () {
return this.e > this.d.length - 2;
};
/*
* Return true if the value of this Decimal is negative, otherwise return false.
*
*/
P.isNegative = P.isneg = function () {
return this.s < 0;
};
/*
* Return true if the value of this Decimal is positive, otherwise return false.
*
*/
P.isPositive = P.ispos = function () {
return this.s > 0;
};
/*
* Return true if the value of this Decimal is 0, otherwise return false.
*
*/
P.isZero = function () {
return this.s === 0;
};
/*
* Return true if the value of this Decimal is less than `y`, otherwise return false.
*
*/
P.lessThan = P.lt = function (y) {
return this.cmp(y) < 0;
};
/*
* Return true if the value of this Decimal is less than or equal to `y`, otherwise return false.
*
*/
P.lessThanOrEqualTo = P.lte = function (y) {
return this.cmp(y) < 1;
};
/*
* Return the logarithm of the value of this Decimal to the specified base, truncated to
* `precision` significant digits.
*
* If no base is specified, return log[10](x).
*
* log[base](x) = ln(x) / ln(base)
*
* The maximum error of the result is 1 ulp (unit in the last place).
*
* [base] {number|string|Decimal} The base of the logarithm.
*
*/
P.logarithm = P.log = function (base) {
var r,
x = this,
Ctor = x.constructor,
pr = Ctor.precision,
wpr = pr + 5;
// Default base is 10.
if (base === void 0) {
base = new Ctor(10);
} else {
base = new Ctor(base);
// log[-b](x) = NaN
// log[0](x) = NaN
// log[1](x) = NaN
if (base.s < 1 || base.eq(ONE)) throw Error(decimalError + 'NaN');
}
// log[b](-x) = NaN
// log[b](0) = -Infinity
if (x.s < 1) throw Error(decimalError + (x.s ? 'NaN' : '-Infinity'));
// log[b](1) = 0
if (x.eq(ONE)) return new Ctor(0);
external = false;
r = divide(ln(x, wpr), ln(base, wpr), wpr);
external = true;
return round(r, pr);
};
/*
* Return a new Decimal whose value is the value of this Decimal minus `y`, truncated to
* `precision` significant digits.
*
*/
P.minus = P.sub = function (y) {
var x = this;
y = new x.constructor(y);
return x.s == y.s ? subtract(x, y) : add(x, (y.s = -y.s, y));
};
/*
* Return a new Decimal whose value is the value of this Decimal modulo `y`, truncated to
* `precision` significant digits.
*
*/
P.modulo = P.mod = function (y) {
var q,
x = this,
Ctor = x.constructor,
pr = Ctor.precision;
y = new Ctor(y);
// x % 0 = NaN
if (!y.s) throw Error(decimalError + 'NaN');
// Return x if x is 0.
if (!x.s) return round(new Ctor(x), pr);
// Prevent rounding of intermediate calculations.
external = false;
q = divide(x, y, 0, 1).times(y);
external = true;
return x.minus(q);
};
/*
* Return a new Decimal whose value is the natural exponential of the value of this Decimal,
* i.e. the base e raised to the power the value of this Decimal, truncated to `precision`
* significant digits.
*
*/
P.naturalExponential = P.exp = function () {
return exp(this);
};
/*
* Return a new Decimal whose value is the natural logarithm of the value of this Decimal,
* truncated to `precision` significant digits.
*
*/
P.naturalLogarithm = P.ln = function () {
return ln(this);
};
/*
* Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by
* -1.
*
*/
P.negated = P.neg = function () {
var x = new this.constructor(this);
x.s = -x.s || 0;
return x;
};
/*
* Return a new Decimal whose value is the value of this Decimal plus `y`, truncated to
* `precision` significant digits.
*
*/
P.plus = P.add = function (y) {
var x = this;
y = new x.constructor(y);
return x.s == y.s ? add(x, y) : subtract(x, (y.s = -y.s, y));
};
/*
* Return the number of significant digits of the value of this Decimal.
*
* [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
*
*/
P.precision = P.sd = function (z) {
var e, sd, w,
x = this;
if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z);
e = getBase10Exponent(x) + 1;
w = x.d.length - 1;
sd = w * LOG_BASE + 1;
w = x.d[w];
// If non-zero...
if (w) {
// Subtract the number of trailing zeros of the last word.
for (; w % 10 == 0; w /= 10) sd--;
// Add the number of digits of the first word.
for (w = x.d[0]; w >= 10; w /= 10) sd++;
}
return z && e > sd ? e : sd;
};
/*
* Return a new Decimal whose value is the square root of this Decimal, truncated to `precision`
* significant digits.
*
*/
P.squareRoot = P.sqrt = function () {
var e, n, pr, r, s, t, wpr,
x = this,
Ctor = x.constructor;
// Negative or zero?
if (x.s < 1) {
if (!x.s) return new Ctor(0);
// sqrt(-x) = NaN
throw Error(decimalError + 'NaN');
}
e = getBase10Exponent(x);
external = false;
// Initial estimate.
s = Math.sqrt(+x);
// Math.sqrt underflow/overflow?
// Pass x to Math.sqrt as integer, then adjust the exponent of the result.
if (s == 0 || s == 1 / 0) {
n = digitsToString(x.d);
if ((n.length + e) % 2 == 0) n += '0';
s = Math.sqrt(n);
e = mathfloor((e + 1) / 2) - (e < 0 || e % 2);
if (s == 1 / 0) {
n = '5e' + e;
} else {
n = s.toExponential();
n = n.slice(0, n.indexOf('e') + 1) + e;
}
r = new Ctor(n);
} else {
r = new Ctor(s.toString());
}
pr = Ctor.precision;
s = wpr = pr + 3;
// Newton-Raphson iteration.
for (;;) {
t = r;
r = t.plus(divide(x, t, wpr + 2)).times(0.5);
if (digitsToString(t.d).slice(0, wpr) === (n = digitsToString(r.d)).slice(0, wpr)) {
n = n.slice(wpr - 3, wpr + 1);
// The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or
// 4999, i.e. approaching a rounding boundary, continue the iteration.
if (s == wpr && n == '4999') {
// On the first iteration only, check to see if rounding up gives the exact result as the
// nines may infinitely repeat.
round(t, pr + 1, 0);
if (t.times(t).eq(x)) {
r = t;
break;
}
} else if (n != '9999') {
break;
}
wpr += 4;
}
}
external = true;
return round(r, pr);
};
/*
* Return a new Decimal whose value is the value of this Decimal times `y`, truncated to
* `precision` significant digits.
*
*/
P.times = P.mul = function (y) {
var carry, e, i, k, r, rL, t, xdL, ydL,
x = this,
Ctor = x.constructor,
xd = x.d,
yd = (y = new Ctor(y)).d;
// Return 0 if either is 0.
if (!x.s || !y.s) return new Ctor(0);
y.s *= x.s;
e = x.e + y.e;
xdL = xd.length;
ydL = yd.length;
// Ensure xd points to the longer array.
if (xdL < ydL) {
r = xd;
xd = yd;
yd = r;
rL = xdL;
xdL = ydL;
ydL = rL;
}
// Initialise the result array with zeros.
r = [];
rL = xdL + ydL;
for (i = rL; i--;) r.push(0);
// Multiply!
for (i = ydL; --i >= 0;) {
carry = 0;
for (k = xdL + i; k > i;) {
t = r[k] + yd[i] * xd[k - i - 1] + carry;
r[k--] = t % BASE | 0;
carry = t / BASE | 0;
}
r[k] = (r[k] + carry) % BASE | 0;
}
// Remove trailing zeros.
for (; !r[--rL];) r.pop();
if (carry) ++e;
else r.shift();
y.d = r;
y.e = e;
return external ? round(y, Ctor.precision) : y;
};
/*
* Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp`
* decimal places using rounding mode `rm` or `rounding` if `rm` is omitted.
*
* If `dp` is omitted, return a new Decimal whose value is the value of this Decimal.
*
* [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
*/
P.toDecimalPlaces = P.todp = function (dp, rm) {
var x = this,
Ctor = x.constructor;
x = new Ctor(x);
if (dp === void 0) return x;
checkInt32(dp, 0, MAX_DIGITS);
if (rm === void 0) rm = Ctor.rounding;
else checkInt32(rm, 0, 8);
return round(x, dp + getBase10Exponent(x) + 1, rm);
};
/*
* Return a string representing the value of this Decimal in exponential notation rounded to
* `dp` fixed decimal places using rounding mode `rounding`.
*
* [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
*/
P.toExponential = function (dp, rm) {
var str,
x = this,
Ctor = x.constructor;
if (dp === void 0) {
str = toString(x, true);
} else {
checkInt32(dp, 0, MAX_DIGITS);
if (rm === void 0) rm = Ctor.rounding;
else checkInt32(rm, 0, 8);
x = round(new Ctor(x), dp + 1, rm);
str = toString(x, true, dp + 1);
}
return str;
};
/*
* Return a string representing the value of this Decimal in normal (fixed-point) notation to
* `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is
* omitted.
*
* As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'.
*
* [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'.
* (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'.
* (-0).toFixed(3) is '0.000'.
* (-0.5).toFixed(0) is '-0'.
*
*/
P.toFixed = function (dp, rm) {
var str, y,
x = this,
Ctor = x.constructor;
if (dp === void 0) return toString(x);
checkInt32(dp, 0, MAX_DIGITS);
if (rm === void 0) rm = Ctor.rounding;
else checkInt32(rm, 0, 8);
y = round(new Ctor(x), dp + getBase10Exponent(x) + 1, rm);
str = toString(y.abs(), false, dp + getBase10Exponent(y) + 1);
// To determine whether to add the minus sign look at the value before it was rounded,
// i.e. look at `x` rather than `y`.
return x.isneg() && !x.isZero() ? '-' + str : str;
};
/*
* Return a new Decimal whose value is the value of this Decimal rounded to a whole number using
* rounding mode `rounding`.
*
*/
P.toInteger = P.toint = function () {
var x = this,
Ctor = x.constructor;
return round(new Ctor(x), getBase10Exponent(x) + 1, Ctor.rounding);
};
/*
* Return the value of this Decimal converted to a number primitive.
*
*/
P.toNumber = function () {
return +this;
};
/*
* Return a new Decimal whose value is the value of this Decimal raised to the power `y`,
* truncated to `precision` significant digits.
*
* For non-integer or very large exponents pow(x, y) is calculated using
*
* x^y = exp(y*ln(x))
*
* The maximum error is 1 ulp (unit in last place).
*
* y {number|string|Decimal} The power to which to raise this Decimal.
*
*/
P.toPower = P.pow = function (y) {
var e, k, pr, r, sign, yIsInt,
x = this,
Ctor = x.constructor,
guard = 12,
yn = +(y = new Ctor(y));
// pow(x, 0) = 1
if (!y.s) return new Ctor(ONE);
x = new Ctor(x);
// pow(0, y > 0) = 0
// pow(0, y < 0) = Infinity
if (!x.s) {
if (y.s < 1) throw Error(decimalError + 'Infinity');
return x;
}
// pow(1, y) = 1
if (x.eq(ONE)) return x;
pr = Ctor.precision;
// pow(x, 1) = x
if (y.eq(ONE)) return round(x, pr);
e = y.e;
k = y.d.length - 1;
yIsInt = e >= k;
sign = x.s;
if (!yIsInt) {
// pow(x < 0, y non-integer) = NaN
if (sign < 0) throw Error(decimalError + 'NaN');
// If y is a small integer use the 'exponentiation by squaring' algorithm.
} else if ((k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) {
r = new Ctor(ONE);
// Max k of 9007199254740991 takes 53 loop iterations.
// Maximum digits array length; leaves [28, 34] guard digits.
e = Math.ceil(pr / LOG_BASE + 4);
external = false;
for (;;) {
if (k % 2) {
r = r.times(x);
truncate(r.d, e);
}
k = mathfloor(k / 2);
if (k === 0) break;
x = x.times(x);
truncate(x.d, e);
}
external = true;
return y.s < 0 ? new Ctor(ONE).div(r) : round(r, pr);
}
// Result is negative if x is negative and the last digit of integer y is odd.
sign = sign < 0 && y.d[Math.max(e, k)] & 1 ? -1 : 1;
x.s = 1;
external = false;
r = y.times(ln(x, pr + guard));
external = true;
r = exp(r);
r.s = sign;
return r;
};
/*
* Return a string representing the value of this Decimal rounded to `sd` significant digits
* using rounding mode `rounding`.
*
* Return exponential notation if `sd` is less than the number of digits necessary to represent
* the integer part of the value in normal notation.
*
* [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
*/
P.toPrecision = function (sd, rm) {
var e, str,
x = this,
Ctor = x.constructor;
if (sd === void 0) {
e = getBase10Exponent(x);
str = toString(x, e <= Ctor.toExpNeg || e >= Ctor.toExpPos);
} else {
checkInt32(sd, 1, MAX_DIGITS);
if (rm === void 0) rm = Ctor.rounding;
else checkInt32(rm, 0, 8);
x = round(new Ctor(x), sd, rm);
e = getBase10Exponent(x);
str = toString(x, sd <= e || e <= Ctor.toExpNeg, sd);
}
return str;
};
/*
* Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd`
* significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if
* omitted.
*
* [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
*/
P.toSignificantDigits = P.tosd = function (sd, rm) {
var x = this,
Ctor = x.constructor;
if (sd === void 0) {
sd = Ctor.precision;
rm = Ctor.rounding;
} else {
checkInt32(sd, 1, MAX_DIGITS);
if (rm === void 0) rm = Ctor.rounding;
else checkInt32(rm, 0, 8);
}
return round(new Ctor(x), sd, rm);
};
/*
* Return a string representing the value of this Decimal.
*
* Return exponential notation if this Decimal has a positive exponent equal to or greater than
* `toExpPos`, or a negative exponent equal to or less than `toExpNeg`.
*
*/
P.toString = P.valueOf = P.val = P.toJSON = function () {
var x = this,
e = getBase10Exponent(x),
Ctor = x.constructor;
return toString(x, e <= Ctor.toExpNeg || e >= Ctor.toExpPos);
};
// Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers.
/*
* add P.minus, P.plus
* checkInt32 P.todp, P.toExponential, P.toFixed, P.toPrecision, P.tosd
* digitsToString P.log, P.sqrt, P.pow, toString, exp, ln
* divide P.div, P.idiv, P.log, P.mod, P.sqrt, exp, ln
* exp P.exp, P.pow
* getBase10Exponent P.exponent, P.sd, P.toint, P.sqrt, P.todp, P.toFixed, P.toPrecision,
* P.toString, divide, round, toString, exp, ln
* getLn10 P.log, ln
* getZeroString digitsToString, toString
* ln P.log, P.ln, P.pow, exp
* parseDecimal Decimal
* round P.abs, P.idiv, P.log, P.minus, P.mod, P.neg, P.plus, P.toint, P.sqrt,
* P.times, P.todp, P.toExponential, P.toFixed, P.pow, P.toPrecision, P.tosd,
* divide, getLn10, exp, ln
* subtract P.minus, P.plus
* toString P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf
* truncate P.pow
*
* Throws: P.log, P.mod, P.sd, P.sqrt, P.pow, checkInt32, divide, round,
* getLn10, exp, ln, parseDecimal, Decimal, config
*/
function add(x, y) {
var carry, d, e, i, k, len, xd, yd,
Ctor = x.constructor,
pr = Ctor.precision;
// If either is zero...
if (!x.s || !y.s) {
// Return x if y is zero.
// Return y if y is non-zero.
if (!y.s) y = new Ctor(x);
return external ? round(y, pr) : y;
}
xd = x.d;
yd = y.d;
// x and y are finite, non-zero numbers with the same sign.
k = x.e;
e = y.e;
xd = xd.slice();
i = k - e;
// If base 1e7 exponents differ...
if (i) {
if (i < 0) {
d = xd;
i = -i;
len = yd.length;
} else {
d = yd;
e = k;
len = xd.length;
}
// Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1.
k = Math.ceil(pr / LOG_BASE);
len = k > len ? k + 1 : len + 1;
if (i > len) {
i = len;
d.length = 1;
}
// Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts.
d.reverse();
for (; i--;) d.push(0);
d.reverse();
}
len = xd.length;
i = yd.length;
// If yd is longer than xd, swap xd and yd so xd points to the longer array.
if (len - i < 0) {
i = len;
d = yd;
yd = xd;
xd = d;
}
// Only start adding at yd.length - 1 as the further digits of xd can be left as they are.
for (carry = 0; i;) {
carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0;
xd[i] %= BASE;
}
if (carry) {
xd.unshift(carry);
++e;
}
// Remove trailing zeros.
// No need to check for zero, as +x + +y != 0 && -x + -y != 0
for (len = xd.length; xd[--len] == 0;) xd.pop();
y.d = xd;
y.e = e;
return external ? round(y, pr) : y;
}