bignumber.js 87 KB

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