bignumber.mjs 82 KB

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