bignumber.js 85 KB

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