decimal.mjs 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985
  1. /*
  2. * decimal.js-light v2.5.1
  3. * An arbitrary-precision Decimal type for JavaScript.
  4. * https://github.com/MikeMcl/decimal.js-light
  5. * Copyright (c) 2020 Michael Mclaughlin <M8ch88l@gmail.com>
  6. * MIT Expat Licence
  7. */
  8. // ------------------------------------ EDITABLE DEFAULTS ------------------------------------- //
  9. // The limit on the value of `precision`, and on the value of the first argument to
  10. // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`.
  11. var MAX_DIGITS = 1e9, // 0 to 1e9
  12. // The initial configuration properties of the Decimal constructor.
  13. defaults = {
  14. // These values must be integers within the stated ranges (inclusive).
  15. // Most of these values can be changed during run-time using `Decimal.config`.
  16. // The maximum number of significant digits of the result of a calculation or base conversion.
  17. // E.g. `Decimal.config({ precision: 20 });`
  18. precision: 20, // 1 to MAX_DIGITS
  19. // The rounding mode used by default by `toInteger`, `toDecimalPlaces`, `toExponential`,
  20. // `toFixed`, `toPrecision` and `toSignificantDigits`.
  21. //
  22. // ROUND_UP 0 Away from zero.
  23. // ROUND_DOWN 1 Towards zero.
  24. // ROUND_CEIL 2 Towards +Infinity.
  25. // ROUND_FLOOR 3 Towards -Infinity.
  26. // ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up.
  27. // ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
  28. // ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
  29. // ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
  30. // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
  31. //
  32. // E.g.
  33. // `Decimal.rounding = 4;`
  34. // `Decimal.rounding = Decimal.ROUND_HALF_UP;`
  35. rounding: 4, // 0 to 8
  36. // The exponent value at and beneath which `toString` returns exponential notation.
  37. // JavaScript numbers: -7
  38. toExpNeg: -7, // 0 to -MAX_E
  39. // The exponent value at and above which `toString` returns exponential notation.
  40. // JavaScript numbers: 21
  41. toExpPos: 21, // 0 to MAX_E
  42. // The natural logarithm of 10.
  43. // 115 digits
  44. LN10: '2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286'
  45. },
  46. // ------------------------------------ END OF EDITABLE DEFAULTS -------------------------------- //
  47. Decimal,
  48. external = true,
  49. decimalError = '[DecimalError] ',
  50. invalidArgument = decimalError + 'Invalid argument: ',
  51. exponentOutOfRange = decimalError + 'Exponent out of range: ',
  52. mathfloor = Math.floor,
  53. mathpow = Math.pow,
  54. isDecimal = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
  55. ONE,
  56. BASE = 1e7,
  57. LOG_BASE = 7,
  58. MAX_SAFE_INTEGER = 9007199254740991,
  59. MAX_E = mathfloor(MAX_SAFE_INTEGER / LOG_BASE), // 1286742750677284
  60. // Decimal.prototype object
  61. P = {};
  62. // Decimal prototype methods
  63. /*
  64. * absoluteValue abs
  65. * comparedTo cmp
  66. * decimalPlaces dp
  67. * dividedBy div
  68. * dividedToIntegerBy idiv
  69. * equals eq
  70. * exponent
  71. * greaterThan gt
  72. * greaterThanOrEqualTo gte
  73. * isInteger isint
  74. * isNegative isneg
  75. * isPositive ispos
  76. * isZero
  77. * lessThan lt
  78. * lessThanOrEqualTo lte
  79. * logarithm log
  80. * minus sub
  81. * modulo mod
  82. * naturalExponential exp
  83. * naturalLogarithm ln
  84. * negated neg
  85. * plus add
  86. * precision sd
  87. * squareRoot sqrt
  88. * times mul
  89. * toDecimalPlaces todp
  90. * toExponential
  91. * toFixed
  92. * toInteger toint
  93. * toNumber
  94. * toPower pow
  95. * toPrecision
  96. * toSignificantDigits tosd
  97. * toString
  98. * valueOf val
  99. */
  100. /*
  101. * Return a new Decimal whose value is the absolute value of this Decimal.
  102. *
  103. */
  104. P.absoluteValue = P.abs = function () {
  105. var x = new this.constructor(this);
  106. if (x.s) x.s = 1;
  107. return x;
  108. };
  109. /*
  110. * Return
  111. * 1 if the value of this Decimal is greater than the value of `y`,
  112. * -1 if the value of this Decimal is less than the value of `y`,
  113. * 0 if they have the same value
  114. *
  115. */
  116. P.comparedTo = P.cmp = function (y) {
  117. var i, j, xdL, ydL,
  118. x = this;
  119. y = new x.constructor(y);
  120. // Signs differ?
  121. if (x.s !== y.s) return x.s || -y.s;
  122. // Compare exponents.
  123. if (x.e !== y.e) return x.e > y.e ^ x.s < 0 ? 1 : -1;
  124. xdL = x.d.length;
  125. ydL = y.d.length;
  126. // Compare digit by digit.
  127. for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) {
  128. if (x.d[i] !== y.d[i]) return x.d[i] > y.d[i] ^ x.s < 0 ? 1 : -1;
  129. }
  130. // Compare lengths.
  131. return xdL === ydL ? 0 : xdL > ydL ^ x.s < 0 ? 1 : -1;
  132. };
  133. /*
  134. * Return the number of decimal places of the value of this Decimal.
  135. *
  136. */
  137. P.decimalPlaces = P.dp = function () {
  138. var x = this,
  139. w = x.d.length - 1,
  140. dp = (w - x.e) * LOG_BASE;
  141. // Subtract the number of trailing zeros of the last word.
  142. w = x.d[w];
  143. if (w) for (; w % 10 == 0; w /= 10) dp--;
  144. return dp < 0 ? 0 : dp;
  145. };
  146. /*
  147. * Return a new Decimal whose value is the value of this Decimal divided by `y`, truncated to
  148. * `precision` significant digits.
  149. *
  150. */
  151. P.dividedBy = P.div = function (y) {
  152. return divide(this, new this.constructor(y));
  153. };
  154. /*
  155. * Return a new Decimal whose value is the integer part of dividing the value of this Decimal
  156. * by the value of `y`, truncated to `precision` significant digits.
  157. *
  158. */
  159. P.dividedToIntegerBy = P.idiv = function (y) {
  160. var x = this,
  161. Ctor = x.constructor;
  162. return round(divide(x, new Ctor(y), 0, 1), Ctor.precision);
  163. };
  164. /*
  165. * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false.
  166. *
  167. */
  168. P.equals = P.eq = function (y) {
  169. return !this.cmp(y);
  170. };
  171. /*
  172. * Return the (base 10) exponent value of this Decimal (this.e is the base 10000000 exponent).
  173. *
  174. */
  175. P.exponent = function () {
  176. return getBase10Exponent(this);
  177. };
  178. /*
  179. * Return true if the value of this Decimal is greater than the value of `y`, otherwise return
  180. * false.
  181. *
  182. */
  183. P.greaterThan = P.gt = function (y) {
  184. return this.cmp(y) > 0;
  185. };
  186. /*
  187. * Return true if the value of this Decimal is greater than or equal to the value of `y`,
  188. * otherwise return false.
  189. *
  190. */
  191. P.greaterThanOrEqualTo = P.gte = function (y) {
  192. return this.cmp(y) >= 0;
  193. };
  194. /*
  195. * Return true if the value of this Decimal is an integer, otherwise return false.
  196. *
  197. */
  198. P.isInteger = P.isint = function () {
  199. return this.e > this.d.length - 2;
  200. };
  201. /*
  202. * Return true if the value of this Decimal is negative, otherwise return false.
  203. *
  204. */
  205. P.isNegative = P.isneg = function () {
  206. return this.s < 0;
  207. };
  208. /*
  209. * Return true if the value of this Decimal is positive, otherwise return false.
  210. *
  211. */
  212. P.isPositive = P.ispos = function () {
  213. return this.s > 0;
  214. };
  215. /*
  216. * Return true if the value of this Decimal is 0, otherwise return false.
  217. *
  218. */
  219. P.isZero = function () {
  220. return this.s === 0;
  221. };
  222. /*
  223. * Return true if the value of this Decimal is less than `y`, otherwise return false.
  224. *
  225. */
  226. P.lessThan = P.lt = function (y) {
  227. return this.cmp(y) < 0;
  228. };
  229. /*
  230. * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false.
  231. *
  232. */
  233. P.lessThanOrEqualTo = P.lte = function (y) {
  234. return this.cmp(y) < 1;
  235. };
  236. /*
  237. * Return the logarithm of the value of this Decimal to the specified base, truncated to
  238. * `precision` significant digits.
  239. *
  240. * If no base is specified, return log[10](x).
  241. *
  242. * log[base](x) = ln(x) / ln(base)
  243. *
  244. * The maximum error of the result is 1 ulp (unit in the last place).
  245. *
  246. * [base] {number|string|Decimal} The base of the logarithm.
  247. *
  248. */
  249. P.logarithm = P.log = function (base) {
  250. var r,
  251. x = this,
  252. Ctor = x.constructor,
  253. pr = Ctor.precision,
  254. wpr = pr + 5;
  255. // Default base is 10.
  256. if (base === void 0) {
  257. base = new Ctor(10);
  258. } else {
  259. base = new Ctor(base);
  260. // log[-b](x) = NaN
  261. // log[0](x) = NaN
  262. // log[1](x) = NaN
  263. if (base.s < 1 || base.eq(ONE)) throw Error(decimalError + 'NaN');
  264. }
  265. // log[b](-x) = NaN
  266. // log[b](0) = -Infinity
  267. if (x.s < 1) throw Error(decimalError + (x.s ? 'NaN' : '-Infinity'));
  268. // log[b](1) = 0
  269. if (x.eq(ONE)) return new Ctor(0);
  270. external = false;
  271. r = divide(ln(x, wpr), ln(base, wpr), wpr);
  272. external = true;
  273. return round(r, pr);
  274. };
  275. /*
  276. * Return a new Decimal whose value is the value of this Decimal minus `y`, truncated to
  277. * `precision` significant digits.
  278. *
  279. */
  280. P.minus = P.sub = function (y) {
  281. var x = this;
  282. y = new x.constructor(y);
  283. return x.s == y.s ? subtract(x, y) : add(x, (y.s = -y.s, y));
  284. };
  285. /*
  286. * Return a new Decimal whose value is the value of this Decimal modulo `y`, truncated to
  287. * `precision` significant digits.
  288. *
  289. */
  290. P.modulo = P.mod = function (y) {
  291. var q,
  292. x = this,
  293. Ctor = x.constructor,
  294. pr = Ctor.precision;
  295. y = new Ctor(y);
  296. // x % 0 = NaN
  297. if (!y.s) throw Error(decimalError + 'NaN');
  298. // Return x if x is 0.
  299. if (!x.s) return round(new Ctor(x), pr);
  300. // Prevent rounding of intermediate calculations.
  301. external = false;
  302. q = divide(x, y, 0, 1).times(y);
  303. external = true;
  304. return x.minus(q);
  305. };
  306. /*
  307. * Return a new Decimal whose value is the natural exponential of the value of this Decimal,
  308. * i.e. the base e raised to the power the value of this Decimal, truncated to `precision`
  309. * significant digits.
  310. *
  311. */
  312. P.naturalExponential = P.exp = function () {
  313. return exp(this);
  314. };
  315. /*
  316. * Return a new Decimal whose value is the natural logarithm of the value of this Decimal,
  317. * truncated to `precision` significant digits.
  318. *
  319. */
  320. P.naturalLogarithm = P.ln = function () {
  321. return ln(this);
  322. };
  323. /*
  324. * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by
  325. * -1.
  326. *
  327. */
  328. P.negated = P.neg = function () {
  329. var x = new this.constructor(this);
  330. x.s = -x.s || 0;
  331. return x;
  332. };
  333. /*
  334. * Return a new Decimal whose value is the value of this Decimal plus `y`, truncated to
  335. * `precision` significant digits.
  336. *
  337. */
  338. P.plus = P.add = function (y) {
  339. var x = this;
  340. y = new x.constructor(y);
  341. return x.s == y.s ? add(x, y) : subtract(x, (y.s = -y.s, y));
  342. };
  343. /*
  344. * Return the number of significant digits of the value of this Decimal.
  345. *
  346. * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
  347. *
  348. */
  349. P.precision = P.sd = function (z) {
  350. var e, sd, w,
  351. x = this;
  352. if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z);
  353. e = getBase10Exponent(x) + 1;
  354. w = x.d.length - 1;
  355. sd = w * LOG_BASE + 1;
  356. w = x.d[w];
  357. // If non-zero...
  358. if (w) {
  359. // Subtract the number of trailing zeros of the last word.
  360. for (; w % 10 == 0; w /= 10) sd--;
  361. // Add the number of digits of the first word.
  362. for (w = x.d[0]; w >= 10; w /= 10) sd++;
  363. }
  364. return z && e > sd ? e : sd;
  365. };
  366. /*
  367. * Return a new Decimal whose value is the square root of this Decimal, truncated to `precision`
  368. * significant digits.
  369. *
  370. */
  371. P.squareRoot = P.sqrt = function () {
  372. var e, n, pr, r, s, t, wpr,
  373. x = this,
  374. Ctor = x.constructor;
  375. // Negative or zero?
  376. if (x.s < 1) {
  377. if (!x.s) return new Ctor(0);
  378. // sqrt(-x) = NaN
  379. throw Error(decimalError + 'NaN');
  380. }
  381. e = getBase10Exponent(x);
  382. external = false;
  383. // Initial estimate.
  384. s = Math.sqrt(+x);
  385. // Math.sqrt underflow/overflow?
  386. // Pass x to Math.sqrt as integer, then adjust the exponent of the result.
  387. if (s == 0 || s == 1 / 0) {
  388. n = digitsToString(x.d);
  389. if ((n.length + e) % 2 == 0) n += '0';
  390. s = Math.sqrt(n);
  391. e = mathfloor((e + 1) / 2) - (e < 0 || e % 2);
  392. if (s == 1 / 0) {
  393. n = '5e' + e;
  394. } else {
  395. n = s.toExponential();
  396. n = n.slice(0, n.indexOf('e') + 1) + e;
  397. }
  398. r = new Ctor(n);
  399. } else {
  400. r = new Ctor(s.toString());
  401. }
  402. pr = Ctor.precision;
  403. s = wpr = pr + 3;
  404. // Newton-Raphson iteration.
  405. for (;;) {
  406. t = r;
  407. r = t.plus(divide(x, t, wpr + 2)).times(0.5);
  408. if (digitsToString(t.d).slice(0, wpr) === (n = digitsToString(r.d)).slice(0, wpr)) {
  409. n = n.slice(wpr - 3, wpr + 1);
  410. // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or
  411. // 4999, i.e. approaching a rounding boundary, continue the iteration.
  412. if (s == wpr && n == '4999') {
  413. // On the first iteration only, check to see if rounding up gives the exact result as the
  414. // nines may infinitely repeat.
  415. round(t, pr + 1, 0);
  416. if (t.times(t).eq(x)) {
  417. r = t;
  418. break;
  419. }
  420. } else if (n != '9999') {
  421. break;
  422. }
  423. wpr += 4;
  424. }
  425. }
  426. external = true;
  427. return round(r, pr);
  428. };
  429. /*
  430. * Return a new Decimal whose value is the value of this Decimal times `y`, truncated to
  431. * `precision` significant digits.
  432. *
  433. */
  434. P.times = P.mul = function (y) {
  435. var carry, e, i, k, r, rL, t, xdL, ydL,
  436. x = this,
  437. Ctor = x.constructor,
  438. xd = x.d,
  439. yd = (y = new Ctor(y)).d;
  440. // Return 0 if either is 0.
  441. if (!x.s || !y.s) return new Ctor(0);
  442. y.s *= x.s;
  443. e = x.e + y.e;
  444. xdL = xd.length;
  445. ydL = yd.length;
  446. // Ensure xd points to the longer array.
  447. if (xdL < ydL) {
  448. r = xd;
  449. xd = yd;
  450. yd = r;
  451. rL = xdL;
  452. xdL = ydL;
  453. ydL = rL;
  454. }
  455. // Initialise the result array with zeros.
  456. r = [];
  457. rL = xdL + ydL;
  458. for (i = rL; i--;) r.push(0);
  459. // Multiply!
  460. for (i = ydL; --i >= 0;) {
  461. carry = 0;
  462. for (k = xdL + i; k > i;) {
  463. t = r[k] + yd[i] * xd[k - i - 1] + carry;
  464. r[k--] = t % BASE | 0;
  465. carry = t / BASE | 0;
  466. }
  467. r[k] = (r[k] + carry) % BASE | 0;
  468. }
  469. // Remove trailing zeros.
  470. for (; !r[--rL];) r.pop();
  471. if (carry) ++e;
  472. else r.shift();
  473. y.d = r;
  474. y.e = e;
  475. return external ? round(y, Ctor.precision) : y;
  476. };
  477. /*
  478. * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp`
  479. * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted.
  480. *
  481. * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal.
  482. *
  483. * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
  484. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  485. *
  486. */
  487. P.toDecimalPlaces = P.todp = function (dp, rm) {
  488. var x = this,
  489. Ctor = x.constructor;
  490. x = new Ctor(x);
  491. if (dp === void 0) return x;
  492. checkInt32(dp, 0, MAX_DIGITS);
  493. if (rm === void 0) rm = Ctor.rounding;
  494. else checkInt32(rm, 0, 8);
  495. return round(x, dp + getBase10Exponent(x) + 1, rm);
  496. };
  497. /*
  498. * Return a string representing the value of this Decimal in exponential notation rounded to
  499. * `dp` fixed decimal places using rounding mode `rounding`.
  500. *
  501. * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
  502. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  503. *
  504. */
  505. P.toExponential = function (dp, rm) {
  506. var str,
  507. x = this,
  508. Ctor = x.constructor;
  509. if (dp === void 0) {
  510. str = toString(x, true);
  511. } else {
  512. checkInt32(dp, 0, MAX_DIGITS);
  513. if (rm === void 0) rm = Ctor.rounding;
  514. else checkInt32(rm, 0, 8);
  515. x = round(new Ctor(x), dp + 1, rm);
  516. str = toString(x, true, dp + 1);
  517. }
  518. return str;
  519. };
  520. /*
  521. * Return a string representing the value of this Decimal in normal (fixed-point) notation to
  522. * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is
  523. * omitted.
  524. *
  525. * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'.
  526. *
  527. * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
  528. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  529. *
  530. * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'.
  531. * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'.
  532. * (-0).toFixed(3) is '0.000'.
  533. * (-0.5).toFixed(0) is '-0'.
  534. *
  535. */
  536. P.toFixed = function (dp, rm) {
  537. var str, y,
  538. x = this,
  539. Ctor = x.constructor;
  540. if (dp === void 0) return toString(x);
  541. checkInt32(dp, 0, MAX_DIGITS);
  542. if (rm === void 0) rm = Ctor.rounding;
  543. else checkInt32(rm, 0, 8);
  544. y = round(new Ctor(x), dp + getBase10Exponent(x) + 1, rm);
  545. str = toString(y.abs(), false, dp + getBase10Exponent(y) + 1);
  546. // To determine whether to add the minus sign look at the value before it was rounded,
  547. // i.e. look at `x` rather than `y`.
  548. return x.isneg() && !x.isZero() ? '-' + str : str;
  549. };
  550. /*
  551. * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using
  552. * rounding mode `rounding`.
  553. *
  554. */
  555. P.toInteger = P.toint = function () {
  556. var x = this,
  557. Ctor = x.constructor;
  558. return round(new Ctor(x), getBase10Exponent(x) + 1, Ctor.rounding);
  559. };
  560. /*
  561. * Return the value of this Decimal converted to a number primitive.
  562. *
  563. */
  564. P.toNumber = function () {
  565. return +this;
  566. };
  567. /*
  568. * Return a new Decimal whose value is the value of this Decimal raised to the power `y`,
  569. * truncated to `precision` significant digits.
  570. *
  571. * For non-integer or very large exponents pow(x, y) is calculated using
  572. *
  573. * x^y = exp(y*ln(x))
  574. *
  575. * The maximum error is 1 ulp (unit in last place).
  576. *
  577. * y {number|string|Decimal} The power to which to raise this Decimal.
  578. *
  579. */
  580. P.toPower = P.pow = function (y) {
  581. var e, k, pr, r, sign, yIsInt,
  582. x = this,
  583. Ctor = x.constructor,
  584. guard = 12,
  585. yn = +(y = new Ctor(y));
  586. // pow(x, 0) = 1
  587. if (!y.s) return new Ctor(ONE);
  588. x = new Ctor(x);
  589. // pow(0, y > 0) = 0
  590. // pow(0, y < 0) = Infinity
  591. if (!x.s) {
  592. if (y.s < 1) throw Error(decimalError + 'Infinity');
  593. return x;
  594. }
  595. // pow(1, y) = 1
  596. if (x.eq(ONE)) return x;
  597. pr = Ctor.precision;
  598. // pow(x, 1) = x
  599. if (y.eq(ONE)) return round(x, pr);
  600. e = y.e;
  601. k = y.d.length - 1;
  602. yIsInt = e >= k;
  603. sign = x.s;
  604. if (!yIsInt) {
  605. // pow(x < 0, y non-integer) = NaN
  606. if (sign < 0) throw Error(decimalError + 'NaN');
  607. // If y is a small integer use the 'exponentiation by squaring' algorithm.
  608. } else if ((k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) {
  609. r = new Ctor(ONE);
  610. // Max k of 9007199254740991 takes 53 loop iterations.
  611. // Maximum digits array length; leaves [28, 34] guard digits.
  612. e = Math.ceil(pr / LOG_BASE + 4);
  613. external = false;
  614. for (;;) {
  615. if (k % 2) {
  616. r = r.times(x);
  617. truncate(r.d, e);
  618. }
  619. k = mathfloor(k / 2);
  620. if (k === 0) break;
  621. x = x.times(x);
  622. truncate(x.d, e);
  623. }
  624. external = true;
  625. return y.s < 0 ? new Ctor(ONE).div(r) : round(r, pr);
  626. }
  627. // Result is negative if x is negative and the last digit of integer y is odd.
  628. sign = sign < 0 && y.d[Math.max(e, k)] & 1 ? -1 : 1;
  629. x.s = 1;
  630. external = false;
  631. r = y.times(ln(x, pr + guard));
  632. external = true;
  633. r = exp(r);
  634. r.s = sign;
  635. return r;
  636. };
  637. /*
  638. * Return a string representing the value of this Decimal rounded to `sd` significant digits
  639. * using rounding mode `rounding`.
  640. *
  641. * Return exponential notation if `sd` is less than the number of digits necessary to represent
  642. * the integer part of the value in normal notation.
  643. *
  644. * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
  645. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  646. *
  647. */
  648. P.toPrecision = function (sd, rm) {
  649. var e, str,
  650. x = this,
  651. Ctor = x.constructor;
  652. if (sd === void 0) {
  653. e = getBase10Exponent(x);
  654. str = toString(x, e <= Ctor.toExpNeg || e >= Ctor.toExpPos);
  655. } else {
  656. checkInt32(sd, 1, MAX_DIGITS);
  657. if (rm === void 0) rm = Ctor.rounding;
  658. else checkInt32(rm, 0, 8);
  659. x = round(new Ctor(x), sd, rm);
  660. e = getBase10Exponent(x);
  661. str = toString(x, sd <= e || e <= Ctor.toExpNeg, sd);
  662. }
  663. return str;
  664. };
  665. /*
  666. * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd`
  667. * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if
  668. * omitted.
  669. *
  670. * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
  671. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  672. *
  673. */
  674. P.toSignificantDigits = P.tosd = function (sd, rm) {
  675. var x = this,
  676. Ctor = x.constructor;
  677. if (sd === void 0) {
  678. sd = Ctor.precision;
  679. rm = Ctor.rounding;
  680. } else {
  681. checkInt32(sd, 1, MAX_DIGITS);
  682. if (rm === void 0) rm = Ctor.rounding;
  683. else checkInt32(rm, 0, 8);
  684. }
  685. return round(new Ctor(x), sd, rm);
  686. };
  687. /*
  688. * Return a string representing the value of this Decimal.
  689. *
  690. * Return exponential notation if this Decimal has a positive exponent equal to or greater than
  691. * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`.
  692. *
  693. */
  694. P.toString = P.valueOf = P.val = P.toJSON = P[Symbol.for('nodejs.util.inspect.custom')] = function () {
  695. var x = this,
  696. e = getBase10Exponent(x),
  697. Ctor = x.constructor;
  698. return toString(x, e <= Ctor.toExpNeg || e >= Ctor.toExpPos);
  699. };
  700. // Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers.
  701. /*
  702. * add P.minus, P.plus
  703. * checkInt32 P.todp, P.toExponential, P.toFixed, P.toPrecision, P.tosd
  704. * digitsToString P.log, P.sqrt, P.pow, toString, exp, ln
  705. * divide P.div, P.idiv, P.log, P.mod, P.sqrt, exp, ln
  706. * exp P.exp, P.pow
  707. * getBase10Exponent P.exponent, P.sd, P.toint, P.sqrt, P.todp, P.toFixed, P.toPrecision,
  708. * P.toString, divide, round, toString, exp, ln
  709. * getLn10 P.log, ln
  710. * getZeroString digitsToString, toString
  711. * ln P.log, P.ln, P.pow, exp
  712. * parseDecimal Decimal
  713. * round P.abs, P.idiv, P.log, P.minus, P.mod, P.neg, P.plus, P.toint, P.sqrt,
  714. * P.times, P.todp, P.toExponential, P.toFixed, P.pow, P.toPrecision, P.tosd,
  715. * divide, getLn10, exp, ln
  716. * subtract P.minus, P.plus
  717. * toString P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf
  718. * truncate P.pow
  719. *
  720. * Throws: P.log, P.mod, P.sd, P.sqrt, P.pow, checkInt32, divide, round,
  721. * getLn10, exp, ln, parseDecimal, Decimal, config
  722. */
  723. function add(x, y) {
  724. var carry, d, e, i, k, len, xd, yd,
  725. Ctor = x.constructor,
  726. pr = Ctor.precision;
  727. // If either is zero...
  728. if (!x.s || !y.s) {
  729. // Return x if y is zero.
  730. // Return y if y is non-zero.
  731. if (!y.s) y = new Ctor(x);
  732. return external ? round(y, pr) : y;
  733. }
  734. xd = x.d;
  735. yd = y.d;
  736. // x and y are finite, non-zero numbers with the same sign.
  737. k = x.e;
  738. e = y.e;
  739. xd = xd.slice();
  740. i = k - e;
  741. // If base 1e7 exponents differ...
  742. if (i) {
  743. if (i < 0) {
  744. d = xd;
  745. i = -i;
  746. len = yd.length;
  747. } else {
  748. d = yd;
  749. e = k;
  750. len = xd.length;
  751. }
  752. // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1.
  753. k = Math.ceil(pr / LOG_BASE);
  754. len = k > len ? k + 1 : len + 1;
  755. if (i > len) {
  756. i = len;
  757. d.length = 1;
  758. }
  759. // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts.
  760. d.reverse();
  761. for (; i--;) d.push(0);
  762. d.reverse();
  763. }
  764. len = xd.length;
  765. i = yd.length;
  766. // If yd is longer than xd, swap xd and yd so xd points to the longer array.
  767. if (len - i < 0) {
  768. i = len;
  769. d = yd;
  770. yd = xd;
  771. xd = d;
  772. }
  773. // Only start adding at yd.length - 1 as the further digits of xd can be left as they are.
  774. for (carry = 0; i;) {
  775. carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0;
  776. xd[i] %= BASE;
  777. }
  778. if (carry) {
  779. xd.unshift(carry);
  780. ++e;
  781. }
  782. // Remove trailing zeros.
  783. // No need to check for zero, as +x + +y != 0 && -x + -y != 0
  784. for (len = xd.length; xd[--len] == 0;) xd.pop();
  785. y.d = xd;
  786. y.e = e;
  787. return external ? round(y, pr) : y;
  788. }
  789. function checkInt32(i, min, max) {
  790. if (i !== ~~i || i < min || i > max) {
  791. throw Error(invalidArgument + i);
  792. }
  793. }
  794. function digitsToString(d) {
  795. var i, k, ws,
  796. indexOfLastWord = d.length - 1,
  797. str = '',
  798. w = d[0];
  799. if (indexOfLastWord > 0) {
  800. str += w;
  801. for (i = 1; i < indexOfLastWord; i++) {
  802. ws = d[i] + '';
  803. k = LOG_BASE - ws.length;
  804. if (k) str += getZeroString(k);
  805. str += ws;
  806. }
  807. w = d[i];
  808. ws = w + '';
  809. k = LOG_BASE - ws.length;
  810. if (k) str += getZeroString(k);
  811. } else if (w === 0) {
  812. return '0';
  813. }
  814. // Remove trailing zeros of last w.
  815. for (; w % 10 === 0;) w /= 10;
  816. return str + w;
  817. }
  818. var divide = (function () {
  819. // Assumes non-zero x and k, and hence non-zero result.
  820. function multiplyInteger(x, k) {
  821. var temp,
  822. carry = 0,
  823. i = x.length;
  824. for (x = x.slice(); i--;) {
  825. temp = x[i] * k + carry;
  826. x[i] = temp % BASE | 0;
  827. carry = temp / BASE | 0;
  828. }
  829. if (carry) x.unshift(carry);
  830. return x;
  831. }
  832. function compare(a, b, aL, bL) {
  833. var i, r;
  834. if (aL != bL) {
  835. r = aL > bL ? 1 : -1;
  836. } else {
  837. for (i = r = 0; i < aL; i++) {
  838. if (a[i] != b[i]) {
  839. r = a[i] > b[i] ? 1 : -1;
  840. break;
  841. }
  842. }
  843. }
  844. return r;
  845. }
  846. function subtract(a, b, aL) {
  847. var i = 0;
  848. // Subtract b from a.
  849. for (; aL--;) {
  850. a[aL] -= i;
  851. i = a[aL] < b[aL] ? 1 : 0;
  852. a[aL] = i * BASE + a[aL] - b[aL];
  853. }
  854. // Remove leading zeros.
  855. for (; !a[0] && a.length > 1;) a.shift();
  856. }
  857. return function (x, y, pr, dp) {
  858. var cmp, e, i, k, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0, yL, yz,
  859. Ctor = x.constructor,
  860. sign = x.s == y.s ? 1 : -1,
  861. xd = x.d,
  862. yd = y.d;
  863. // Either 0?
  864. if (!x.s) return new Ctor(x);
  865. if (!y.s) throw Error(decimalError + 'Division by zero');
  866. e = x.e - y.e;
  867. yL = yd.length;
  868. xL = xd.length;
  869. q = new Ctor(sign);
  870. qd = q.d = [];
  871. // Result exponent may be one less than e.
  872. for (i = 0; yd[i] == (xd[i] || 0); ) ++i;
  873. if (yd[i] > (xd[i] || 0)) --e;
  874. if (pr == null) {
  875. sd = pr = Ctor.precision;
  876. } else if (dp) {
  877. sd = pr + (getBase10Exponent(x) - getBase10Exponent(y)) + 1;
  878. } else {
  879. sd = pr;
  880. }
  881. if (sd < 0) return new Ctor(0);
  882. // Convert precision in number of base 10 digits to base 1e7 digits.
  883. sd = sd / LOG_BASE + 2 | 0;
  884. i = 0;
  885. // divisor < 1e7
  886. if (yL == 1) {
  887. k = 0;
  888. yd = yd[0];
  889. sd++;
  890. // k is the carry.
  891. for (; (i < xL || k) && sd--; i++) {
  892. t = k * BASE + (xd[i] || 0);
  893. qd[i] = t / yd | 0;
  894. k = t % yd | 0;
  895. }
  896. // divisor >= 1e7
  897. } else {
  898. // Normalise xd and yd so highest order digit of yd is >= BASE/2
  899. k = BASE / (yd[0] + 1) | 0;
  900. if (k > 1) {
  901. yd = multiplyInteger(yd, k);
  902. xd = multiplyInteger(xd, k);
  903. yL = yd.length;
  904. xL = xd.length;
  905. }
  906. xi = yL;
  907. rem = xd.slice(0, yL);
  908. remL = rem.length;
  909. // Add zeros to make remainder as long as divisor.
  910. for (; remL < yL;) rem[remL++] = 0;
  911. yz = yd.slice();
  912. yz.unshift(0);
  913. yd0 = yd[0];
  914. if (yd[1] >= BASE / 2) ++yd0;
  915. do {
  916. k = 0;
  917. // Compare divisor and remainder.
  918. cmp = compare(yd, rem, yL, remL);
  919. // If divisor < remainder.
  920. if (cmp < 0) {
  921. // Calculate trial digit, k.
  922. rem0 = rem[0];
  923. if (yL != remL) rem0 = rem0 * BASE + (rem[1] || 0);
  924. // k will be how many times the divisor goes into the current remainder.
  925. k = rem0 / yd0 | 0;
  926. // Algorithm:
  927. // 1. product = divisor * trial digit (k)
  928. // 2. if product > remainder: product -= divisor, k--
  929. // 3. remainder -= product
  930. // 4. if product was < remainder at 2:
  931. // 5. compare new remainder and divisor
  932. // 6. If remainder > divisor: remainder -= divisor, k++
  933. if (k > 1) {
  934. if (k >= BASE) k = BASE - 1;
  935. // product = divisor * trial digit.
  936. prod = multiplyInteger(yd, k);
  937. prodL = prod.length;
  938. remL = rem.length;
  939. // Compare product and remainder.
  940. cmp = compare(prod, rem, prodL, remL);
  941. // product > remainder.
  942. if (cmp == 1) {
  943. k--;
  944. // Subtract divisor from product.
  945. subtract(prod, yL < prodL ? yz : yd, prodL);
  946. }
  947. } else {
  948. // cmp is -1.
  949. // If k is 0, there is no need to compare yd and rem again below, so change cmp to 1
  950. // to avoid it. If k is 1 there is a need to compare yd and rem again below.
  951. if (k == 0) cmp = k = 1;
  952. prod = yd.slice();
  953. }
  954. prodL = prod.length;
  955. if (prodL < remL) prod.unshift(0);
  956. // Subtract product from remainder.
  957. subtract(rem, prod, remL);
  958. // If product was < previous remainder.
  959. if (cmp == -1) {
  960. remL = rem.length;
  961. // Compare divisor and new remainder.
  962. cmp = compare(yd, rem, yL, remL);
  963. // If divisor < new remainder, subtract divisor from remainder.
  964. if (cmp < 1) {
  965. k++;
  966. // Subtract divisor from remainder.
  967. subtract(rem, yL < remL ? yz : yd, remL);
  968. }
  969. }
  970. remL = rem.length;
  971. } else if (cmp === 0) {
  972. k++;
  973. rem = [0];
  974. } // if cmp === 1, k will be 0
  975. // Add the next digit, k, to the result array.
  976. qd[i++] = k;
  977. // Update the remainder.
  978. if (cmp && rem[0]) {
  979. rem[remL++] = xd[xi] || 0;
  980. } else {
  981. rem = [xd[xi]];
  982. remL = 1;
  983. }
  984. } while ((xi++ < xL || rem[0] !== void 0) && sd--);
  985. }
  986. // Leading zero?
  987. if (!qd[0]) qd.shift();
  988. q.e = e;
  989. return round(q, dp ? pr + getBase10Exponent(q) + 1 : pr);
  990. };
  991. })();
  992. /*
  993. * Return a new Decimal whose value is the natural exponential of `x` truncated to `sd`
  994. * significant digits.
  995. *
  996. * Taylor/Maclaurin series.
  997. *
  998. * exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ...
  999. *
  1000. * Argument reduction:
  1001. * Repeat x = x / 32, k += 5, until |x| < 0.1
  1002. * exp(x) = exp(x / 2^k)^(2^k)
  1003. *
  1004. * Previously, the argument was initially reduced by
  1005. * exp(x) = exp(r) * 10^k where r = x - k * ln10, k = floor(x / ln10)
  1006. * to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was
  1007. * found to be slower than just dividing repeatedly by 32 as above.
  1008. *
  1009. * (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324)
  1010. *
  1011. * exp(x) is non-terminating for any finite, non-zero x.
  1012. *
  1013. */
  1014. function exp(x, sd) {
  1015. var denominator, guard, pow, sum, t, wpr,
  1016. i = 0,
  1017. k = 0,
  1018. Ctor = x.constructor,
  1019. pr = Ctor.precision;
  1020. if (getBase10Exponent(x) > 16) throw Error(exponentOutOfRange + getBase10Exponent(x));
  1021. // exp(0) = 1
  1022. if (!x.s) return new Ctor(ONE);
  1023. if (sd == null) {
  1024. external = false;
  1025. wpr = pr;
  1026. } else {
  1027. wpr = sd;
  1028. }
  1029. t = new Ctor(0.03125);
  1030. while (x.abs().gte(0.1)) {
  1031. x = x.times(t); // x = x / 2^5
  1032. k += 5;
  1033. }
  1034. // Estimate the precision increase necessary to ensure the first 4 rounding digits are correct.
  1035. guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0;
  1036. wpr += guard;
  1037. denominator = pow = sum = new Ctor(ONE);
  1038. Ctor.precision = wpr;
  1039. for (;;) {
  1040. pow = round(pow.times(x), wpr);
  1041. denominator = denominator.times(++i);
  1042. t = sum.plus(divide(pow, denominator, wpr));
  1043. if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
  1044. while (k--) sum = round(sum.times(sum), wpr);
  1045. Ctor.precision = pr;
  1046. return sd == null ? (external = true, round(sum, pr)) : sum;
  1047. }
  1048. sum = t;
  1049. }
  1050. }
  1051. // Calculate the base 10 exponent from the base 1e7 exponent.
  1052. function getBase10Exponent(x) {
  1053. var e = x.e * LOG_BASE,
  1054. w = x.d[0];
  1055. // Add the number of digits of the first word of the digits array.
  1056. for (; w >= 10; w /= 10) e++;
  1057. return e;
  1058. }
  1059. function getLn10(Ctor, sd, pr) {
  1060. if (sd > Ctor.LN10.sd()) {
  1061. // Reset global state in case the exception is caught.
  1062. external = true;
  1063. if (pr) Ctor.precision = pr;
  1064. throw Error(decimalError + 'LN10 precision limit exceeded');
  1065. }
  1066. return round(new Ctor(Ctor.LN10), sd);
  1067. }
  1068. function getZeroString(k) {
  1069. var zs = '';
  1070. for (; k--;) zs += '0';
  1071. return zs;
  1072. }
  1073. /*
  1074. * Return a new Decimal whose value is the natural logarithm of `x` truncated to `sd` significant
  1075. * digits.
  1076. *
  1077. * ln(n) is non-terminating (n != 1)
  1078. *
  1079. */
  1080. function ln(y, sd) {
  1081. var c, c0, denominator, e, numerator, sum, t, wpr, x2,
  1082. n = 1,
  1083. guard = 10,
  1084. x = y,
  1085. xd = x.d,
  1086. Ctor = x.constructor,
  1087. pr = Ctor.precision;
  1088. // ln(-x) = NaN
  1089. // ln(0) = -Infinity
  1090. if (x.s < 1) throw Error(decimalError + (x.s ? 'NaN' : '-Infinity'));
  1091. // ln(1) = 0
  1092. if (x.eq(ONE)) return new Ctor(0);
  1093. if (sd == null) {
  1094. external = false;
  1095. wpr = pr;
  1096. } else {
  1097. wpr = sd;
  1098. }
  1099. if (x.eq(10)) {
  1100. if (sd == null) external = true;
  1101. return getLn10(Ctor, wpr);
  1102. }
  1103. wpr += guard;
  1104. Ctor.precision = wpr;
  1105. c = digitsToString(xd);
  1106. c0 = c.charAt(0);
  1107. e = getBase10Exponent(x);
  1108. if (Math.abs(e) < 1.5e15) {
  1109. // Argument reduction.
  1110. // The series converges faster the closer the argument is to 1, so using
  1111. // ln(a^b) = b * ln(a), ln(a) = ln(a^b) / b
  1112. // multiply the argument by itself until the leading digits of the significand are 7, 8, 9,
  1113. // 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can
  1114. // later be divided by this number, then separate out the power of 10 using
  1115. // ln(a*10^b) = ln(a) + b*ln(10).
  1116. // max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14).
  1117. //while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) {
  1118. // max n is 6 (gives 0.7 - 1.3)
  1119. while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) {
  1120. x = x.times(y);
  1121. c = digitsToString(x.d);
  1122. c0 = c.charAt(0);
  1123. n++;
  1124. }
  1125. e = getBase10Exponent(x);
  1126. if (c0 > 1) {
  1127. x = new Ctor('0.' + c);
  1128. e++;
  1129. } else {
  1130. x = new Ctor(c0 + '.' + c.slice(1));
  1131. }
  1132. } else {
  1133. // The argument reduction method above may result in overflow if the argument y is a massive
  1134. // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this
  1135. // function using ln(x*10^e) = ln(x) + e*ln(10).
  1136. t = getLn10(Ctor, wpr + 2, pr).times(e + '');
  1137. x = ln(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t);
  1138. Ctor.precision = pr;
  1139. return sd == null ? (external = true, round(x, pr)) : x;
  1140. }
  1141. // x is reduced to a value near 1.
  1142. // Taylor series.
  1143. // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...)
  1144. // where x = (y - 1)/(y + 1) (|x| < 1)
  1145. sum = numerator = x = divide(x.minus(ONE), x.plus(ONE), wpr);
  1146. x2 = round(x.times(x), wpr);
  1147. denominator = 3;
  1148. for (;;) {
  1149. numerator = round(numerator.times(x2), wpr);
  1150. t = sum.plus(divide(numerator, new Ctor(denominator), wpr));
  1151. if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
  1152. sum = sum.times(2);
  1153. // Reverse the argument reduction.
  1154. if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + ''));
  1155. sum = divide(sum, new Ctor(n), wpr);
  1156. Ctor.precision = pr;
  1157. return sd == null ? (external = true, round(sum, pr)) : sum;
  1158. }
  1159. sum = t;
  1160. denominator += 2;
  1161. }
  1162. }
  1163. /*
  1164. * Parse the value of a new Decimal `x` from string `str`.
  1165. */
  1166. function parseDecimal(x, str) {
  1167. var e, i, len;
  1168. // Decimal point?
  1169. if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');
  1170. // Exponential form?
  1171. if ((i = str.search(/e/i)) > 0) {
  1172. // Determine exponent.
  1173. if (e < 0) e = i;
  1174. e += +str.slice(i + 1);
  1175. str = str.substring(0, i);
  1176. } else if (e < 0) {
  1177. // Integer.
  1178. e = str.length;
  1179. }
  1180. // Determine leading zeros.
  1181. for (i = 0; str.charCodeAt(i) === 48;) ++i;
  1182. // Determine trailing zeros.
  1183. for (len = str.length; str.charCodeAt(len - 1) === 48;) --len;
  1184. str = str.slice(i, len);
  1185. if (str) {
  1186. len -= i;
  1187. e = e - i - 1;
  1188. x.e = mathfloor(e / LOG_BASE);
  1189. x.d = [];
  1190. // Transform base
  1191. // e is the base 10 exponent.
  1192. // i is where to slice str to get the first word of the digits array.
  1193. i = (e + 1) % LOG_BASE;
  1194. if (e < 0) i += LOG_BASE;
  1195. if (i < len) {
  1196. if (i) x.d.push(+str.slice(0, i));
  1197. for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE));
  1198. str = str.slice(i);
  1199. i = LOG_BASE - str.length;
  1200. } else {
  1201. i -= len;
  1202. }
  1203. for (; i--;) str += '0';
  1204. x.d.push(+str);
  1205. if (external && (x.e > MAX_E || x.e < -MAX_E)) throw Error(exponentOutOfRange + e);
  1206. } else {
  1207. // Zero.
  1208. x.s = 0;
  1209. x.e = 0;
  1210. x.d = [0];
  1211. }
  1212. return x;
  1213. }
  1214. /*
  1215. * Round `x` to `sd` significant digits, using rounding mode `rm` if present (truncate otherwise).
  1216. */
  1217. function round(x, sd, rm) {
  1218. var i, j, k, n, rd, doRound, w, xdi,
  1219. xd = x.d;
  1220. // rd: the rounding digit, i.e. the digit after the digit that may be rounded up.
  1221. // w: the word of xd which contains the rounding digit, a base 1e7 number.
  1222. // xdi: the index of w within xd.
  1223. // n: the number of digits of w.
  1224. // i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if
  1225. // they had leading zeros)
  1226. // j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero).
  1227. // Get the length of the first word of the digits array xd.
  1228. for (n = 1, k = xd[0]; k >= 10; k /= 10) n++;
  1229. i = sd - n;
  1230. // Is the rounding digit in the first word of xd?
  1231. if (i < 0) {
  1232. i += LOG_BASE;
  1233. j = sd;
  1234. w = xd[xdi = 0];
  1235. } else {
  1236. xdi = Math.ceil((i + 1) / LOG_BASE);
  1237. k = xd.length;
  1238. if (xdi >= k) return x;
  1239. w = k = xd[xdi];
  1240. // Get the number of digits of w.
  1241. for (n = 1; k >= 10; k /= 10) n++;
  1242. // Get the index of rd within w.
  1243. i %= LOG_BASE;
  1244. // Get the index of rd within w, adjusted for leading zeros.
  1245. // The number of leading zeros of w is given by LOG_BASE - n.
  1246. j = i - LOG_BASE + n;
  1247. }
  1248. if (rm !== void 0) {
  1249. k = mathpow(10, n - j - 1);
  1250. // Get the rounding digit at index j of w.
  1251. rd = w / k % 10 | 0;
  1252. // Are there any non-zero digits after the rounding digit?
  1253. doRound = sd < 0 || xd[xdi + 1] !== void 0 || w % k;
  1254. // The expression `w % mathpow(10, n - j - 1)` returns all the digits of w to the right of the
  1255. // digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression will give
  1256. // 714.
  1257. doRound = rm < 4
  1258. ? (rd || doRound) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))
  1259. : rd > 5 || rd == 5 && (rm == 4 || doRound || rm == 6 &&
  1260. // Check whether the digit to the left of the rounding digit is odd.
  1261. ((i > 0 ? j > 0 ? w / mathpow(10, n - j) : 0 : xd[xdi - 1]) % 10) & 1 ||
  1262. rm == (x.s < 0 ? 8 : 7));
  1263. }
  1264. if (sd < 1 || !xd[0]) {
  1265. if (doRound) {
  1266. k = getBase10Exponent(x);
  1267. xd.length = 1;
  1268. // Convert sd to decimal places.
  1269. sd = sd - k - 1;
  1270. // 1, 0.1, 0.01, 0.001, 0.0001 etc.
  1271. xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE);
  1272. x.e = mathfloor(-sd / LOG_BASE) || 0;
  1273. } else {
  1274. xd.length = 1;
  1275. // Zero.
  1276. xd[0] = x.e = x.s = 0;
  1277. }
  1278. return x;
  1279. }
  1280. // Remove excess digits.
  1281. if (i == 0) {
  1282. xd.length = xdi;
  1283. k = 1;
  1284. xdi--;
  1285. } else {
  1286. xd.length = xdi + 1;
  1287. k = mathpow(10, LOG_BASE - i);
  1288. // E.g. 56700 becomes 56000 if 7 is the rounding digit.
  1289. // j > 0 means i > number of leading zeros of w.
  1290. xd[xdi] = j > 0 ? (w / mathpow(10, n - j) % mathpow(10, j) | 0) * k : 0;
  1291. }
  1292. if (doRound) {
  1293. for (;;) {
  1294. // Is the digit to be rounded up in the first word of xd?
  1295. if (xdi == 0) {
  1296. if ((xd[0] += k) == BASE) {
  1297. xd[0] = 1;
  1298. ++x.e;
  1299. }
  1300. break;
  1301. } else {
  1302. xd[xdi] += k;
  1303. if (xd[xdi] != BASE) break;
  1304. xd[xdi--] = 0;
  1305. k = 1;
  1306. }
  1307. }
  1308. }
  1309. // Remove trailing zeros.
  1310. for (i = xd.length; xd[--i] === 0;) xd.pop();
  1311. if (external && (x.e > MAX_E || x.e < -MAX_E)) {
  1312. throw Error(exponentOutOfRange + getBase10Exponent(x));
  1313. }
  1314. return x;
  1315. }
  1316. function subtract(x, y) {
  1317. var d, e, i, j, k, len, xd, xe, xLTy, yd,
  1318. Ctor = x.constructor,
  1319. pr = Ctor.precision;
  1320. // Return y negated if x is zero.
  1321. // Return x if y is zero and x is non-zero.
  1322. if (!x.s || !y.s) {
  1323. if (y.s) y.s = -y.s;
  1324. else y = new Ctor(x);
  1325. return external ? round(y, pr) : y;
  1326. }
  1327. xd = x.d;
  1328. yd = y.d;
  1329. // x and y are non-zero numbers with the same sign.
  1330. e = y.e;
  1331. xe = x.e;
  1332. xd = xd.slice();
  1333. k = xe - e;
  1334. // If exponents differ...
  1335. if (k) {
  1336. xLTy = k < 0;
  1337. if (xLTy) {
  1338. d = xd;
  1339. k = -k;
  1340. len = yd.length;
  1341. } else {
  1342. d = yd;
  1343. e = xe;
  1344. len = xd.length;
  1345. }
  1346. // Numbers with massively different exponents would result in a very high number of zeros
  1347. // needing to be prepended, but this can be avoided while still ensuring correct rounding by
  1348. // limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`.
  1349. i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2;
  1350. if (k > i) {
  1351. k = i;
  1352. d.length = 1;
  1353. }
  1354. // Prepend zeros to equalise exponents.
  1355. d.reverse();
  1356. for (i = k; i--;) d.push(0);
  1357. d.reverse();
  1358. // Base 1e7 exponents equal.
  1359. } else {
  1360. // Check digits to determine which is the bigger number.
  1361. i = xd.length;
  1362. len = yd.length;
  1363. xLTy = i < len;
  1364. if (xLTy) len = i;
  1365. for (i = 0; i < len; i++) {
  1366. if (xd[i] != yd[i]) {
  1367. xLTy = xd[i] < yd[i];
  1368. break;
  1369. }
  1370. }
  1371. k = 0;
  1372. }
  1373. if (xLTy) {
  1374. d = xd;
  1375. xd = yd;
  1376. yd = d;
  1377. y.s = -y.s;
  1378. }
  1379. len = xd.length;
  1380. // Append zeros to xd if shorter.
  1381. // Don't add zeros to yd if shorter as subtraction only needs to start at yd length.
  1382. for (i = yd.length - len; i > 0; --i) xd[len++] = 0;
  1383. // Subtract yd from xd.
  1384. for (i = yd.length; i > k;) {
  1385. if (xd[--i] < yd[i]) {
  1386. for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1;
  1387. --xd[j];
  1388. xd[i] += BASE;
  1389. }
  1390. xd[i] -= yd[i];
  1391. }
  1392. // Remove trailing zeros.
  1393. for (; xd[--len] === 0;) xd.pop();
  1394. // Remove leading zeros and adjust exponent accordingly.
  1395. for (; xd[0] === 0; xd.shift()) --e;
  1396. // Zero?
  1397. if (!xd[0]) return new Ctor(0);
  1398. y.d = xd;
  1399. y.e = e;
  1400. //return external && xd.length >= pr / LOG_BASE ? round(y, pr) : y;
  1401. return external ? round(y, pr) : y;
  1402. }
  1403. function toString(x, isExp, sd) {
  1404. var k,
  1405. e = getBase10Exponent(x),
  1406. str = digitsToString(x.d),
  1407. len = str.length;
  1408. if (isExp) {
  1409. if (sd && (k = sd - len) > 0) {
  1410. str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k);
  1411. } else if (len > 1) {
  1412. str = str.charAt(0) + '.' + str.slice(1);
  1413. }
  1414. str = str + (e < 0 ? 'e' : 'e+') + e;
  1415. } else if (e < 0) {
  1416. str = '0.' + getZeroString(-e - 1) + str;
  1417. if (sd && (k = sd - len) > 0) str += getZeroString(k);
  1418. } else if (e >= len) {
  1419. str += getZeroString(e + 1 - len);
  1420. if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k);
  1421. } else {
  1422. if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k);
  1423. if (sd && (k = sd - len) > 0) {
  1424. if (e + 1 === len) str += '.';
  1425. str += getZeroString(k);
  1426. }
  1427. }
  1428. return x.s < 0 ? '-' + str : str;
  1429. }
  1430. // Does not strip trailing zeros.
  1431. function truncate(arr, len) {
  1432. if (arr.length > len) {
  1433. arr.length = len;
  1434. return true;
  1435. }
  1436. }
  1437. // Decimal methods
  1438. /*
  1439. * clone
  1440. * config/set
  1441. */
  1442. /*
  1443. * Create and return a Decimal constructor with the same configuration properties as this Decimal
  1444. * constructor.
  1445. *
  1446. */
  1447. function clone(obj) {
  1448. var i, p, ps;
  1449. /*
  1450. * The Decimal constructor and exported function.
  1451. * Return a new Decimal instance.
  1452. *
  1453. * value {number|string|Decimal} A numeric value.
  1454. *
  1455. */
  1456. function Decimal(value) {
  1457. var x = this;
  1458. // Decimal called without new.
  1459. if (!(x instanceof Decimal)) return new Decimal(value);
  1460. // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor
  1461. // which points to Object.
  1462. x.constructor = Decimal;
  1463. // Duplicate.
  1464. if (value instanceof Decimal) {
  1465. x.s = value.s;
  1466. x.e = value.e;
  1467. x.d = (value = value.d) ? value.slice() : value;
  1468. return;
  1469. }
  1470. if (typeof value === 'number') {
  1471. // Reject Infinity/NaN.
  1472. if (value * 0 !== 0) {
  1473. throw Error(invalidArgument + value);
  1474. }
  1475. if (value > 0) {
  1476. x.s = 1;
  1477. } else if (value < 0) {
  1478. value = -value;
  1479. x.s = -1;
  1480. } else {
  1481. x.s = 0;
  1482. x.e = 0;
  1483. x.d = [0];
  1484. return;
  1485. }
  1486. // Fast path for small integers.
  1487. if (value === ~~value && value < 1e7) {
  1488. x.e = 0;
  1489. x.d = [value];
  1490. return;
  1491. }
  1492. return parseDecimal(x, value.toString());
  1493. } else if (typeof value !== 'string') {
  1494. throw Error(invalidArgument + value);
  1495. }
  1496. // Minus sign?
  1497. if (value.charCodeAt(0) === 45) {
  1498. value = value.slice(1);
  1499. x.s = -1;
  1500. } else {
  1501. x.s = 1;
  1502. }
  1503. if (isDecimal.test(value)) parseDecimal(x, value);
  1504. else throw Error(invalidArgument + value);
  1505. }
  1506. Decimal.prototype = P;
  1507. Decimal.ROUND_UP = 0;
  1508. Decimal.ROUND_DOWN = 1;
  1509. Decimal.ROUND_CEIL = 2;
  1510. Decimal.ROUND_FLOOR = 3;
  1511. Decimal.ROUND_HALF_UP = 4;
  1512. Decimal.ROUND_HALF_DOWN = 5;
  1513. Decimal.ROUND_HALF_EVEN = 6;
  1514. Decimal.ROUND_HALF_CEIL = 7;
  1515. Decimal.ROUND_HALF_FLOOR = 8;
  1516. Decimal.clone = clone;
  1517. Decimal.config = Decimal.set = config;
  1518. if (obj === void 0) obj = {};
  1519. if (obj) {
  1520. ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'LN10'];
  1521. for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p];
  1522. }
  1523. Decimal.config(obj);
  1524. return Decimal;
  1525. }
  1526. /*
  1527. * Configure global settings for a Decimal constructor.
  1528. *
  1529. * `obj` is an object with one or more of the following properties,
  1530. *
  1531. * precision {number}
  1532. * rounding {number}
  1533. * toExpNeg {number}
  1534. * toExpPos {number}
  1535. *
  1536. * E.g. Decimal.config({ precision: 20, rounding: 4 })
  1537. *
  1538. */
  1539. function config(obj) {
  1540. if (!obj || typeof obj !== 'object') {
  1541. throw Error(decimalError + 'Object expected');
  1542. }
  1543. var i, p, v,
  1544. ps = [
  1545. 'precision', 1, MAX_DIGITS,
  1546. 'rounding', 0, 8,
  1547. 'toExpNeg', -1 / 0, 0,
  1548. 'toExpPos', 0, 1 / 0
  1549. ];
  1550. for (i = 0; i < ps.length; i += 3) {
  1551. if ((v = obj[p = ps[i]]) !== void 0) {
  1552. if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v;
  1553. else throw Error(invalidArgument + p + ': ' + v);
  1554. }
  1555. }
  1556. if ((v = obj[p = 'LN10']) !== void 0) {
  1557. if (v == Math.LN10) this[p] = new this(v);
  1558. else throw Error(invalidArgument + p + ': ' + v);
  1559. }
  1560. return this;
  1561. }
  1562. // Create and configure initial Decimal constructor.
  1563. export var Decimal = clone(defaults);
  1564. // Internal constant.
  1565. ONE = new Decimal(1);
  1566. export default Decimal;