選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

bignumber.mjs 83KB

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