/ bignumber.js
bignumber.js
1 /*! bignumber.js v4.0.2 https://github.com/MikeMcl/bignumber.js/LICENCE */ 2 3 ;(function (globalObj) { 4 'use strict'; 5 6 /* 7 bignumber.js v4.0.2 8 A JavaScript library for arbitrary-precision arithmetic. 9 https://github.com/MikeMcl/bignumber.js 10 Copyright (c) 2017 Michael Mclaughlin <M8ch88l@gmail.com> 11 MIT Expat Licence 12 */ 13 14 15 var BigNumber, 16 isNumeric = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i, 17 mathceil = Math.ceil, 18 mathfloor = Math.floor, 19 notBool = ' not a boolean or binary digit', 20 roundingMode = 'rounding mode', 21 tooManyDigits = 'number type has more than 15 significant digits', 22 ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_', 23 BASE = 1e14, 24 LOG_BASE = 14, 25 MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 26 // MAX_INT32 = 0x7fffffff, // 2^31 - 1 27 POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], 28 SQRT_BASE = 1e7, 29 30 /* 31 * The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and 32 * the arguments to toExponential, toFixed, toFormat, and toPrecision, beyond which an 33 * exception is thrown (if ERRORS is true). 34 */ 35 MAX = 1E9; // 0 to MAX_INT32 36 37 38 /* 39 * Create and return a BigNumber constructor. 40 */ 41 function constructorFactory(config) { 42 var div, parseNumeric, 43 44 // id tracks the caller function, so its name can be included in error messages. 45 id = 0, 46 P = BigNumber.prototype, 47 ONE = new BigNumber(1), 48 49 50 /********************************* EDITABLE DEFAULTS **********************************/ 51 52 53 /* 54 * The default values below must be integers within the inclusive ranges stated. 55 * The values can also be changed at run-time using BigNumber.config. 56 */ 57 58 // The maximum number of decimal places for operations involving division. 59 DECIMAL_PLACES = 20, // 0 to MAX 60 61 /* 62 * The rounding mode used when rounding to the above decimal places, and when using 63 * toExponential, toFixed, toFormat and toPrecision, and round (default value). 64 * UP 0 Away from zero. 65 * DOWN 1 Towards zero. 66 * CEIL 2 Towards +Infinity. 67 * FLOOR 3 Towards -Infinity. 68 * HALF_UP 4 Towards nearest neighbour. If equidistant, up. 69 * HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. 70 * HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. 71 * HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. 72 * HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. 73 */ 74 ROUNDING_MODE = 4, // 0 to 8 75 76 // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] 77 78 // The exponent value at and beneath which toString returns exponential notation. 79 // Number type: -7 80 TO_EXP_NEG = -7, // 0 to -MAX 81 82 // The exponent value at and above which toString returns exponential notation. 83 // Number type: 21 84 TO_EXP_POS = 21, // 0 to MAX 85 86 // RANGE : [MIN_EXP, MAX_EXP] 87 88 // The minimum exponent value, beneath which underflow to zero occurs. 89 // Number type: -324 (5e-324) 90 MIN_EXP = -1e7, // -1 to -MAX 91 92 // The maximum exponent value, above which overflow to Infinity occurs. 93 // Number type: 308 (1.7976931348623157e+308) 94 // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. 95 MAX_EXP = 1e7, // 1 to MAX 96 97 // Whether BigNumber Errors are ever thrown. 98 ERRORS = true, // true or false 99 100 // Change to intValidatorNoErrors if ERRORS is false. 101 isValidInt = intValidatorWithErrors, // intValidatorWithErrors/intValidatorNoErrors 102 103 // Whether to use cryptographically-secure random number generation, if available. 104 CRYPTO = false, // true or false 105 106 /* 107 * The modulo mode used when calculating the modulus: a mod n. 108 * The quotient (q = a / n) is calculated according to the corresponding rounding mode. 109 * The remainder (r) is calculated as: r = a - n * q. 110 * 111 * UP 0 The remainder is positive if the dividend is negative, else is negative. 112 * DOWN 1 The remainder has the same sign as the dividend. 113 * This modulo mode is commonly known as 'truncated division' and is 114 * equivalent to (a % n) in JavaScript. 115 * FLOOR 3 The remainder has the same sign as the divisor (Python %). 116 * HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. 117 * EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). 118 * The remainder is always positive. 119 * 120 * The truncated division, floored division, Euclidian division and IEEE 754 remainder 121 * modes are commonly used for the modulus operation. 122 * Although the other rounding modes can also be used, they may not give useful results. 123 */ 124 MODULO_MODE = 1, // 0 to 9 125 126 // The maximum number of significant digits of the result of the toPower operation. 127 // If POW_PRECISION is 0, there will be unlimited significant digits. 128 POW_PRECISION = 0, // 0 to MAX 129 130 // The format specification used by the BigNumber.prototype.toFormat method. 131 FORMAT = { 132 decimalSeparator: '.', 133 groupSeparator: ',', 134 groupSize: 3, 135 secondaryGroupSize: 0, 136 fractionGroupSeparator: '\xA0', // non-breaking space 137 fractionGroupSize: 0 138 }; 139 140 141 /******************************************************************************************/ 142 143 144 // CONSTRUCTOR 145 146 147 /* 148 * The BigNumber constructor and exported function. 149 * Create and return a new instance of a BigNumber object. 150 * 151 * n {number|string|BigNumber} A numeric value. 152 * [b] {number} The base of n. Integer, 2 to 64 inclusive. 153 */ 154 function BigNumber( n, b ) { 155 var c, e, i, num, len, str, 156 x = this; 157 158 // Enable constructor usage without new. 159 if ( !( x instanceof BigNumber ) ) { 160 161 // 'BigNumber() constructor call without new: {n}' 162 if (ERRORS) raise( 26, 'constructor call without new', n ); 163 return new BigNumber( n, b ); 164 } 165 166 // 'new BigNumber() base not an integer: {b}' 167 // 'new BigNumber() base out of range: {b}' 168 if ( b == null || !isValidInt( b, 2, 64, id, 'base' ) ) { 169 170 // Duplicate. 171 if ( n instanceof BigNumber ) { 172 x.s = n.s; 173 x.e = n.e; 174 x.c = ( n = n.c ) ? n.slice() : n; 175 id = 0; 176 return; 177 } 178 179 if ( ( num = typeof n == 'number' ) && n * 0 == 0 ) { 180 x.s = 1 / n < 0 ? ( n = -n, -1 ) : 1; 181 182 // Fast path for integers. 183 if ( n === ~~n ) { 184 for ( e = 0, i = n; i >= 10; i /= 10, e++ ); 185 x.e = e; 186 x.c = [n]; 187 id = 0; 188 return; 189 } 190 191 str = n + ''; 192 } else { 193 if ( !isNumeric.test( str = n + '' ) ) return parseNumeric( x, str, num ); 194 x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1; 195 } 196 } else { 197 b = b | 0; 198 str = n + ''; 199 200 // Ensure return value is rounded to DECIMAL_PLACES as with other bases. 201 // Allow exponential notation to be used with base 10 argument. 202 if ( b == 10 ) { 203 x = new BigNumber( n instanceof BigNumber ? n : str ); 204 return round( x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE ); 205 } 206 207 // Avoid potential interpretation of Infinity and NaN as base 44+ values. 208 // Any number in exponential form will fail due to the [Ee][+-]. 209 if ( ( num = typeof n == 'number' ) && n * 0 != 0 || 210 !( new RegExp( '^-?' + ( c = '[' + ALPHABET.slice( 0, b ) + ']+' ) + 211 '(?:\\.' + c + ')?$',b < 37 ? 'i' : '' ) ).test(str) ) { 212 return parseNumeric( x, str, num, b ); 213 } 214 215 if (num) { 216 x.s = 1 / n < 0 ? ( str = str.slice(1), -1 ) : 1; 217 218 if ( ERRORS && str.replace( /^0\.0*|\./, '' ).length > 15 ) { 219 220 // 'new BigNumber() number type has more than 15 significant digits: {n}' 221 raise( id, tooManyDigits, n ); 222 } 223 224 // Prevent later check for length on converted number. 225 num = false; 226 } else { 227 x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1; 228 } 229 230 str = convertBase( str, 10, b, x.s ); 231 } 232 233 // Decimal point? 234 if ( ( e = str.indexOf('.') ) > -1 ) str = str.replace( '.', '' ); 235 236 // Exponential form? 237 if ( ( i = str.search( /e/i ) ) > 0 ) { 238 239 // Determine exponent. 240 if ( e < 0 ) e = i; 241 e += +str.slice( i + 1 ); 242 str = str.substring( 0, i ); 243 } else if ( e < 0 ) { 244 245 // Integer. 246 e = str.length; 247 } 248 249 // Determine leading zeros. 250 for ( i = 0; str.charCodeAt(i) === 48; i++ ); 251 252 // Determine trailing zeros. 253 for ( len = str.length; str.charCodeAt(--len) === 48; ); 254 str = str.slice( i, len + 1 ); 255 256 if (str) { 257 len = str.length; 258 259 // Disallow numbers with over 15 significant digits if number type. 260 // 'new BigNumber() number type has more than 15 significant digits: {n}' 261 if ( num && ERRORS && len > 15 && ( n > MAX_SAFE_INTEGER || n !== mathfloor(n) ) ) { 262 raise( id, tooManyDigits, x.s * n ); 263 } 264 265 e = e - i - 1; 266 267 // Overflow? 268 if ( e > MAX_EXP ) { 269 270 // Infinity. 271 x.c = x.e = null; 272 273 // Underflow? 274 } else if ( e < MIN_EXP ) { 275 276 // Zero. 277 x.c = [ x.e = 0 ]; 278 } else { 279 x.e = e; 280 x.c = []; 281 282 // Transform base 283 284 // e is the base 10 exponent. 285 // i is where to slice str to get the first element of the coefficient array. 286 i = ( e + 1 ) % LOG_BASE; 287 if ( e < 0 ) i += LOG_BASE; 288 289 if ( i < len ) { 290 if (i) x.c.push( +str.slice( 0, i ) ); 291 292 for ( len -= LOG_BASE; i < len; ) { 293 x.c.push( +str.slice( i, i += LOG_BASE ) ); 294 } 295 296 str = str.slice(i); 297 i = LOG_BASE - str.length; 298 } else { 299 i -= len; 300 } 301 302 for ( ; i--; str += '0' ); 303 x.c.push( +str ); 304 } 305 } else { 306 307 // Zero. 308 x.c = [ x.e = 0 ]; 309 } 310 311 id = 0; 312 } 313 314 315 // CONSTRUCTOR PROPERTIES 316 317 318 BigNumber.another = constructorFactory; 319 320 BigNumber.ROUND_UP = 0; 321 BigNumber.ROUND_DOWN = 1; 322 BigNumber.ROUND_CEIL = 2; 323 BigNumber.ROUND_FLOOR = 3; 324 BigNumber.ROUND_HALF_UP = 4; 325 BigNumber.ROUND_HALF_DOWN = 5; 326 BigNumber.ROUND_HALF_EVEN = 6; 327 BigNumber.ROUND_HALF_CEIL = 7; 328 BigNumber.ROUND_HALF_FLOOR = 8; 329 BigNumber.EUCLID = 9; 330 331 332 /* 333 * Configure infrequently-changing library-wide settings. 334 * 335 * Accept an object or an argument list, with one or many of the following properties or 336 * parameters respectively: 337 * 338 * DECIMAL_PLACES {number} Integer, 0 to MAX inclusive 339 * ROUNDING_MODE {number} Integer, 0 to 8 inclusive 340 * EXPONENTIAL_AT {number|number[]} Integer, -MAX to MAX inclusive or 341 * [integer -MAX to 0 incl., 0 to MAX incl.] 342 * RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or 343 * [integer -MAX to -1 incl., integer 1 to MAX incl.] 344 * ERRORS {boolean|number} true, false, 1 or 0 345 * CRYPTO {boolean|number} true, false, 1 or 0 346 * MODULO_MODE {number} 0 to 9 inclusive 347 * POW_PRECISION {number} 0 to MAX inclusive 348 * FORMAT {object} See BigNumber.prototype.toFormat 349 * decimalSeparator {string} 350 * groupSeparator {string} 351 * groupSize {number} 352 * secondaryGroupSize {number} 353 * fractionGroupSeparator {string} 354 * fractionGroupSize {number} 355 * 356 * (The values assigned to the above FORMAT object properties are not checked for validity.) 357 * 358 * E.g. 359 * BigNumber.config(20, 4) is equivalent to 360 * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) 361 * 362 * Ignore properties/parameters set to null or undefined. 363 * Return an object with the properties current values. 364 */ 365 BigNumber.config = BigNumber.set = function () { 366 var v, p, 367 i = 0, 368 r = {}, 369 a = arguments, 370 o = a[0], 371 has = o && typeof o == 'object' 372 ? function () { if ( o.hasOwnProperty(p) ) return ( v = o[p] ) != null; } 373 : function () { if ( a.length > i ) return ( v = a[i++] ) != null; }; 374 375 // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. 376 // 'config() DECIMAL_PLACES not an integer: {v}' 377 // 'config() DECIMAL_PLACES out of range: {v}' 378 if ( has( p = 'DECIMAL_PLACES' ) && isValidInt( v, 0, MAX, 2, p ) ) { 379 DECIMAL_PLACES = v | 0; 380 } 381 r[p] = DECIMAL_PLACES; 382 383 // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. 384 // 'config() ROUNDING_MODE not an integer: {v}' 385 // 'config() ROUNDING_MODE out of range: {v}' 386 if ( has( p = 'ROUNDING_MODE' ) && isValidInt( v, 0, 8, 2, p ) ) { 387 ROUNDING_MODE = v | 0; 388 } 389 r[p] = ROUNDING_MODE; 390 391 // EXPONENTIAL_AT {number|number[]} 392 // Integer, -MAX to MAX inclusive or [integer -MAX to 0 inclusive, 0 to MAX inclusive]. 393 // 'config() EXPONENTIAL_AT not an integer: {v}' 394 // 'config() EXPONENTIAL_AT out of range: {v}' 395 if ( has( p = 'EXPONENTIAL_AT' ) ) { 396 397 if ( isArray(v) ) { 398 if ( isValidInt( v[0], -MAX, 0, 2, p ) && isValidInt( v[1], 0, MAX, 2, p ) ) { 399 TO_EXP_NEG = v[0] | 0; 400 TO_EXP_POS = v[1] | 0; 401 } 402 } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) { 403 TO_EXP_NEG = -( TO_EXP_POS = ( v < 0 ? -v : v ) | 0 ); 404 } 405 } 406 r[p] = [ TO_EXP_NEG, TO_EXP_POS ]; 407 408 // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or 409 // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. 410 // 'config() RANGE not an integer: {v}' 411 // 'config() RANGE cannot be zero: {v}' 412 // 'config() RANGE out of range: {v}' 413 if ( has( p = 'RANGE' ) ) { 414 415 if ( isArray(v) ) { 416 if ( isValidInt( v[0], -MAX, -1, 2, p ) && isValidInt( v[1], 1, MAX, 2, p ) ) { 417 MIN_EXP = v[0] | 0; 418 MAX_EXP = v[1] | 0; 419 } 420 } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) { 421 if ( v | 0 ) MIN_EXP = -( MAX_EXP = ( v < 0 ? -v : v ) | 0 ); 422 else if (ERRORS) raise( 2, p + ' cannot be zero', v ); 423 } 424 } 425 r[p] = [ MIN_EXP, MAX_EXP ]; 426 427 // ERRORS {boolean|number} true, false, 1 or 0. 428 // 'config() ERRORS not a boolean or binary digit: {v}' 429 if ( has( p = 'ERRORS' ) ) { 430 431 if ( v === !!v || v === 1 || v === 0 ) { 432 id = 0; 433 isValidInt = ( ERRORS = !!v ) ? intValidatorWithErrors : intValidatorNoErrors; 434 } else if (ERRORS) { 435 raise( 2, p + notBool, v ); 436 } 437 } 438 r[p] = ERRORS; 439 440 // CRYPTO {boolean|number} true, false, 1 or 0. 441 // 'config() CRYPTO not a boolean or binary digit: {v}' 442 // 'config() crypto unavailable: {crypto}' 443 if ( has( p = 'CRYPTO' ) ) { 444 445 if ( v === true || v === false || v === 1 || v === 0 ) { 446 if (v) { 447 v = typeof crypto == 'undefined'; 448 if ( !v && crypto && (crypto.getRandomValues || crypto.randomBytes)) { 449 CRYPTO = true; 450 } else if (ERRORS) { 451 raise( 2, 'crypto unavailable', v ? void 0 : crypto ); 452 } else { 453 CRYPTO = false; 454 } 455 } else { 456 CRYPTO = false; 457 } 458 } else if (ERRORS) { 459 raise( 2, p + notBool, v ); 460 } 461 } 462 r[p] = CRYPTO; 463 464 // MODULO_MODE {number} Integer, 0 to 9 inclusive. 465 // 'config() MODULO_MODE not an integer: {v}' 466 // 'config() MODULO_MODE out of range: {v}' 467 if ( has( p = 'MODULO_MODE' ) && isValidInt( v, 0, 9, 2, p ) ) { 468 MODULO_MODE = v | 0; 469 } 470 r[p] = MODULO_MODE; 471 472 // POW_PRECISION {number} Integer, 0 to MAX inclusive. 473 // 'config() POW_PRECISION not an integer: {v}' 474 // 'config() POW_PRECISION out of range: {v}' 475 if ( has( p = 'POW_PRECISION' ) && isValidInt( v, 0, MAX, 2, p ) ) { 476 POW_PRECISION = v | 0; 477 } 478 r[p] = POW_PRECISION; 479 480 // FORMAT {object} 481 // 'config() FORMAT not an object: {v}' 482 if ( has( p = 'FORMAT' ) ) { 483 484 if ( typeof v == 'object' ) { 485 FORMAT = v; 486 } else if (ERRORS) { 487 raise( 2, p + ' not an object', v ); 488 } 489 } 490 r[p] = FORMAT; 491 492 return r; 493 }; 494 495 496 /* 497 * Return a new BigNumber whose value is the maximum of the arguments. 498 * 499 * arguments {number|string|BigNumber} 500 */ 501 BigNumber.max = function () { return maxOrMin( arguments, P.lt ); }; 502 503 504 /* 505 * Return a new BigNumber whose value is the minimum of the arguments. 506 * 507 * arguments {number|string|BigNumber} 508 */ 509 BigNumber.min = function () { return maxOrMin( arguments, P.gt ); }; 510 511 512 /* 513 * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, 514 * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing 515 * zeros are produced). 516 * 517 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. 518 * 519 * 'random() decimal places not an integer: {dp}' 520 * 'random() decimal places out of range: {dp}' 521 * 'random() crypto unavailable: {crypto}' 522 */ 523 BigNumber.random = (function () { 524 var pow2_53 = 0x20000000000000; 525 526 // Return a 53 bit integer n, where 0 <= n < 9007199254740992. 527 // Check if Math.random() produces more than 32 bits of randomness. 528 // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. 529 // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. 530 var random53bitInt = (Math.random() * pow2_53) & 0x1fffff 531 ? function () { return mathfloor( Math.random() * pow2_53 ); } 532 : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + 533 (Math.random() * 0x800000 | 0); }; 534 535 return function (dp) { 536 var a, b, e, k, v, 537 i = 0, 538 c = [], 539 rand = new BigNumber(ONE); 540 541 dp = dp == null || !isValidInt( dp, 0, MAX, 14 ) ? DECIMAL_PLACES : dp | 0; 542 k = mathceil( dp / LOG_BASE ); 543 544 if (CRYPTO) { 545 546 // Browsers supporting crypto.getRandomValues. 547 if (crypto.getRandomValues) { 548 549 a = crypto.getRandomValues( new Uint32Array( k *= 2 ) ); 550 551 for ( ; i < k; ) { 552 553 // 53 bits: 554 // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) 555 // 11111 11111111 11111111 11111111 11100000 00000000 00000000 556 // ((Math.pow(2, 32) - 1) >>> 11).toString(2) 557 // 11111 11111111 11111111 558 // 0x20000 is 2^21. 559 v = a[i] * 0x20000 + (a[i + 1] >>> 11); 560 561 // Rejection sampling: 562 // 0 <= v < 9007199254740992 563 // Probability that v >= 9e15, is 564 // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 565 if ( v >= 9e15 ) { 566 b = crypto.getRandomValues( new Uint32Array(2) ); 567 a[i] = b[0]; 568 a[i + 1] = b[1]; 569 } else { 570 571 // 0 <= v <= 8999999999999999 572 // 0 <= (v % 1e14) <= 99999999999999 573 c.push( v % 1e14 ); 574 i += 2; 575 } 576 } 577 i = k / 2; 578 579 // Node.js supporting crypto.randomBytes. 580 } else if (crypto.randomBytes) { 581 582 // buffer 583 a = crypto.randomBytes( k *= 7 ); 584 585 for ( ; i < k; ) { 586 587 // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 588 // 0x100000000 is 2^32, 0x1000000 is 2^24 589 // 11111 11111111 11111111 11111111 11111111 11111111 11111111 590 // 0 <= v < 9007199254740992 591 v = ( ( a[i] & 31 ) * 0x1000000000000 ) + ( a[i + 1] * 0x10000000000 ) + 592 ( a[i + 2] * 0x100000000 ) + ( a[i + 3] * 0x1000000 ) + 593 ( a[i + 4] << 16 ) + ( a[i + 5] << 8 ) + a[i + 6]; 594 595 if ( v >= 9e15 ) { 596 crypto.randomBytes(7).copy( a, i ); 597 } else { 598 599 // 0 <= (v % 1e14) <= 99999999999999 600 c.push( v % 1e14 ); 601 i += 7; 602 } 603 } 604 i = k / 7; 605 } else { 606 CRYPTO = false; 607 if (ERRORS) raise( 14, 'crypto unavailable', crypto ); 608 } 609 } 610 611 // Use Math.random. 612 if (!CRYPTO) { 613 614 for ( ; i < k; ) { 615 v = random53bitInt(); 616 if ( v < 9e15 ) c[i++] = v % 1e14; 617 } 618 } 619 620 k = c[--i]; 621 dp %= LOG_BASE; 622 623 // Convert trailing digits to zeros according to dp. 624 if ( k && dp ) { 625 v = POWS_TEN[LOG_BASE - dp]; 626 c[i] = mathfloor( k / v ) * v; 627 } 628 629 // Remove trailing elements which are zero. 630 for ( ; c[i] === 0; c.pop(), i-- ); 631 632 // Zero? 633 if ( i < 0 ) { 634 c = [ e = 0 ]; 635 } else { 636 637 // Remove leading elements which are zero and adjust exponent accordingly. 638 for ( e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); 639 640 // Count the digits of the first element of c to determine leading zeros, and... 641 for ( i = 1, v = c[0]; v >= 10; v /= 10, i++); 642 643 // adjust the exponent accordingly. 644 if ( i < LOG_BASE ) e -= LOG_BASE - i; 645 } 646 647 rand.e = e; 648 rand.c = c; 649 return rand; 650 }; 651 })(); 652 653 654 // PRIVATE FUNCTIONS 655 656 657 // Convert a numeric string of baseIn to a numeric string of baseOut. 658 function convertBase( str, baseOut, baseIn, sign ) { 659 var d, e, k, r, x, xc, y, 660 i = str.indexOf( '.' ), 661 dp = DECIMAL_PLACES, 662 rm = ROUNDING_MODE; 663 664 if ( baseIn < 37 ) str = str.toLowerCase(); 665 666 // Non-integer. 667 if ( i >= 0 ) { 668 k = POW_PRECISION; 669 670 // Unlimited precision. 671 POW_PRECISION = 0; 672 str = str.replace( '.', '' ); 673 y = new BigNumber(baseIn); 674 x = y.pow( str.length - i ); 675 POW_PRECISION = k; 676 677 // Convert str as if an integer, then restore the fraction part by dividing the 678 // result by its base raised to a power. 679 y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e ), 10, baseOut ); 680 y.e = y.c.length; 681 } 682 683 // Convert the number as integer. 684 xc = toBaseOut( str, baseIn, baseOut ); 685 e = k = xc.length; 686 687 // Remove trailing zeros. 688 for ( ; xc[--k] == 0; xc.pop() ); 689 if ( !xc[0] ) return '0'; 690 691 if ( i < 0 ) { 692 --e; 693 } else { 694 x.c = xc; 695 x.e = e; 696 697 // sign is needed for correct rounding. 698 x.s = sign; 699 x = div( x, y, dp, rm, baseOut ); 700 xc = x.c; 701 r = x.r; 702 e = x.e; 703 } 704 705 d = e + dp + 1; 706 707 // The rounding digit, i.e. the digit to the right of the digit that may be rounded up. 708 i = xc[d]; 709 k = baseOut / 2; 710 r = r || d < 0 || xc[d + 1] != null; 711 712 r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) ) 713 : i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 || 714 rm == ( x.s < 0 ? 8 : 7 ) ); 715 716 if ( d < 1 || !xc[0] ) { 717 718 // 1^-dp or 0. 719 str = r ? toFixedPoint( '1', -dp ) : '0'; 720 } else { 721 xc.length = d; 722 723 if (r) { 724 725 // Rounding up may mean the previous digit has to be rounded up and so on. 726 for ( --baseOut; ++xc[--d] > baseOut; ) { 727 xc[d] = 0; 728 729 if ( !d ) { 730 ++e; 731 xc = [1].concat(xc); 732 } 733 } 734 } 735 736 // Determine trailing zeros. 737 for ( k = xc.length; !xc[--k]; ); 738 739 // E.g. [4, 11, 15] becomes 4bf. 740 for ( i = 0, str = ''; i <= k; str += ALPHABET.charAt( xc[i++] ) ); 741 str = toFixedPoint( str, e ); 742 } 743 744 // The caller will add the sign. 745 return str; 746 } 747 748 749 // Perform division in the specified base. Called by div and convertBase. 750 div = (function () { 751 752 // Assume non-zero x and k. 753 function multiply( x, k, base ) { 754 var m, temp, xlo, xhi, 755 carry = 0, 756 i = x.length, 757 klo = k % SQRT_BASE, 758 khi = k / SQRT_BASE | 0; 759 760 for ( x = x.slice(); i--; ) { 761 xlo = x[i] % SQRT_BASE; 762 xhi = x[i] / SQRT_BASE | 0; 763 m = khi * xlo + xhi * klo; 764 temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry; 765 carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi; 766 x[i] = temp % base; 767 } 768 769 if (carry) x = [carry].concat(x); 770 771 return x; 772 } 773 774 function compare( a, b, aL, bL ) { 775 var i, cmp; 776 777 if ( aL != bL ) { 778 cmp = aL > bL ? 1 : -1; 779 } else { 780 781 for ( i = cmp = 0; i < aL; i++ ) { 782 783 if ( a[i] != b[i] ) { 784 cmp = a[i] > b[i] ? 1 : -1; 785 break; 786 } 787 } 788 } 789 return cmp; 790 } 791 792 function subtract( a, b, aL, base ) { 793 var i = 0; 794 795 // Subtract b from a. 796 for ( ; aL--; ) { 797 a[aL] -= i; 798 i = a[aL] < b[aL] ? 1 : 0; 799 a[aL] = i * base + a[aL] - b[aL]; 800 } 801 802 // Remove leading zeros. 803 for ( ; !a[0] && a.length > 1; a.splice(0, 1) ); 804 } 805 806 // x: dividend, y: divisor. 807 return function ( x, y, dp, rm, base ) { 808 var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, 809 yL, yz, 810 s = x.s == y.s ? 1 : -1, 811 xc = x.c, 812 yc = y.c; 813 814 // Either NaN, Infinity or 0? 815 if ( !xc || !xc[0] || !yc || !yc[0] ) { 816 817 return new BigNumber( 818 819 // Return NaN if either NaN, or both Infinity or 0. 820 !x.s || !y.s || ( xc ? yc && xc[0] == yc[0] : !yc ) ? NaN : 821 822 // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. 823 xc && xc[0] == 0 || !yc ? s * 0 : s / 0 824 ); 825 } 826 827 q = new BigNumber(s); 828 qc = q.c = []; 829 e = x.e - y.e; 830 s = dp + e + 1; 831 832 if ( !base ) { 833 base = BASE; 834 e = bitFloor( x.e / LOG_BASE ) - bitFloor( y.e / LOG_BASE ); 835 s = s / LOG_BASE | 0; 836 } 837 838 // Result exponent may be one less then the current value of e. 839 // The coefficients of the BigNumbers from convertBase may have trailing zeros. 840 for ( i = 0; yc[i] == ( xc[i] || 0 ); i++ ); 841 if ( yc[i] > ( xc[i] || 0 ) ) e--; 842 843 if ( s < 0 ) { 844 qc.push(1); 845 more = true; 846 } else { 847 xL = xc.length; 848 yL = yc.length; 849 i = 0; 850 s += 2; 851 852 // Normalise xc and yc so highest order digit of yc is >= base / 2. 853 854 n = mathfloor( base / ( yc[0] + 1 ) ); 855 856 // Not necessary, but to handle odd bases where yc[0] == ( base / 2 ) - 1. 857 // if ( n > 1 || n++ == 1 && yc[0] < base / 2 ) { 858 if ( n > 1 ) { 859 yc = multiply( yc, n, base ); 860 xc = multiply( xc, n, base ); 861 yL = yc.length; 862 xL = xc.length; 863 } 864 865 xi = yL; 866 rem = xc.slice( 0, yL ); 867 remL = rem.length; 868 869 // Add zeros to make remainder as long as divisor. 870 for ( ; remL < yL; rem[remL++] = 0 ); 871 yz = yc.slice(); 872 yz = [0].concat(yz); 873 yc0 = yc[0]; 874 if ( yc[1] >= base / 2 ) yc0++; 875 // Not necessary, but to prevent trial digit n > base, when using base 3. 876 // else if ( base == 3 && yc0 == 1 ) yc0 = 1 + 1e-15; 877 878 do { 879 n = 0; 880 881 // Compare divisor and remainder. 882 cmp = compare( yc, rem, yL, remL ); 883 884 // If divisor < remainder. 885 if ( cmp < 0 ) { 886 887 // Calculate trial digit, n. 888 889 rem0 = rem[0]; 890 if ( yL != remL ) rem0 = rem0 * base + ( rem[1] || 0 ); 891 892 // n is how many times the divisor goes into the current remainder. 893 n = mathfloor( rem0 / yc0 ); 894 895 // Algorithm: 896 // 1. product = divisor * trial digit (n) 897 // 2. if product > remainder: product -= divisor, n-- 898 // 3. remainder -= product 899 // 4. if product was < remainder at 2: 900 // 5. compare new remainder and divisor 901 // 6. If remainder > divisor: remainder -= divisor, n++ 902 903 if ( n > 1 ) { 904 905 // n may be > base only when base is 3. 906 if (n >= base) n = base - 1; 907 908 // product = divisor * trial digit. 909 prod = multiply( yc, n, base ); 910 prodL = prod.length; 911 remL = rem.length; 912 913 // Compare product and remainder. 914 // If product > remainder. 915 // Trial digit n too high. 916 // n is 1 too high about 5% of the time, and is not known to have 917 // ever been more than 1 too high. 918 while ( compare( prod, rem, prodL, remL ) == 1 ) { 919 n--; 920 921 // Subtract divisor from product. 922 subtract( prod, yL < prodL ? yz : yc, prodL, base ); 923 prodL = prod.length; 924 cmp = 1; 925 } 926 } else { 927 928 // n is 0 or 1, cmp is -1. 929 // If n is 0, there is no need to compare yc and rem again below, 930 // so change cmp to 1 to avoid it. 931 // If n is 1, leave cmp as -1, so yc and rem are compared again. 932 if ( n == 0 ) { 933 934 // divisor < remainder, so n must be at least 1. 935 cmp = n = 1; 936 } 937 938 // product = divisor 939 prod = yc.slice(); 940 prodL = prod.length; 941 } 942 943 if ( prodL < remL ) prod = [0].concat(prod); 944 945 // Subtract product from remainder. 946 subtract( rem, prod, remL, base ); 947 remL = rem.length; 948 949 // If product was < remainder. 950 if ( cmp == -1 ) { 951 952 // Compare divisor and new remainder. 953 // If divisor < new remainder, subtract divisor from remainder. 954 // Trial digit n too low. 955 // n is 1 too low about 5% of the time, and very rarely 2 too low. 956 while ( compare( yc, rem, yL, remL ) < 1 ) { 957 n++; 958 959 // Subtract divisor from remainder. 960 subtract( rem, yL < remL ? yz : yc, remL, base ); 961 remL = rem.length; 962 } 963 } 964 } else if ( cmp === 0 ) { 965 n++; 966 rem = [0]; 967 } // else cmp === 1 and n will be 0 968 969 // Add the next digit, n, to the result array. 970 qc[i++] = n; 971 972 // Update the remainder. 973 if ( rem[0] ) { 974 rem[remL++] = xc[xi] || 0; 975 } else { 976 rem = [ xc[xi] ]; 977 remL = 1; 978 } 979 } while ( ( xi++ < xL || rem[0] != null ) && s-- ); 980 981 more = rem[0] != null; 982 983 // Leading zero? 984 if ( !qc[0] ) qc.splice(0, 1); 985 } 986 987 if ( base == BASE ) { 988 989 // To calculate q.e, first get the number of digits of qc[0]. 990 for ( i = 1, s = qc[0]; s >= 10; s /= 10, i++ ); 991 round( q, dp + ( q.e = i + e * LOG_BASE - 1 ) + 1, rm, more ); 992 993 // Caller is convertBase. 994 } else { 995 q.e = e; 996 q.r = +more; 997 } 998 999 return q; 1000 }; 1001 })(); 1002 1003 1004 /* 1005 * Return a string representing the value of BigNumber n in fixed-point or exponential 1006 * notation rounded to the specified decimal places or significant digits. 1007 * 1008 * n is a BigNumber. 1009 * i is the index of the last digit required (i.e. the digit that may be rounded up). 1010 * rm is the rounding mode. 1011 * caller is caller id: toExponential 19, toFixed 20, toFormat 21, toPrecision 24. 1012 */ 1013 function format( n, i, rm, caller ) { 1014 var c0, e, ne, len, str; 1015 1016 rm = rm != null && isValidInt( rm, 0, 8, caller, roundingMode ) 1017 ? rm | 0 : ROUNDING_MODE; 1018 1019 if ( !n.c ) return n.toString(); 1020 c0 = n.c[0]; 1021 ne = n.e; 1022 1023 if ( i == null ) { 1024 str = coeffToString( n.c ); 1025 str = caller == 19 || caller == 24 && ne <= TO_EXP_NEG 1026 ? toExponential( str, ne ) 1027 : toFixedPoint( str, ne ); 1028 } else { 1029 n = round( new BigNumber(n), i, rm ); 1030 1031 // n.e may have changed if the value was rounded up. 1032 e = n.e; 1033 1034 str = coeffToString( n.c ); 1035 len = str.length; 1036 1037 // toPrecision returns exponential notation if the number of significant digits 1038 // specified is less than the number of digits necessary to represent the integer 1039 // part of the value in fixed-point notation. 1040 1041 // Exponential notation. 1042 if ( caller == 19 || caller == 24 && ( i <= e || e <= TO_EXP_NEG ) ) { 1043 1044 // Append zeros? 1045 for ( ; len < i; str += '0', len++ ); 1046 str = toExponential( str, e ); 1047 1048 // Fixed-point notation. 1049 } else { 1050 i -= ne; 1051 str = toFixedPoint( str, e ); 1052 1053 // Append zeros? 1054 if ( e + 1 > len ) { 1055 if ( --i > 0 ) for ( str += '.'; i--; str += '0' ); 1056 } else { 1057 i += e - len; 1058 if ( i > 0 ) { 1059 if ( e + 1 == len ) str += '.'; 1060 for ( ; i--; str += '0' ); 1061 } 1062 } 1063 } 1064 } 1065 1066 return n.s < 0 && c0 ? '-' + str : str; 1067 } 1068 1069 1070 // Handle BigNumber.max and BigNumber.min. 1071 function maxOrMin( args, method ) { 1072 var m, n, 1073 i = 0; 1074 1075 if ( isArray( args[0] ) ) args = args[0]; 1076 m = new BigNumber( args[0] ); 1077 1078 for ( ; ++i < args.length; ) { 1079 n = new BigNumber( args[i] ); 1080 1081 // If any number is NaN, return NaN. 1082 if ( !n.s ) { 1083 m = n; 1084 break; 1085 } else if ( method.call( m, n ) ) { 1086 m = n; 1087 } 1088 } 1089 1090 return m; 1091 } 1092 1093 1094 /* 1095 * Return true if n is an integer in range, otherwise throw. 1096 * Use for argument validation when ERRORS is true. 1097 */ 1098 function intValidatorWithErrors( n, min, max, caller, name ) { 1099 if ( n < min || n > max || n != truncate(n) ) { 1100 raise( caller, ( name || 'decimal places' ) + 1101 ( n < min || n > max ? ' out of range' : ' not an integer' ), n ); 1102 } 1103 1104 return true; 1105 } 1106 1107 1108 /* 1109 * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. 1110 * Called by minus, plus and times. 1111 */ 1112 function normalise( n, c, e ) { 1113 var i = 1, 1114 j = c.length; 1115 1116 // Remove trailing zeros. 1117 for ( ; !c[--j]; c.pop() ); 1118 1119 // Calculate the base 10 exponent. First get the number of digits of c[0]. 1120 for ( j = c[0]; j >= 10; j /= 10, i++ ); 1121 1122 // Overflow? 1123 if ( ( e = i + e * LOG_BASE - 1 ) > MAX_EXP ) { 1124 1125 // Infinity. 1126 n.c = n.e = null; 1127 1128 // Underflow? 1129 } else if ( e < MIN_EXP ) { 1130 1131 // Zero. 1132 n.c = [ n.e = 0 ]; 1133 } else { 1134 n.e = e; 1135 n.c = c; 1136 } 1137 1138 return n; 1139 } 1140 1141 1142 // Handle values that fail the validity test in BigNumber. 1143 parseNumeric = (function () { 1144 var basePrefix = /^((-?)0([xbo]))(\w[\w.]*)$/i, 1145 dotAfter = /^([^.]+)\.$/, 1146 dotBefore = /^\.([^.]+)$/, 1147 isInfinityOrNaN = /^-?(Infinity|NaN)$/, 1148 whitespaceOrPlus = /^\s*\+([\w.])|^\s+|\s+$/g; 1149 1150 return function ( x, str, num, b ) { 1151 var base, 1152 s = num ? str : str.replace(whitespaceOrPlus, function (m, p1) { 1153 return m.indexOf('+') > -1 && p1 !== '' ? p1 : ''; 1154 }); 1155 1156 // No exception on ±Infinity or NaN. 1157 if ( isInfinityOrNaN.test(s) ) { 1158 x.s = isNaN(s) ? null : s < 0 ? -1 : 1; 1159 } else { 1160 if ( !num ) { 1161 1162 // basePrefix = /^((-?)0([xbo]))(\w[\w.]*)$/i 1163 s = s.replace( basePrefix, function ( s, m, p1, p2, p3 ) { 1164 base = ( p2 = p2.toLowerCase() ) == 'x' ? 16 : p2 == 'b' ? 2 : 8; 1165 return (!b || b == base ? p1 : m) + p3; 1166 }); 1167 1168 if (b) { 1169 base = b; 1170 1171 // E.g. '1.' to '1', '.1' to '0.1' 1172 s = s.replace( dotAfter, '$1' ).replace( dotBefore, '0.$1' ); 1173 } 1174 1175 if ( str != s ) return new BigNumber( s, base ); 1176 } 1177 1178 // 'new BigNumber() not a number: {n}' 1179 // 'new BigNumber() not a base {b} number: {n}' 1180 if (ERRORS) raise( id, 'not a' + ( b ? ' base ' + b : '' ) + ' number', str ); 1181 x.s = null; 1182 } 1183 1184 x.c = x.e = null; 1185 id = 0; 1186 } 1187 })(); 1188 1189 1190 // Throw a BigNumber Error. 1191 function raise( caller, msg, val ) { 1192 var error = new Error( [ 1193 'new BigNumber', // 0 1194 'cmp', // 1 1195 'config', // 2 1196 'div', // 3 1197 'divToInt', // 4 1198 'eq', // 5 1199 'gt', // 6 1200 'gte', // 7 1201 'lt', // 8 1202 'lte', // 9 1203 'minus', // 10 1204 'mod', // 11 1205 'plus', // 12 1206 'precision', // 13 1207 'random', // 14 1208 'round', // 15 1209 'shift', // 16 1210 'times', // 17 1211 'toDigits', // 18 1212 'toExponential', // 19 1213 'toFixed', // 20 1214 'toFormat', // 21 1215 'toFraction', // 22 1216 'pow', // 23 1217 'toPrecision', // 24 1218 'toString', // 25 1219 'BigNumber' // 26 1220 ][caller] + '() ' + msg + ': ' + val ); 1221 1222 error.name = 'BigNumber Error'; 1223 id = 0; 1224 throw error; 1225 } 1226 1227 1228 /* 1229 * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. 1230 * If r is truthy, it is known that there are more digits after the rounding digit. 1231 */ 1232 function round( x, sd, rm, r ) { 1233 var d, i, j, k, n, ni, rd, 1234 xc = x.c, 1235 pows10 = POWS_TEN; 1236 1237 // if x is not Infinity or NaN... 1238 if (xc) { 1239 1240 // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. 1241 // n is a base 1e14 number, the value of the element of array x.c containing rd. 1242 // ni is the index of n within x.c. 1243 // d is the number of digits of n. 1244 // i is the index of rd within n including leading zeros. 1245 // j is the actual index of rd within n (if < 0, rd is a leading zero). 1246 out: { 1247 1248 // Get the number of digits of the first element of xc. 1249 for ( d = 1, k = xc[0]; k >= 10; k /= 10, d++ ); 1250 i = sd - d; 1251 1252 // If the rounding digit is in the first element of xc... 1253 if ( i < 0 ) { 1254 i += LOG_BASE; 1255 j = sd; 1256 n = xc[ ni = 0 ]; 1257 1258 // Get the rounding digit at index j of n. 1259 rd = n / pows10[ d - j - 1 ] % 10 | 0; 1260 } else { 1261 ni = mathceil( ( i + 1 ) / LOG_BASE ); 1262 1263 if ( ni >= xc.length ) { 1264 1265 if (r) { 1266 1267 // Needed by sqrt. 1268 for ( ; xc.length <= ni; xc.push(0) ); 1269 n = rd = 0; 1270 d = 1; 1271 i %= LOG_BASE; 1272 j = i - LOG_BASE + 1; 1273 } else { 1274 break out; 1275 } 1276 } else { 1277 n = k = xc[ni]; 1278 1279 // Get the number of digits of n. 1280 for ( d = 1; k >= 10; k /= 10, d++ ); 1281 1282 // Get the index of rd within n. 1283 i %= LOG_BASE; 1284 1285 // Get the index of rd within n, adjusted for leading zeros. 1286 // The number of leading zeros of n is given by LOG_BASE - d. 1287 j = i - LOG_BASE + d; 1288 1289 // Get the rounding digit at index j of n. 1290 rd = j < 0 ? 0 : n / pows10[ d - j - 1 ] % 10 | 0; 1291 } 1292 } 1293 1294 r = r || sd < 0 || 1295 1296 // Are there any non-zero digits after the rounding digit? 1297 // The expression n % pows10[ d - j - 1 ] returns all digits of n to the right 1298 // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. 1299 xc[ni + 1] != null || ( j < 0 ? n : n % pows10[ d - j - 1 ] ); 1300 1301 r = rm < 4 1302 ? ( rd || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) ) 1303 : rd > 5 || rd == 5 && ( rm == 4 || r || rm == 6 && 1304 1305 // Check whether the digit to the left of the rounding digit is odd. 1306 ( ( i > 0 ? j > 0 ? n / pows10[ d - j ] : 0 : xc[ni - 1] ) % 10 ) & 1 || 1307 rm == ( x.s < 0 ? 8 : 7 ) ); 1308 1309 if ( sd < 1 || !xc[0] ) { 1310 xc.length = 0; 1311 1312 if (r) { 1313 1314 // Convert sd to decimal places. 1315 sd -= x.e + 1; 1316 1317 // 1, 0.1, 0.01, 0.001, 0.0001 etc. 1318 xc[0] = pows10[ ( LOG_BASE - sd % LOG_BASE ) % LOG_BASE ]; 1319 x.e = -sd || 0; 1320 } else { 1321 1322 // Zero. 1323 xc[0] = x.e = 0; 1324 } 1325 1326 return x; 1327 } 1328 1329 // Remove excess digits. 1330 if ( i == 0 ) { 1331 xc.length = ni; 1332 k = 1; 1333 ni--; 1334 } else { 1335 xc.length = ni + 1; 1336 k = pows10[ LOG_BASE - i ]; 1337 1338 // E.g. 56700 becomes 56000 if 7 is the rounding digit. 1339 // j > 0 means i > number of leading zeros of n. 1340 xc[ni] = j > 0 ? mathfloor( n / pows10[ d - j ] % pows10[j] ) * k : 0; 1341 } 1342 1343 // Round up? 1344 if (r) { 1345 1346 for ( ; ; ) { 1347 1348 // If the digit to be rounded up is in the first element of xc... 1349 if ( ni == 0 ) { 1350 1351 // i will be the length of xc[0] before k is added. 1352 for ( i = 1, j = xc[0]; j >= 10; j /= 10, i++ ); 1353 j = xc[0] += k; 1354 for ( k = 1; j >= 10; j /= 10, k++ ); 1355 1356 // if i != k the length has increased. 1357 if ( i != k ) { 1358 x.e++; 1359 if ( xc[0] == BASE ) xc[0] = 1; 1360 } 1361 1362 break; 1363 } else { 1364 xc[ni] += k; 1365 if ( xc[ni] != BASE ) break; 1366 xc[ni--] = 0; 1367 k = 1; 1368 } 1369 } 1370 } 1371 1372 // Remove trailing zeros. 1373 for ( i = xc.length; xc[--i] === 0; xc.pop() ); 1374 } 1375 1376 // Overflow? Infinity. 1377 if ( x.e > MAX_EXP ) { 1378 x.c = x.e = null; 1379 1380 // Underflow? Zero. 1381 } else if ( x.e < MIN_EXP ) { 1382 x.c = [ x.e = 0 ]; 1383 } 1384 } 1385 1386 return x; 1387 } 1388 1389 1390 // PROTOTYPE/INSTANCE METHODS 1391 1392 1393 /* 1394 * Return a new BigNumber whose value is the absolute value of this BigNumber. 1395 */ 1396 P.absoluteValue = P.abs = function () { 1397 var x = new BigNumber(this); 1398 if ( x.s < 0 ) x.s = 1; 1399 return x; 1400 }; 1401 1402 1403 /* 1404 * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole 1405 * number in the direction of Infinity. 1406 */ 1407 P.ceil = function () { 1408 return round( new BigNumber(this), this.e + 1, 2 ); 1409 }; 1410 1411 1412 /* 1413 * Return 1414 * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), 1415 * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), 1416 * 0 if they have the same value, 1417 * or null if the value of either is NaN. 1418 */ 1419 P.comparedTo = P.cmp = function ( y, b ) { 1420 id = 1; 1421 return compare( this, new BigNumber( y, b ) ); 1422 }; 1423 1424 1425 /* 1426 * Return the number of decimal places of the value of this BigNumber, or null if the value 1427 * of this BigNumber is ±Infinity or NaN. 1428 */ 1429 P.decimalPlaces = P.dp = function () { 1430 var n, v, 1431 c = this.c; 1432 1433 if ( !c ) return null; 1434 n = ( ( v = c.length - 1 ) - bitFloor( this.e / LOG_BASE ) ) * LOG_BASE; 1435 1436 // Subtract the number of trailing zeros of the last number. 1437 if ( v = c[v] ) for ( ; v % 10 == 0; v /= 10, n-- ); 1438 if ( n < 0 ) n = 0; 1439 1440 return n; 1441 }; 1442 1443 1444 /* 1445 * n / 0 = I 1446 * n / N = N 1447 * n / I = 0 1448 * 0 / n = 0 1449 * 0 / 0 = N 1450 * 0 / N = N 1451 * 0 / I = 0 1452 * N / n = N 1453 * N / 0 = N 1454 * N / N = N 1455 * N / I = N 1456 * I / n = I 1457 * I / 0 = I 1458 * I / N = N 1459 * I / I = N 1460 * 1461 * Return a new BigNumber whose value is the value of this BigNumber divided by the value of 1462 * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. 1463 */ 1464 P.dividedBy = P.div = function ( y, b ) { 1465 id = 3; 1466 return div( this, new BigNumber( y, b ), DECIMAL_PLACES, ROUNDING_MODE ); 1467 }; 1468 1469 1470 /* 1471 * Return a new BigNumber whose value is the integer part of dividing the value of this 1472 * BigNumber by the value of BigNumber(y, b). 1473 */ 1474 P.dividedToIntegerBy = P.divToInt = function ( y, b ) { 1475 id = 4; 1476 return div( this, new BigNumber( y, b ), 0, 1 ); 1477 }; 1478 1479 1480 /* 1481 * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), 1482 * otherwise returns false. 1483 */ 1484 P.equals = P.eq = function ( y, b ) { 1485 id = 5; 1486 return compare( this, new BigNumber( y, b ) ) === 0; 1487 }; 1488 1489 1490 /* 1491 * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole 1492 * number in the direction of -Infinity. 1493 */ 1494 P.floor = function () { 1495 return round( new BigNumber(this), this.e + 1, 3 ); 1496 }; 1497 1498 1499 /* 1500 * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), 1501 * otherwise returns false. 1502 */ 1503 P.greaterThan = P.gt = function ( y, b ) { 1504 id = 6; 1505 return compare( this, new BigNumber( y, b ) ) > 0; 1506 }; 1507 1508 1509 /* 1510 * Return true if the value of this BigNumber is greater than or equal to the value of 1511 * BigNumber(y, b), otherwise returns false. 1512 */ 1513 P.greaterThanOrEqualTo = P.gte = function ( y, b ) { 1514 id = 7; 1515 return ( b = compare( this, new BigNumber( y, b ) ) ) === 1 || b === 0; 1516 1517 }; 1518 1519 1520 /* 1521 * Return true if the value of this BigNumber is a finite number, otherwise returns false. 1522 */ 1523 P.isFinite = function () { 1524 return !!this.c; 1525 }; 1526 1527 1528 /* 1529 * Return true if the value of this BigNumber is an integer, otherwise return false. 1530 */ 1531 P.isInteger = P.isInt = function () { 1532 return !!this.c && bitFloor( this.e / LOG_BASE ) > this.c.length - 2; 1533 }; 1534 1535 1536 /* 1537 * Return true if the value of this BigNumber is NaN, otherwise returns false. 1538 */ 1539 P.isNaN = function () { 1540 return !this.s; 1541 }; 1542 1543 1544 /* 1545 * Return true if the value of this BigNumber is negative, otherwise returns false. 1546 */ 1547 P.isNegative = P.isNeg = function () { 1548 return this.s < 0; 1549 }; 1550 1551 1552 /* 1553 * Return true if the value of this BigNumber is 0 or -0, otherwise returns false. 1554 */ 1555 P.isZero = function () { 1556 return !!this.c && this.c[0] == 0; 1557 }; 1558 1559 1560 /* 1561 * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), 1562 * otherwise returns false. 1563 */ 1564 P.lessThan = P.lt = function ( y, b ) { 1565 id = 8; 1566 return compare( this, new BigNumber( y, b ) ) < 0; 1567 }; 1568 1569 1570 /* 1571 * Return true if the value of this BigNumber is less than or equal to the value of 1572 * BigNumber(y, b), otherwise returns false. 1573 */ 1574 P.lessThanOrEqualTo = P.lte = function ( y, b ) { 1575 id = 9; 1576 return ( b = compare( this, new BigNumber( y, b ) ) ) === -1 || b === 0; 1577 }; 1578 1579 1580 /* 1581 * n - 0 = n 1582 * n - N = N 1583 * n - I = -I 1584 * 0 - n = -n 1585 * 0 - 0 = 0 1586 * 0 - N = N 1587 * 0 - I = -I 1588 * N - n = N 1589 * N - 0 = N 1590 * N - N = N 1591 * N - I = N 1592 * I - n = I 1593 * I - 0 = I 1594 * I - N = N 1595 * I - I = N 1596 * 1597 * Return a new BigNumber whose value is the value of this BigNumber minus the value of 1598 * BigNumber(y, b). 1599 */ 1600 P.minus = P.sub = function ( y, b ) { 1601 var i, j, t, xLTy, 1602 x = this, 1603 a = x.s; 1604 1605 id = 10; 1606 y = new BigNumber( y, b ); 1607 b = y.s; 1608 1609 // Either NaN? 1610 if ( !a || !b ) return new BigNumber(NaN); 1611 1612 // Signs differ? 1613 if ( a != b ) { 1614 y.s = -b; 1615 return x.plus(y); 1616 } 1617 1618 var xe = x.e / LOG_BASE, 1619 ye = y.e / LOG_BASE, 1620 xc = x.c, 1621 yc = y.c; 1622 1623 if ( !xe || !ye ) { 1624 1625 // Either Infinity? 1626 if ( !xc || !yc ) return xc ? ( y.s = -b, y ) : new BigNumber( yc ? x : NaN ); 1627 1628 // Either zero? 1629 if ( !xc[0] || !yc[0] ) { 1630 1631 // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. 1632 return yc[0] ? ( y.s = -b, y ) : new BigNumber( xc[0] ? x : 1633 1634 // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity 1635 ROUNDING_MODE == 3 ? -0 : 0 ); 1636 } 1637 } 1638 1639 xe = bitFloor(xe); 1640 ye = bitFloor(ye); 1641 xc = xc.slice(); 1642 1643 // Determine which is the bigger number. 1644 if ( a = xe - ye ) { 1645 1646 if ( xLTy = a < 0 ) { 1647 a = -a; 1648 t = xc; 1649 } else { 1650 ye = xe; 1651 t = yc; 1652 } 1653 1654 t.reverse(); 1655 1656 // Prepend zeros to equalise exponents. 1657 for ( b = a; b--; t.push(0) ); 1658 t.reverse(); 1659 } else { 1660 1661 // Exponents equal. Check digit by digit. 1662 j = ( xLTy = ( a = xc.length ) < ( b = yc.length ) ) ? a : b; 1663 1664 for ( a = b = 0; b < j; b++ ) { 1665 1666 if ( xc[b] != yc[b] ) { 1667 xLTy = xc[b] < yc[b]; 1668 break; 1669 } 1670 } 1671 } 1672 1673 // x < y? Point xc to the array of the bigger number. 1674 if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s; 1675 1676 b = ( j = yc.length ) - ( i = xc.length ); 1677 1678 // Append zeros to xc if shorter. 1679 // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. 1680 if ( b > 0 ) for ( ; b--; xc[i++] = 0 ); 1681 b = BASE - 1; 1682 1683 // Subtract yc from xc. 1684 for ( ; j > a; ) { 1685 1686 if ( xc[--j] < yc[j] ) { 1687 for ( i = j; i && !xc[--i]; xc[i] = b ); 1688 --xc[i]; 1689 xc[j] += BASE; 1690 } 1691 1692 xc[j] -= yc[j]; 1693 } 1694 1695 // Remove leading zeros and adjust exponent accordingly. 1696 for ( ; xc[0] == 0; xc.splice(0, 1), --ye ); 1697 1698 // Zero? 1699 if ( !xc[0] ) { 1700 1701 // Following IEEE 754 (2008) 6.3, 1702 // n - n = +0 but n - n = -0 when rounding towards -Infinity. 1703 y.s = ROUNDING_MODE == 3 ? -1 : 1; 1704 y.c = [ y.e = 0 ]; 1705 return y; 1706 } 1707 1708 // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity 1709 // for finite x and y. 1710 return normalise( y, xc, ye ); 1711 }; 1712 1713 1714 /* 1715 * n % 0 = N 1716 * n % N = N 1717 * n % I = n 1718 * 0 % n = 0 1719 * -0 % n = -0 1720 * 0 % 0 = N 1721 * 0 % N = N 1722 * 0 % I = 0 1723 * N % n = N 1724 * N % 0 = N 1725 * N % N = N 1726 * N % I = N 1727 * I % n = N 1728 * I % 0 = N 1729 * I % N = N 1730 * I % I = N 1731 * 1732 * Return a new BigNumber whose value is the value of this BigNumber modulo the value of 1733 * BigNumber(y, b). The result depends on the value of MODULO_MODE. 1734 */ 1735 P.modulo = P.mod = function ( y, b ) { 1736 var q, s, 1737 x = this; 1738 1739 id = 11; 1740 y = new BigNumber( y, b ); 1741 1742 // Return NaN if x is Infinity or NaN, or y is NaN or zero. 1743 if ( !x.c || !y.s || y.c && !y.c[0] ) { 1744 return new BigNumber(NaN); 1745 1746 // Return x if y is Infinity or x is zero. 1747 } else if ( !y.c || x.c && !x.c[0] ) { 1748 return new BigNumber(x); 1749 } 1750 1751 if ( MODULO_MODE == 9 ) { 1752 1753 // Euclidian division: q = sign(y) * floor(x / abs(y)) 1754 // r = x - qy where 0 <= r < abs(y) 1755 s = y.s; 1756 y.s = 1; 1757 q = div( x, y, 0, 3 ); 1758 y.s = s; 1759 q.s *= s; 1760 } else { 1761 q = div( x, y, 0, MODULO_MODE ); 1762 } 1763 1764 return x.minus( q.times(y) ); 1765 }; 1766 1767 1768 /* 1769 * Return a new BigNumber whose value is the value of this BigNumber negated, 1770 * i.e. multiplied by -1. 1771 */ 1772 P.negated = P.neg = function () { 1773 var x = new BigNumber(this); 1774 x.s = -x.s || null; 1775 return x; 1776 }; 1777 1778 1779 /* 1780 * n + 0 = n 1781 * n + N = N 1782 * n + I = I 1783 * 0 + n = n 1784 * 0 + 0 = 0 1785 * 0 + N = N 1786 * 0 + I = I 1787 * N + n = N 1788 * N + 0 = N 1789 * N + N = N 1790 * N + I = N 1791 * I + n = I 1792 * I + 0 = I 1793 * I + N = N 1794 * I + I = I 1795 * 1796 * Return a new BigNumber whose value is the value of this BigNumber plus the value of 1797 * BigNumber(y, b). 1798 */ 1799 P.plus = P.add = function ( y, b ) { 1800 var t, 1801 x = this, 1802 a = x.s; 1803 1804 id = 12; 1805 y = new BigNumber( y, b ); 1806 b = y.s; 1807 1808 // Either NaN? 1809 if ( !a || !b ) return new BigNumber(NaN); 1810 1811 // Signs differ? 1812 if ( a != b ) { 1813 y.s = -b; 1814 return x.minus(y); 1815 } 1816 1817 var xe = x.e / LOG_BASE, 1818 ye = y.e / LOG_BASE, 1819 xc = x.c, 1820 yc = y.c; 1821 1822 if ( !xe || !ye ) { 1823 1824 // Return ±Infinity if either ±Infinity. 1825 if ( !xc || !yc ) return new BigNumber( a / 0 ); 1826 1827 // Either zero? 1828 // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. 1829 if ( !xc[0] || !yc[0] ) return yc[0] ? y : new BigNumber( xc[0] ? x : a * 0 ); 1830 } 1831 1832 xe = bitFloor(xe); 1833 ye = bitFloor(ye); 1834 xc = xc.slice(); 1835 1836 // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. 1837 if ( a = xe - ye ) { 1838 if ( a > 0 ) { 1839 ye = xe; 1840 t = yc; 1841 } else { 1842 a = -a; 1843 t = xc; 1844 } 1845 1846 t.reverse(); 1847 for ( ; a--; t.push(0) ); 1848 t.reverse(); 1849 } 1850 1851 a = xc.length; 1852 b = yc.length; 1853 1854 // Point xc to the longer array, and b to the shorter length. 1855 if ( a - b < 0 ) t = yc, yc = xc, xc = t, b = a; 1856 1857 // Only start adding at yc.length - 1 as the further digits of xc can be ignored. 1858 for ( a = 0; b; ) { 1859 a = ( xc[--b] = xc[b] + yc[b] + a ) / BASE | 0; 1860 xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; 1861 } 1862 1863 if (a) { 1864 xc = [a].concat(xc); 1865 ++ye; 1866 } 1867 1868 // No need to check for zero, as +x + +y != 0 && -x + -y != 0 1869 // ye = MAX_EXP + 1 possible 1870 return normalise( y, xc, ye ); 1871 }; 1872 1873 1874 /* 1875 * Return the number of significant digits of the value of this BigNumber. 1876 * 1877 * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0. 1878 */ 1879 P.precision = P.sd = function (z) { 1880 var n, v, 1881 x = this, 1882 c = x.c; 1883 1884 // 'precision() argument not a boolean or binary digit: {z}' 1885 if ( z != null && z !== !!z && z !== 1 && z !== 0 ) { 1886 if (ERRORS) raise( 13, 'argument' + notBool, z ); 1887 if ( z != !!z ) z = null; 1888 } 1889 1890 if ( !c ) return null; 1891 v = c.length - 1; 1892 n = v * LOG_BASE + 1; 1893 1894 if ( v = c[v] ) { 1895 1896 // Subtract the number of trailing zeros of the last element. 1897 for ( ; v % 10 == 0; v /= 10, n-- ); 1898 1899 // Add the number of digits of the first element. 1900 for ( v = c[0]; v >= 10; v /= 10, n++ ); 1901 } 1902 1903 if ( z && x.e + 1 > n ) n = x.e + 1; 1904 1905 return n; 1906 }; 1907 1908 1909 /* 1910 * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of 1911 * dp decimal places using rounding mode rm, or to 0 and ROUNDING_MODE respectively if 1912 * omitted. 1913 * 1914 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. 1915 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. 1916 * 1917 * 'round() decimal places out of range: {dp}' 1918 * 'round() decimal places not an integer: {dp}' 1919 * 'round() rounding mode not an integer: {rm}' 1920 * 'round() rounding mode out of range: {rm}' 1921 */ 1922 P.round = function ( dp, rm ) { 1923 var n = new BigNumber(this); 1924 1925 if ( dp == null || isValidInt( dp, 0, MAX, 15 ) ) { 1926 round( n, ~~dp + this.e + 1, rm == null || 1927 !isValidInt( rm, 0, 8, 15, roundingMode ) ? ROUNDING_MODE : rm | 0 ); 1928 } 1929 1930 return n; 1931 }; 1932 1933 1934 /* 1935 * Return a new BigNumber whose value is the value of this BigNumber shifted by k places 1936 * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. 1937 * 1938 * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. 1939 * 1940 * If k is out of range and ERRORS is false, the result will be ±0 if k < 0, or ±Infinity 1941 * otherwise. 1942 * 1943 * 'shift() argument not an integer: {k}' 1944 * 'shift() argument out of range: {k}' 1945 */ 1946 P.shift = function (k) { 1947 var n = this; 1948 return isValidInt( k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 16, 'argument' ) 1949 1950 // k < 1e+21, or truncate(k) will produce exponential notation. 1951 ? n.times( '1e' + truncate(k) ) 1952 : new BigNumber( n.c && n.c[0] && ( k < -MAX_SAFE_INTEGER || k > MAX_SAFE_INTEGER ) 1953 ? n.s * ( k < 0 ? 0 : 1 / 0 ) 1954 : n ); 1955 }; 1956 1957 1958 /* 1959 * sqrt(-n) = N 1960 * sqrt( N) = N 1961 * sqrt(-I) = N 1962 * sqrt( I) = I 1963 * sqrt( 0) = 0 1964 * sqrt(-0) = -0 1965 * 1966 * Return a new BigNumber whose value is the square root of the value of this BigNumber, 1967 * rounded according to DECIMAL_PLACES and ROUNDING_MODE. 1968 */ 1969 P.squareRoot = P.sqrt = function () { 1970 var m, n, r, rep, t, 1971 x = this, 1972 c = x.c, 1973 s = x.s, 1974 e = x.e, 1975 dp = DECIMAL_PLACES + 4, 1976 half = new BigNumber('0.5'); 1977 1978 // Negative/NaN/Infinity/zero? 1979 if ( s !== 1 || !c || !c[0] ) { 1980 return new BigNumber( !s || s < 0 && ( !c || c[0] ) ? NaN : c ? x : 1 / 0 ); 1981 } 1982 1983 // Initial estimate. 1984 s = Math.sqrt( +x ); 1985 1986 // Math.sqrt underflow/overflow? 1987 // Pass x to Math.sqrt as integer, then adjust the exponent of the result. 1988 if ( s == 0 || s == 1 / 0 ) { 1989 n = coeffToString(c); 1990 if ( ( n.length + e ) % 2 == 0 ) n += '0'; 1991 s = Math.sqrt(n); 1992 e = bitFloor( ( e + 1 ) / 2 ) - ( e < 0 || e % 2 ); 1993 1994 if ( s == 1 / 0 ) { 1995 n = '1e' + e; 1996 } else { 1997 n = s.toExponential(); 1998 n = n.slice( 0, n.indexOf('e') + 1 ) + e; 1999 } 2000 2001 r = new BigNumber(n); 2002 } else { 2003 r = new BigNumber( s + '' ); 2004 } 2005 2006 // Check for zero. 2007 // r could be zero if MIN_EXP is changed after the this value was created. 2008 // This would cause a division by zero (x/t) and hence Infinity below, which would cause 2009 // coeffToString to throw. 2010 if ( r.c[0] ) { 2011 e = r.e; 2012 s = e + dp; 2013 if ( s < 3 ) s = 0; 2014 2015 // Newton-Raphson iteration. 2016 for ( ; ; ) { 2017 t = r; 2018 r = half.times( t.plus( div( x, t, dp, 1 ) ) ); 2019 2020 if ( coeffToString( t.c ).slice( 0, s ) === ( n = 2021 coeffToString( r.c ) ).slice( 0, s ) ) { 2022 2023 // The exponent of r may here be one less than the final result exponent, 2024 // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits 2025 // are indexed correctly. 2026 if ( r.e < e ) --s; 2027 n = n.slice( s - 3, s + 1 ); 2028 2029 // The 4th rounding digit may be in error by -1 so if the 4 rounding digits 2030 // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the 2031 // iteration. 2032 if ( n == '9999' || !rep && n == '4999' ) { 2033 2034 // On the first iteration only, check to see if rounding up gives the 2035 // exact result as the nines may infinitely repeat. 2036 if ( !rep ) { 2037 round( t, t.e + DECIMAL_PLACES + 2, 0 ); 2038 2039 if ( t.times(t).eq(x) ) { 2040 r = t; 2041 break; 2042 } 2043 } 2044 2045 dp += 4; 2046 s += 4; 2047 rep = 1; 2048 } else { 2049 2050 // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact 2051 // result. If not, then there are further digits and m will be truthy. 2052 if ( !+n || !+n.slice(1) && n.charAt(0) == '5' ) { 2053 2054 // Truncate to the first rounding digit. 2055 round( r, r.e + DECIMAL_PLACES + 2, 1 ); 2056 m = !r.times(r).eq(x); 2057 } 2058 2059 break; 2060 } 2061 } 2062 } 2063 } 2064 2065 return round( r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m ); 2066 }; 2067 2068 2069 /* 2070 * n * 0 = 0 2071 * n * N = N 2072 * n * I = I 2073 * 0 * n = 0 2074 * 0 * 0 = 0 2075 * 0 * N = N 2076 * 0 * I = N 2077 * N * n = N 2078 * N * 0 = N 2079 * N * N = N 2080 * N * I = N 2081 * I * n = I 2082 * I * 0 = N 2083 * I * N = N 2084 * I * I = I 2085 * 2086 * Return a new BigNumber whose value is the value of this BigNumber times the value of 2087 * BigNumber(y, b). 2088 */ 2089 P.times = P.mul = function ( y, b ) { 2090 var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, 2091 base, sqrtBase, 2092 x = this, 2093 xc = x.c, 2094 yc = ( id = 17, y = new BigNumber( y, b ) ).c; 2095 2096 // Either NaN, ±Infinity or ±0? 2097 if ( !xc || !yc || !xc[0] || !yc[0] ) { 2098 2099 // Return NaN if either is NaN, or one is 0 and the other is Infinity. 2100 if ( !x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc ) { 2101 y.c = y.e = y.s = null; 2102 } else { 2103 y.s *= x.s; 2104 2105 // Return ±Infinity if either is ±Infinity. 2106 if ( !xc || !yc ) { 2107 y.c = y.e = null; 2108 2109 // Return ±0 if either is ±0. 2110 } else { 2111 y.c = [0]; 2112 y.e = 0; 2113 } 2114 } 2115 2116 return y; 2117 } 2118 2119 e = bitFloor( x.e / LOG_BASE ) + bitFloor( y.e / LOG_BASE ); 2120 y.s *= x.s; 2121 xcL = xc.length; 2122 ycL = yc.length; 2123 2124 // Ensure xc points to longer array and xcL to its length. 2125 if ( xcL < ycL ) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i; 2126 2127 // Initialise the result array with zeros. 2128 for ( i = xcL + ycL, zc = []; i--; zc.push(0) ); 2129 2130 base = BASE; 2131 sqrtBase = SQRT_BASE; 2132 2133 for ( i = ycL; --i >= 0; ) { 2134 c = 0; 2135 ylo = yc[i] % sqrtBase; 2136 yhi = yc[i] / sqrtBase | 0; 2137 2138 for ( k = xcL, j = i + k; j > i; ) { 2139 xlo = xc[--k] % sqrtBase; 2140 xhi = xc[k] / sqrtBase | 0; 2141 m = yhi * xlo + xhi * ylo; 2142 xlo = ylo * xlo + ( ( m % sqrtBase ) * sqrtBase ) + zc[j] + c; 2143 c = ( xlo / base | 0 ) + ( m / sqrtBase | 0 ) + yhi * xhi; 2144 zc[j--] = xlo % base; 2145 } 2146 2147 zc[j] = c; 2148 } 2149 2150 if (c) { 2151 ++e; 2152 } else { 2153 zc.splice(0, 1); 2154 } 2155 2156 return normalise( y, zc, e ); 2157 }; 2158 2159 2160 /* 2161 * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of 2162 * sd significant digits using rounding mode rm, or ROUNDING_MODE if rm is omitted. 2163 * 2164 * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. 2165 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. 2166 * 2167 * 'toDigits() precision out of range: {sd}' 2168 * 'toDigits() precision not an integer: {sd}' 2169 * 'toDigits() rounding mode not an integer: {rm}' 2170 * 'toDigits() rounding mode out of range: {rm}' 2171 */ 2172 P.toDigits = function ( sd, rm ) { 2173 var n = new BigNumber(this); 2174 sd = sd == null || !isValidInt( sd, 1, MAX, 18, 'precision' ) ? null : sd | 0; 2175 rm = rm == null || !isValidInt( rm, 0, 8, 18, roundingMode ) ? ROUNDING_MODE : rm | 0; 2176 return sd ? round( n, sd, rm ) : n; 2177 }; 2178 2179 2180 /* 2181 * Return a string representing the value of this BigNumber in exponential notation and 2182 * rounded using ROUNDING_MODE to dp fixed decimal places. 2183 * 2184 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. 2185 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. 2186 * 2187 * 'toExponential() decimal places not an integer: {dp}' 2188 * 'toExponential() decimal places out of range: {dp}' 2189 * 'toExponential() rounding mode not an integer: {rm}' 2190 * 'toExponential() rounding mode out of range: {rm}' 2191 */ 2192 P.toExponential = function ( dp, rm ) { 2193 return format( this, 2194 dp != null && isValidInt( dp, 0, MAX, 19 ) ? ~~dp + 1 : null, rm, 19 ); 2195 }; 2196 2197 2198 /* 2199 * Return a string representing the value of this BigNumber in fixed-point notation rounding 2200 * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. 2201 * 2202 * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', 2203 * but e.g. (-0.00001).toFixed(0) is '-0'. 2204 * 2205 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. 2206 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. 2207 * 2208 * 'toFixed() decimal places not an integer: {dp}' 2209 * 'toFixed() decimal places out of range: {dp}' 2210 * 'toFixed() rounding mode not an integer: {rm}' 2211 * 'toFixed() rounding mode out of range: {rm}' 2212 */ 2213 P.toFixed = function ( dp, rm ) { 2214 return format( this, dp != null && isValidInt( dp, 0, MAX, 20 ) 2215 ? ~~dp + this.e + 1 : null, rm, 20 ); 2216 }; 2217 2218 2219 /* 2220 * Return a string representing the value of this BigNumber in fixed-point notation rounded 2221 * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties 2222 * of the FORMAT object (see BigNumber.config). 2223 * 2224 * FORMAT = { 2225 * decimalSeparator : '.', 2226 * groupSeparator : ',', 2227 * groupSize : 3, 2228 * secondaryGroupSize : 0, 2229 * fractionGroupSeparator : '\xA0', // non-breaking space 2230 * fractionGroupSize : 0 2231 * }; 2232 * 2233 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. 2234 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. 2235 * 2236 * 'toFormat() decimal places not an integer: {dp}' 2237 * 'toFormat() decimal places out of range: {dp}' 2238 * 'toFormat() rounding mode not an integer: {rm}' 2239 * 'toFormat() rounding mode out of range: {rm}' 2240 */ 2241 P.toFormat = function ( dp, rm ) { 2242 var str = format( this, dp != null && isValidInt( dp, 0, MAX, 21 ) 2243 ? ~~dp + this.e + 1 : null, rm, 21 ); 2244 2245 if ( this.c ) { 2246 var i, 2247 arr = str.split('.'), 2248 g1 = +FORMAT.groupSize, 2249 g2 = +FORMAT.secondaryGroupSize, 2250 groupSeparator = FORMAT.groupSeparator, 2251 intPart = arr[0], 2252 fractionPart = arr[1], 2253 isNeg = this.s < 0, 2254 intDigits = isNeg ? intPart.slice(1) : intPart, 2255 len = intDigits.length; 2256 2257 if (g2) i = g1, g1 = g2, g2 = i, len -= i; 2258 2259 if ( g1 > 0 && len > 0 ) { 2260 i = len % g1 || g1; 2261 intPart = intDigits.substr( 0, i ); 2262 2263 for ( ; i < len; i += g1 ) { 2264 intPart += groupSeparator + intDigits.substr( i, g1 ); 2265 } 2266 2267 if ( g2 > 0 ) intPart += groupSeparator + intDigits.slice(i); 2268 if (isNeg) intPart = '-' + intPart; 2269 } 2270 2271 str = fractionPart 2272 ? intPart + FORMAT.decimalSeparator + ( ( g2 = +FORMAT.fractionGroupSize ) 2273 ? fractionPart.replace( new RegExp( '\\d{' + g2 + '}\\B', 'g' ), 2274 '$&' + FORMAT.fractionGroupSeparator ) 2275 : fractionPart ) 2276 : intPart; 2277 } 2278 2279 return str; 2280 }; 2281 2282 2283 /* 2284 * Return a string array representing the value of this BigNumber as a simple fraction with 2285 * an integer numerator and an integer denominator. The denominator will be a positive 2286 * non-zero value less than or equal to the specified maximum denominator. If a maximum 2287 * denominator is not specified, the denominator will be the lowest value necessary to 2288 * represent the number exactly. 2289 * 2290 * [md] {number|string|BigNumber} Integer >= 1 and < Infinity. The maximum denominator. 2291 * 2292 * 'toFraction() max denominator not an integer: {md}' 2293 * 'toFraction() max denominator out of range: {md}' 2294 */ 2295 P.toFraction = function (md) { 2296 var arr, d0, d2, e, exp, n, n0, q, s, 2297 k = ERRORS, 2298 x = this, 2299 xc = x.c, 2300 d = new BigNumber(ONE), 2301 n1 = d0 = new BigNumber(ONE), 2302 d1 = n0 = new BigNumber(ONE); 2303 2304 if ( md != null ) { 2305 ERRORS = false; 2306 n = new BigNumber(md); 2307 ERRORS = k; 2308 2309 if ( !( k = n.isInt() ) || n.lt(ONE) ) { 2310 2311 if (ERRORS) { 2312 raise( 22, 2313 'max denominator ' + ( k ? 'out of range' : 'not an integer' ), md ); 2314 } 2315 2316 // ERRORS is false: 2317 // If md is a finite non-integer >= 1, round it to an integer and use it. 2318 md = !k && n.c && round( n, n.e + 1, 1 ).gte(ONE) ? n : null; 2319 } 2320 } 2321 2322 if ( !xc ) return x.toString(); 2323 s = coeffToString(xc); 2324 2325 // Determine initial denominator. 2326 // d is a power of 10 and the minimum max denominator that specifies the value exactly. 2327 e = d.e = s.length - x.e - 1; 2328 d.c[0] = POWS_TEN[ ( exp = e % LOG_BASE ) < 0 ? LOG_BASE + exp : exp ]; 2329 md = !md || n.cmp(d) > 0 ? ( e > 0 ? d : n1 ) : n; 2330 2331 exp = MAX_EXP; 2332 MAX_EXP = 1 / 0; 2333 n = new BigNumber(s); 2334 2335 // n0 = d1 = 0 2336 n0.c[0] = 0; 2337 2338 for ( ; ; ) { 2339 q = div( n, d, 0, 1 ); 2340 d2 = d0.plus( q.times(d1) ); 2341 if ( d2.cmp(md) == 1 ) break; 2342 d0 = d1; 2343 d1 = d2; 2344 n1 = n0.plus( q.times( d2 = n1 ) ); 2345 n0 = d2; 2346 d = n.minus( q.times( d2 = d ) ); 2347 n = d2; 2348 } 2349 2350 d2 = div( md.minus(d0), d1, 0, 1 ); 2351 n0 = n0.plus( d2.times(n1) ); 2352 d0 = d0.plus( d2.times(d1) ); 2353 n0.s = n1.s = x.s; 2354 e *= 2; 2355 2356 // Determine which fraction is closer to x, n0/d0 or n1/d1 2357 arr = div( n1, d1, e, ROUNDING_MODE ).minus(x).abs().cmp( 2358 div( n0, d0, e, ROUNDING_MODE ).minus(x).abs() ) < 1 2359 ? [ n1.toString(), d1.toString() ] 2360 : [ n0.toString(), d0.toString() ]; 2361 2362 MAX_EXP = exp; 2363 return arr; 2364 }; 2365 2366 2367 /* 2368 * Return the value of this BigNumber converted to a number primitive. 2369 */ 2370 P.toNumber = function () { 2371 return +this; 2372 }; 2373 2374 2375 /* 2376 * Return a BigNumber whose value is the value of this BigNumber raised to the power n. 2377 * If m is present, return the result modulo m. 2378 * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. 2379 * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using 2380 * ROUNDING_MODE. 2381 * 2382 * The modular power operation works efficiently when x, n, and m are positive integers, 2383 * otherwise it is equivalent to calculating x.toPower(n).modulo(m) (with POW_PRECISION 0). 2384 * 2385 * n {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. 2386 * [m] {number|string|BigNumber} The modulus. 2387 * 2388 * 'pow() exponent not an integer: {n}' 2389 * 'pow() exponent out of range: {n}' 2390 * 2391 * Performs 54 loop iterations for n of 9007199254740991. 2392 */ 2393 P.toPower = P.pow = function ( n, m ) { 2394 var k, y, z, 2395 i = mathfloor( n < 0 ? -n : +n ), 2396 x = this; 2397 2398 if ( m != null ) { 2399 id = 23; 2400 m = new BigNumber(m); 2401 } 2402 2403 // Pass ±Infinity to Math.pow if exponent is out of range. 2404 if ( !isValidInt( n, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 23, 'exponent' ) && 2405 ( !isFinite(n) || i > MAX_SAFE_INTEGER && ( n /= 0 ) || 2406 parseFloat(n) != n && !( n = NaN ) ) || n == 0 ) { 2407 k = Math.pow( +x, n ); 2408 return new BigNumber( m ? k % m : k ); 2409 } 2410 2411 if (m) { 2412 if ( n > 1 && x.gt(ONE) && x.isInt() && m.gt(ONE) && m.isInt() ) { 2413 x = x.mod(m); 2414 } else { 2415 z = m; 2416 2417 // Nullify m so only a single mod operation is performed at the end. 2418 m = null; 2419 } 2420 } else if (POW_PRECISION) { 2421 2422 // Truncating each coefficient array to a length of k after each multiplication 2423 // equates to truncating significant digits to POW_PRECISION + [28, 41], 2424 // i.e. there will be a minimum of 28 guard digits retained. 2425 // (Using + 1.5 would give [9, 21] guard digits.) 2426 k = mathceil( POW_PRECISION / LOG_BASE + 2 ); 2427 } 2428 2429 y = new BigNumber(ONE); 2430 2431 for ( ; ; ) { 2432 if ( i % 2 ) { 2433 y = y.times(x); 2434 if ( !y.c ) break; 2435 if (k) { 2436 if ( y.c.length > k ) y.c.length = k; 2437 } else if (m) { 2438 y = y.mod(m); 2439 } 2440 } 2441 2442 i = mathfloor( i / 2 ); 2443 if ( !i ) break; 2444 x = x.times(x); 2445 if (k) { 2446 if ( x.c && x.c.length > k ) x.c.length = k; 2447 } else if (m) { 2448 x = x.mod(m); 2449 } 2450 } 2451 2452 if (m) return y; 2453 if ( n < 0 ) y = ONE.div(y); 2454 2455 return z ? y.mod(z) : k ? round( y, POW_PRECISION, ROUNDING_MODE ) : y; 2456 }; 2457 2458 2459 /* 2460 * Return a string representing the value of this BigNumber rounded to sd significant digits 2461 * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits 2462 * necessary to represent the integer part of the value in fixed-point notation, then use 2463 * exponential notation. 2464 * 2465 * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. 2466 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. 2467 * 2468 * 'toPrecision() precision not an integer: {sd}' 2469 * 'toPrecision() precision out of range: {sd}' 2470 * 'toPrecision() rounding mode not an integer: {rm}' 2471 * 'toPrecision() rounding mode out of range: {rm}' 2472 */ 2473 P.toPrecision = function ( sd, rm ) { 2474 return format( this, sd != null && isValidInt( sd, 1, MAX, 24, 'precision' ) 2475 ? sd | 0 : null, rm, 24 ); 2476 }; 2477 2478 2479 /* 2480 * Return a string representing the value of this BigNumber in base b, or base 10 if b is 2481 * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and 2482 * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent 2483 * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than 2484 * TO_EXP_NEG, return exponential notation. 2485 * 2486 * [b] {number} Integer, 2 to 64 inclusive. 2487 * 2488 * 'toString() base not an integer: {b}' 2489 * 'toString() base out of range: {b}' 2490 */ 2491 P.toString = function (b) { 2492 var str, 2493 n = this, 2494 s = n.s, 2495 e = n.e; 2496 2497 // Infinity or NaN? 2498 if ( e === null ) { 2499 2500 if (s) { 2501 str = 'Infinity'; 2502 if ( s < 0 ) str = '-' + str; 2503 } else { 2504 str = 'NaN'; 2505 } 2506 } else { 2507 str = coeffToString( n.c ); 2508 2509 if ( b == null || !isValidInt( b, 2, 64, 25, 'base' ) ) { 2510 str = e <= TO_EXP_NEG || e >= TO_EXP_POS 2511 ? toExponential( str, e ) 2512 : toFixedPoint( str, e ); 2513 } else { 2514 str = convertBase( toFixedPoint( str, e ), b | 0, 10, s ); 2515 } 2516 2517 if ( s < 0 && n.c[0] ) str = '-' + str; 2518 } 2519 2520 return str; 2521 }; 2522 2523 2524 /* 2525 * Return a new BigNumber whose value is the value of this BigNumber truncated to a whole 2526 * number. 2527 */ 2528 P.truncated = P.trunc = function () { 2529 return round( new BigNumber(this), this.e + 1, 1 ); 2530 }; 2531 2532 2533 /* 2534 * Return as toString, but do not accept a base argument, and include the minus sign for 2535 * negative zero. 2536 */ 2537 P.valueOf = P.toJSON = function () { 2538 var str, 2539 n = this, 2540 e = n.e; 2541 2542 if ( e === null ) return n.toString(); 2543 2544 str = coeffToString( n.c ); 2545 2546 str = e <= TO_EXP_NEG || e >= TO_EXP_POS 2547 ? toExponential( str, e ) 2548 : toFixedPoint( str, e ); 2549 2550 return n.s < 0 ? '-' + str : str; 2551 }; 2552 2553 2554 P.isBigNumber = true; 2555 2556 if ( config != null ) BigNumber.config(config); 2557 2558 return BigNumber; 2559 } 2560 2561 2562 // PRIVATE HELPER FUNCTIONS 2563 2564 2565 function bitFloor(n) { 2566 var i = n | 0; 2567 return n > 0 || n === i ? i : i - 1; 2568 } 2569 2570 2571 // Return a coefficient array as a string of base 10 digits. 2572 function coeffToString(a) { 2573 var s, z, 2574 i = 1, 2575 j = a.length, 2576 r = a[0] + ''; 2577 2578 for ( ; i < j; ) { 2579 s = a[i++] + ''; 2580 z = LOG_BASE - s.length; 2581 for ( ; z--; s = '0' + s ); 2582 r += s; 2583 } 2584 2585 // Determine trailing zeros. 2586 for ( j = r.length; r.charCodeAt(--j) === 48; ); 2587 return r.slice( 0, j + 1 || 1 ); 2588 } 2589 2590 2591 // Compare the value of BigNumbers x and y. 2592 function compare( x, y ) { 2593 var a, b, 2594 xc = x.c, 2595 yc = y.c, 2596 i = x.s, 2597 j = y.s, 2598 k = x.e, 2599 l = y.e; 2600 2601 // Either NaN? 2602 if ( !i || !j ) return null; 2603 2604 a = xc && !xc[0]; 2605 b = yc && !yc[0]; 2606 2607 // Either zero? 2608 if ( a || b ) return a ? b ? 0 : -j : i; 2609 2610 // Signs differ? 2611 if ( i != j ) return i; 2612 2613 a = i < 0; 2614 b = k == l; 2615 2616 // Either Infinity? 2617 if ( !xc || !yc ) return b ? 0 : !xc ^ a ? 1 : -1; 2618 2619 // Compare exponents. 2620 if ( !b ) return k > l ^ a ? 1 : -1; 2621 2622 j = ( k = xc.length ) < ( l = yc.length ) ? k : l; 2623 2624 // Compare digit by digit. 2625 for ( i = 0; i < j; i++ ) if ( xc[i] != yc[i] ) return xc[i] > yc[i] ^ a ? 1 : -1; 2626 2627 // Compare lengths. 2628 return k == l ? 0 : k > l ^ a ? 1 : -1; 2629 } 2630 2631 2632 /* 2633 * Return true if n is a valid number in range, otherwise false. 2634 * Use for argument validation when ERRORS is false. 2635 * Note: parseInt('1e+1') == 1 but parseFloat('1e+1') == 10. 2636 */ 2637 function intValidatorNoErrors( n, min, max ) { 2638 return ( n = truncate(n) ) >= min && n <= max; 2639 } 2640 2641 2642 function isArray(obj) { 2643 return Object.prototype.toString.call(obj) == '[object Array]'; 2644 } 2645 2646 2647 /* 2648 * Convert string of baseIn to an array of numbers of baseOut. 2649 * Eg. convertBase('255', 10, 16) returns [15, 15]. 2650 * Eg. convertBase('ff', 16, 10) returns [2, 5, 5]. 2651 */ 2652 function toBaseOut( str, baseIn, baseOut ) { 2653 var j, 2654 arr = [0], 2655 arrL, 2656 i = 0, 2657 len = str.length; 2658 2659 for ( ; i < len; ) { 2660 for ( arrL = arr.length; arrL--; arr[arrL] *= baseIn ); 2661 arr[ j = 0 ] += ALPHABET.indexOf( str.charAt( i++ ) ); 2662 2663 for ( ; j < arr.length; j++ ) { 2664 2665 if ( arr[j] > baseOut - 1 ) { 2666 if ( arr[j + 1] == null ) arr[j + 1] = 0; 2667 arr[j + 1] += arr[j] / baseOut | 0; 2668 arr[j] %= baseOut; 2669 } 2670 } 2671 } 2672 2673 return arr.reverse(); 2674 } 2675 2676 2677 function toExponential( str, e ) { 2678 return ( str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str ) + 2679 ( e < 0 ? 'e' : 'e+' ) + e; 2680 } 2681 2682 2683 function toFixedPoint( str, e ) { 2684 var len, z; 2685 2686 // Negative exponent? 2687 if ( e < 0 ) { 2688 2689 // Prepend zeros. 2690 for ( z = '0.'; ++e; z += '0' ); 2691 str = z + str; 2692 2693 // Positive exponent 2694 } else { 2695 len = str.length; 2696 2697 // Append zeros. 2698 if ( ++e > len ) { 2699 for ( z = '0', e -= len; --e; z += '0' ); 2700 str += z; 2701 } else if ( e < len ) { 2702 str = str.slice( 0, e ) + '.' + str.slice(e); 2703 } 2704 } 2705 2706 return str; 2707 } 2708 2709 2710 function truncate(n) { 2711 n = parseFloat(n); 2712 return n < 0 ? mathceil(n) : mathfloor(n); 2713 } 2714 2715 2716 // EXPORT 2717 2718 2719 BigNumber = constructorFactory(); 2720 BigNumber['default'] = BigNumber.BigNumber = BigNumber; 2721 2722 2723 // AMD. 2724 if ( typeof define == 'function' && define.amd ) { 2725 define( function () { return BigNumber; } ); 2726 2727 // Node.js and other environments that support module.exports. 2728 } else if ( typeof module != 'undefined' && module.exports ) { 2729 module.exports = BigNumber; 2730 2731 // Browser. 2732 } else { 2733 if ( !globalObj ) globalObj = typeof self != 'undefined' ? self : Function('return this')(); 2734 globalObj.BigNumber = BigNumber; 2735 } 2736 })(this);