forked from MikeMcl/bignumber.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bignumber.mjs
2888 lines (2303 loc) · 82.3 KB
/
bignumber.mjs
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
/*
* bignumber.js v9.0.1
* A JavaScript library for arbitrary-precision arithmetic.
* https://github.com/MikeMcl/bignumber.js
* Copyright (c) 2020 Michael Mclaughlin <M8ch88l@gmail.com>
* MIT Licensed.
*
* BigNumber.prototype methods | BigNumber methods
* |
* absoluteValue abs | clone
* comparedTo | config set
* decimalPlaces dp | DECIMAL_PLACES
* dividedBy div | ROUNDING_MODE
* dividedToIntegerBy idiv | EXPONENTIAL_AT
* exponentiatedBy pow | RANGE
* integerValue | CRYPTO
* isEqualTo eq | MODULO_MODE
* isFinite | POW_PRECISION
* isGreaterThan gt | FORMAT
* isGreaterThanOrEqualTo gte | ALPHABET
* isInteger | isBigNumber
* isLessThan lt | maximum max
* isLessThanOrEqualTo lte | minimum min
* isNaN | random
* isNegative | sum
* isPositive |
* isZero |
* minus |
* modulo mod |
* multipliedBy times |
* negated |
* plus |
* precision sd |
* shiftedBy |
* squareRoot sqrt |
* toExponential |
* toFixed |
* toFormat |
* toFraction |
* toJSON |
* toNumber |
* toPrecision |
* toString |
* valueOf |
*
*/
var
isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,
mathceil = Math.ceil,
mathfloor = Math.floor,
bignumberError = '[BigNumber Error] ',
tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ',
BASE = 1e14,
LOG_BASE = 14,
MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1
// MAX_INT32 = 0x7fffffff, // 2^31 - 1
POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],
SQRT_BASE = 1e7,
// EDITABLE
// The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and
// the arguments to toExponential, toFixed, toFormat, and toPrecision.
MAX = 1E9; // 0 to MAX_INT32
/*
* Create and return a BigNumber constructor.
*/
function clone(configObject) {
var div, convertBase, parseNumeric,
P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null },
ONE = new BigNumber(1),
//----------------------------- EDITABLE CONFIG DEFAULTS -------------------------------
// The default values below must be integers within the inclusive ranges stated.
// The values can also be changed at run-time using BigNumber.set.
// The maximum number of decimal places for operations involving division.
DECIMAL_PLACES = 20, // 0 to MAX
// The rounding mode used when rounding to the above decimal places, and when using
// toExponential, toFixed, toFormat and toPrecision, and round (default value).
// UP 0 Away from zero.
// DOWN 1 Towards zero.
// CEIL 2 Towards +Infinity.
// FLOOR 3 Towards -Infinity.
// HALF_UP 4 Towards nearest neighbour. If equidistant, up.
// HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
// HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
// HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
// HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
ROUNDING_MODE = 4, // 0 to 8
// EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]
// The exponent value at and beneath which toString returns exponential notation.
// Number type: -7
TO_EXP_NEG = -7, // 0 to -MAX
// The exponent value at and above which toString returns exponential notation.
// Number type: 21
TO_EXP_POS = 21, // 0 to MAX
// RANGE : [MIN_EXP, MAX_EXP]
// The minimum exponent value, beneath which underflow to zero occurs.
// Number type: -324 (5e-324)
MIN_EXP = -1e7, // -1 to -MAX
// The maximum exponent value, above which overflow to Infinity occurs.
// Number type: 308 (1.7976931348623157e+308)
// For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.
MAX_EXP = 1e7, // 1 to MAX
// Whether to use cryptographically-secure random number generation, if available.
CRYPTO = false, // true or false
// The modulo mode used when calculating the modulus: a mod n.
// The quotient (q = a / n) is calculated according to the corresponding rounding mode.
// The remainder (r) is calculated as: r = a - n * q.
//
// UP 0 The remainder is positive if the dividend is negative, else is negative.
// DOWN 1 The remainder has the same sign as the dividend.
// This modulo mode is commonly known as 'truncated division' and is
// equivalent to (a % n) in JavaScript.
// FLOOR 3 The remainder has the same sign as the divisor (Python %).
// HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.
// EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).
// The remainder is always positive.
//
// The truncated division, floored division, Euclidian division and IEEE 754 remainder
// modes are commonly used for the modulus operation.
// Although the other rounding modes can also be used, they may not give useful results.
MODULO_MODE = 1, // 0 to 9
// The maximum number of significant digits of the result of the exponentiatedBy operation.
// If POW_PRECISION is 0, there will be unlimited significant digits.
POW_PRECISION = 0, // 0 to MAX
// The format specification used by the BigNumber.prototype.toFormat method.
FORMAT = {
prefix: '',
groupSize: 3,
secondaryGroupSize: 0,
groupSeparator: ',',
decimalSeparator: '.',
fractionGroupSize: 0,
fractionGroupSeparator: '\xA0', // non-breaking space
suffix: ''
},
// The alphabet used for base conversion. It must be at least 2 characters long, with no '+',
// '-', '.', whitespace, or repeated character.
// '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'
ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';
//------------------------------------------------------------------------------------------
// CONSTRUCTOR
/*
* The BigNumber constructor and exported function.
* Create and return a new instance of a BigNumber object.
*
* v {number|string|BigNumber} A numeric value.
* [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive.
*/
function BigNumber(v, b) {
var alphabet, c, caseChanged, e, i, isNum, len, str,
x = this;
// Enable constructor call without `new`.
if (!(x instanceof BigNumber)) return new BigNumber(v, b);
if (b == null) {
if (v && v._isBigNumber === true) {
x.s = v.s;
if (!v.c || v.e > MAX_EXP) {
x.c = x.e = null;
} else if (v.e < MIN_EXP) {
x.c = [x.e = 0];
} else {
x.e = v.e;
x.c = v.c.slice();
}
return;
}
if ((isNum = typeof v == 'number') && v * 0 == 0) {
// Use `1 / n` to handle minus zero also.
x.s = 1 / v < 0 ? (v = -v, -1) : 1;
// Fast path for integers, where n < 2147483648 (2**31).
if (v === ~~v) {
for (e = 0, i = v; i >= 10; i /= 10, e++);
if (e > MAX_EXP) {
x.c = x.e = null;
} else {
x.e = e;
x.c = [v];
}
return;
}
str = String(v);
} else {
if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum);
x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1;
}
// Decimal point?
if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');
// Exponential form?
if ((i = str.search(/e/i)) > 0) {
// Determine exponent.
if (e < 0) e = i;
e += +str.slice(i + 1);
str = str.substring(0, i);
} else if (e < 0) {
// Integer.
e = str.length;
}
} else {
// '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'
intCheck(b, 2, ALPHABET.length, 'Base');
// Allow exponential notation to be used with base 10 argument, while
// also rounding to DECIMAL_PLACES as with other bases.
if (b == 10) {
x = new BigNumber(v);
return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE);
}
str = String(v);
if (isNum = typeof v == 'number') {
// Avoid potential interpretation of Infinity and NaN as base 44+ values.
if (v * 0 != 0) return parseNumeric(x, str, isNum, b);
x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1;
// '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'
if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) {
throw Error
(tooManyDigits + v);
}
} else {
x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1;
}
alphabet = ALPHABET.slice(0, b);
e = i = 0;
// Check that str is a valid base b number.
// Don't use RegExp, so alphabet can contain special characters.
for (len = str.length; i < len; i++) {
if (alphabet.indexOf(c = str.charAt(i)) < 0) {
if (c == '.') {
// If '.' is not the first character and it has not be found before.
if (i > e) {
e = len;
continue;
}
} else if (!caseChanged) {
// Allow e.g. hexadecimal 'FF' as well as 'ff'.
if (str == str.toUpperCase() && (str = str.toLowerCase()) ||
str == str.toLowerCase() && (str = str.toUpperCase())) {
caseChanged = true;
i = -1;
e = 0;
continue;
}
}
return parseNumeric(x, String(v), isNum, b);
}
}
// Prevent later check for length on converted number.
isNum = false;
str = convertBase(str, b, 10, x.s);
// Decimal point?
if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');
else e = str.length;
}
// Determine leading zeros.
for (i = 0; str.charCodeAt(i) === 48; i++);
// Determine trailing zeros.
for (len = str.length; str.charCodeAt(--len) === 48;);
if (str = str.slice(i, ++len)) {
len -= i;
// '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'
if (isNum && BigNumber.DEBUG &&
len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) {
throw Error
(tooManyDigits + (x.s * v));
}
// Overflow?
if ((e = e - i - 1) > MAX_EXP) {
// Infinity.
x.c = x.e = null;
// Underflow?
} else if (e < MIN_EXP) {
// Zero.
x.c = [x.e = 0];
} else {
x.e = e;
x.c = [];
// Transform base
// e is the base 10 exponent.
// i is where to slice str to get the first element of the coefficient array.
i = (e + 1) % LOG_BASE;
if (e < 0) i += LOG_BASE; // i < 1
if (i < len) {
if (i) x.c.push(+str.slice(0, i));
for (len -= LOG_BASE; i < len;) {
x.c.push(+str.slice(i, i += LOG_BASE));
}
i = LOG_BASE - (str = str.slice(i)).length;
} else {
i -= len;
}
for (; i--; str += '0');
x.c.push(+str);
}
} else {
// Zero.
x.c = [x.e = 0];
}
}
// CONSTRUCTOR PROPERTIES
BigNumber.clone = clone;
BigNumber.ROUND_UP = 0;
BigNumber.ROUND_DOWN = 1;
BigNumber.ROUND_CEIL = 2;
BigNumber.ROUND_FLOOR = 3;
BigNumber.ROUND_HALF_UP = 4;
BigNumber.ROUND_HALF_DOWN = 5;
BigNumber.ROUND_HALF_EVEN = 6;
BigNumber.ROUND_HALF_CEIL = 7;
BigNumber.ROUND_HALF_FLOOR = 8;
BigNumber.EUCLID = 9;
/*
* Configure infrequently-changing library-wide settings.
*
* Accept an object with the following optional properties (if the value of a property is
* a number, it must be an integer within the inclusive range stated):
*
* DECIMAL_PLACES {number} 0 to MAX
* ROUNDING_MODE {number} 0 to 8
* EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX]
* RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX]
* CRYPTO {boolean} true or false
* MODULO_MODE {number} 0 to 9
* POW_PRECISION {number} 0 to MAX
* ALPHABET {string} A string of two or more unique characters which does
* not contain '.'.
* FORMAT {object} An object with some of the following properties:
* prefix {string}
* groupSize {number}
* secondaryGroupSize {number}
* groupSeparator {string}
* decimalSeparator {string}
* fractionGroupSize {number}
* fractionGroupSeparator {string}
* suffix {string}
*
* (The values assigned to the above FORMAT object properties are not checked for validity.)
*
* E.g.
* BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })
*
* Ignore properties/parameters set to null or undefined, except for ALPHABET.
*
* Return an object with the properties current values.
*/
BigNumber.config = BigNumber.set = function (obj) {
var p, v;
if (obj != null) {
if (typeof obj == 'object') {
// DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.
// '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}'
if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) {
v = obj[p];
intCheck(v, 0, MAX, p);
DECIMAL_PLACES = v;
}
// ROUNDING_MODE {number} Integer, 0 to 8 inclusive.
// '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}'
if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) {
v = obj[p];
intCheck(v, 0, 8, p);
ROUNDING_MODE = v;
}
// EXPONENTIAL_AT {number|number[]}
// Integer, -MAX to MAX inclusive or
// [integer -MAX to 0 inclusive, 0 to MAX inclusive].
// '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}'
if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) {
v = obj[p];
if (v && v.pop) {
intCheck(v[0], -MAX, 0, p);
intCheck(v[1], 0, MAX, p);
TO_EXP_NEG = v[0];
TO_EXP_POS = v[1];
} else {
intCheck(v, -MAX, MAX, p);
TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v);
}
}
// RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
// [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].
// '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}'
if (obj.hasOwnProperty(p = 'RANGE')) {
v = obj[p];
if (v && v.pop) {
intCheck(v[0], -MAX, -1, p);
intCheck(v[1], 1, MAX, p);
MIN_EXP = v[0];
MAX_EXP = v[1];
} else {
intCheck(v, -MAX, MAX, p);
if (v) {
MIN_EXP = -(MAX_EXP = v < 0 ? -v : v);
} else {
throw Error
(bignumberError + p + ' cannot be zero: ' + v);
}
}
}
// CRYPTO {boolean} true or false.
// '[BigNumber Error] CRYPTO not true or false: {v}'
// '[BigNumber Error] crypto unavailable'
if (obj.hasOwnProperty(p = 'CRYPTO')) {
v = obj[p];
if (v === !!v) {
if (v) {
if (typeof crypto != 'undefined' && crypto &&
(crypto.getRandomValues || crypto.randomBytes)) {
CRYPTO = v;
} else {
CRYPTO = !v;
throw Error
(bignumberError + 'crypto unavailable');
}
} else {
CRYPTO = v;
}
} else {
throw Error
(bignumberError + p + ' not true or false: ' + v);
}
}
// MODULO_MODE {number} Integer, 0 to 9 inclusive.
// '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}'
if (obj.hasOwnProperty(p = 'MODULO_MODE')) {
v = obj[p];
intCheck(v, 0, 9, p);
MODULO_MODE = v;
}
// POW_PRECISION {number} Integer, 0 to MAX inclusive.
// '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}'
if (obj.hasOwnProperty(p = 'POW_PRECISION')) {
v = obj[p];
intCheck(v, 0, MAX, p);
POW_PRECISION = v;
}
// FORMAT {object}
// '[BigNumber Error] FORMAT not an object: {v}'
if (obj.hasOwnProperty(p = 'FORMAT')) {
v = obj[p];
if (typeof v == 'object') FORMAT = v;
else throw Error
(bignumberError + p + ' not an object: ' + v);
}
// ALPHABET {string}
// '[BigNumber Error] ALPHABET invalid: {v}'
if (obj.hasOwnProperty(p = 'ALPHABET')) {
v = obj[p];
// Disallow if only one character,
// or if it contains '+', '-', '.', whitespace, or a repeated character.
if (typeof v == 'string' && !/^.$|[+-.\s]|(.).*\1/.test(v)) {
ALPHABET = v;
} else {
throw Error
(bignumberError + p + ' invalid: ' + v);
}
}
} else {
// '[BigNumber Error] Object expected: {v}'
throw Error
(bignumberError + 'Object expected: ' + obj);
}
}
return {
DECIMAL_PLACES: DECIMAL_PLACES,
ROUNDING_MODE: ROUNDING_MODE,
EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS],
RANGE: [MIN_EXP, MAX_EXP],
CRYPTO: CRYPTO,
MODULO_MODE: MODULO_MODE,
POW_PRECISION: POW_PRECISION,
FORMAT: FORMAT,
ALPHABET: ALPHABET
};
};
/*
* Return true if v is a BigNumber instance, otherwise return false.
*
* If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed.
*
* v {any}
*
* '[BigNumber Error] Invalid BigNumber: {v}'
*/
BigNumber.isBigNumber = function (v) {
if (!v || v._isBigNumber !== true) return false;
if (!BigNumber.DEBUG) return true;
var i, n,
c = v.c,
e = v.e,
s = v.s;
out: if ({}.toString.call(c) == '[object Array]') {
if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) {
// If the first element is zero, the BigNumber value must be zero.
if (c[0] === 0) {
if (e === 0 && c.length === 1) return true;
break out;
}
// Calculate number of digits that c[0] should have, based on the exponent.
i = (e + 1) % LOG_BASE;
if (i < 1) i += LOG_BASE;
// Calculate number of digits of c[0].
//if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) {
if (String(c[0]).length == i) {
for (i = 0; i < c.length; i++) {
n = c[i];
if (n < 0 || n >= BASE || n !== mathfloor(n)) break out;
}
// Last element cannot be zero, unless it is the only element.
if (n !== 0) return true;
}
}
// Infinity/NaN
} else if (c === null && e === null && (s === null || s === 1 || s === -1)) {
return true;
}
throw Error
(bignumberError + 'Invalid BigNumber: ' + v);
};
/*
* Return a new BigNumber whose value is the maximum of the arguments.
*
* arguments {number|string|BigNumber}
*/
BigNumber.maximum = BigNumber.max = function () {
return maxOrMin(arguments, P.lt);
};
/*
* Return a new BigNumber whose value is the minimum of the arguments.
*
* arguments {number|string|BigNumber}
*/
BigNumber.minimum = BigNumber.min = function () {
return maxOrMin(arguments, P.gt);
};
/*
* Return a new BigNumber with a random value equal to or greater than 0 and less than 1,
* and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing
* zeros are produced).
*
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
*
* '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}'
* '[BigNumber Error] crypto unavailable'
*/
BigNumber.random = (function () {
var pow2_53 = 0x20000000000000;
// Return a 53 bit integer n, where 0 <= n < 9007199254740992.
// Check if Math.random() produces more than 32 bits of randomness.
// If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.
// 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.
var random53bitInt = (Math.random() * pow2_53) & 0x1fffff
? function () { return mathfloor(Math.random() * pow2_53); }
: function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +
(Math.random() * 0x800000 | 0); };
return function (dp) {
var a, b, e, k, v,
i = 0,
c = [],
rand = new BigNumber(ONE);
if (dp == null) dp = DECIMAL_PLACES;
else intCheck(dp, 0, MAX);
k = mathceil(dp / LOG_BASE);
if (CRYPTO) {
// Browsers supporting crypto.getRandomValues.
if (crypto.getRandomValues) {
a = crypto.getRandomValues(new Uint32Array(k *= 2));
for (; i < k;) {
// 53 bits:
// ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)
// 11111 11111111 11111111 11111111 11100000 00000000 00000000
// ((Math.pow(2, 32) - 1) >>> 11).toString(2)
// 11111 11111111 11111111
// 0x20000 is 2^21.
v = a[i] * 0x20000 + (a[i + 1] >>> 11);
// Rejection sampling:
// 0 <= v < 9007199254740992
// Probability that v >= 9e15, is
// 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251
if (v >= 9e15) {
b = crypto.getRandomValues(new Uint32Array(2));
a[i] = b[0];
a[i + 1] = b[1];
} else {
// 0 <= v <= 8999999999999999
// 0 <= (v % 1e14) <= 99999999999999
c.push(v % 1e14);
i += 2;
}
}
i = k / 2;
// Node.js supporting crypto.randomBytes.
} else if (crypto.randomBytes) {
// buffer
a = crypto.randomBytes(k *= 7);
for (; i < k;) {
// 0x1000000000000 is 2^48, 0x10000000000 is 2^40
// 0x100000000 is 2^32, 0x1000000 is 2^24
// 11111 11111111 11111111 11111111 11111111 11111111 11111111
// 0 <= v < 9007199254740992
v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) +
(a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) +
(a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6];
if (v >= 9e15) {
crypto.randomBytes(7).copy(a, i);
} else {
// 0 <= (v % 1e14) <= 99999999999999
c.push(v % 1e14);
i += 7;
}
}
i = k / 7;
} else {
CRYPTO = false;
throw Error
(bignumberError + 'crypto unavailable');
}
}
// Use Math.random.
if (!CRYPTO) {
for (; i < k;) {
v = random53bitInt();
if (v < 9e15) c[i++] = v % 1e14;
}
}
k = c[--i];
dp %= LOG_BASE;
// Convert trailing digits to zeros according to dp.
if (k && dp) {
v = POWS_TEN[LOG_BASE - dp];
c[i] = mathfloor(k / v) * v;
}
// Remove trailing elements which are zero.
for (; c[i] === 0; c.pop(), i--);
// Zero?
if (i < 0) {
c = [e = 0];
} else {
// Remove leading elements which are zero and adjust exponent accordingly.
for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE);
// Count the digits of the first element of c to determine leading zeros, and...
for (i = 1, v = c[0]; v >= 10; v /= 10, i++);
// adjust the exponent accordingly.
if (i < LOG_BASE) e -= LOG_BASE - i;
}
rand.e = e;
rand.c = c;
return rand;
};
})();
/*
* Return a BigNumber whose value is the sum of the arguments.
*
* arguments {number|string|BigNumber}
*/
BigNumber.sum = function () {
var i = 1,
args = arguments,
sum = new BigNumber(args[0]);
for (; i < args.length;) sum = sum.plus(args[i++]);
return sum;
};
// PRIVATE FUNCTIONS
// Called by BigNumber and BigNumber.prototype.toString.
convertBase = (function () {
var decimal = '0123456789';
/*
* Convert string of baseIn to an array of numbers of baseOut.
* Eg. toBaseOut('255', 10, 16) returns [15, 15].
* Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5].
*/
function toBaseOut(str, baseIn, baseOut, alphabet) {
var j,
arr = [0],
arrL,
i = 0,
len = str.length;
for (; i < len;) {
for (arrL = arr.length; arrL--; arr[arrL] *= baseIn);
arr[0] += alphabet.indexOf(str.charAt(i++));
for (j = 0; j < arr.length; j++) {
if (arr[j] > baseOut - 1) {
if (arr[j + 1] == null) arr[j + 1] = 0;
arr[j + 1] += arr[j] / baseOut | 0;
arr[j] %= baseOut;
}
}
}
return arr.reverse();
}
// Convert a numeric string of baseIn to a numeric string of baseOut.
// If the caller is toString, we are converting from base 10 to baseOut.
// If the caller is BigNumber, we are converting from baseIn to base 10.
return function (str, baseIn, baseOut, sign, callerIsToString) {
var alphabet, d, e, k, r, x, xc, y,
i = str.indexOf('.'),
dp = DECIMAL_PLACES,
rm = ROUNDING_MODE;
// Non-integer.
if (i >= 0) {
k = POW_PRECISION;
// Unlimited precision.
POW_PRECISION = 0;
str = str.replace('.', '');
y = new BigNumber(baseIn);
x = y.pow(str.length - i);
POW_PRECISION = k;
// Convert str as if an integer, then restore the fraction part by dividing the
// result by its base raised to a power.
y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'),
10, baseOut, decimal);
y.e = y.c.length;
}
// Convert the number as integer.
xc = toBaseOut(str, baseIn, baseOut, callerIsToString
? (alphabet = ALPHABET, decimal)
: (alphabet = decimal, ALPHABET));
// xc now represents str as an integer and converted to baseOut. e is the exponent.
e = k = xc.length;
// Remove trailing zeros.
for (; xc[--k] == 0; xc.pop());
// Zero?
if (!xc[0]) return alphabet.charAt(0);
// Does str represent an integer? If so, no need for the division.
if (i < 0) {
--e;
} else {
x.c = xc;
x.e = e;
// The sign is needed for correct rounding.
x.s = sign;
x = div(x, y, dp, rm, baseOut);
xc = x.c;
r = x.r;
e = x.e;
}
// xc now represents str converted to baseOut.
// THe index of the rounding digit.
d = e + dp + 1;
// The rounding digit: the digit to the right of the digit that may be rounded up.
i = xc[d];
// Look at the rounding digits and mode to determine whether to round up.
k = baseOut / 2;
r = r || d < 0 || xc[d + 1] != null;
r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))
: i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||
rm == (x.s < 0 ? 8 : 7));
// If the index of the rounding digit is not greater than zero, or xc represents
// zero, then the result of the base conversion is zero or, if rounding up, a value
// such as 0.00001.
if (d < 1 || !xc[0]) {
// 1^-dp or 0
str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0);
} else {
// Truncate xc to the required number of decimal places.
xc.length = d;
// Round up?
if (r) {
// Rounding up may mean the previous digit has to be rounded up and so on.
for (--baseOut; ++xc[--d] > baseOut;) {
xc[d] = 0;
if (!d) {
++e;
xc = [1].concat(xc);
}
}
}
// Determine trailing zeros.
for (k = xc.length; !xc[--k];);
// E.g. [4, 11, 15] becomes 4bf.
for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++]));
// Add leading zeros, decimal point and trailing zeros as required.
str = toFixedPoint(str, e, alphabet.charAt(0));
}
// The caller will add the sign.
return str;
};
})();
// Perform division in the specified base. Called by div and convertBase.
div = (function () {
// Assume non-zero x and k.
function multiply(x, k, base) {
var m, temp, xlo, xhi,
carry = 0,
i = x.length,
klo = k % SQRT_BASE,
khi = k / SQRT_BASE | 0;
for (x = x.slice(); i--;) {
xlo = x[i] % SQRT_BASE;
xhi = x[i] / SQRT_BASE | 0;
m = khi * xlo + xhi * klo;
temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;
carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;
x[i] = temp % base;
}
if (carry) x = [carry].concat(x);
return x;
}
function compare(a, b, aL, bL) {
var i, cmp;
if (aL != bL) {
cmp = aL > bL ? 1 : -1;
} else {
for (i = cmp = 0; i < aL; i++) {
if (a[i] != b[i]) {
cmp = a[i] > b[i] ? 1 : -1;
break;
}
}