You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4841 lines
123 KiB

  1. /*
  2. * decimal.js v10.2.1
  3. * An arbitrary-precision Decimal type for JavaScript.
  4. * https://github.com/MikeMcl/decimal.js
  5. * Copyright (c) 2020 Michael Mclaughlin <M8ch88l@gmail.com>
  6. * MIT Licence
  7. */
  8. // ----------------------------------- EDITABLE DEFAULTS ------------------------------------ //
  9. // The maximum exponent magnitude.
  10. // The limit on the value of `toExpNeg`, `toExpPos`, `minE` and `maxE`.
  11. var EXP_LIMIT = 9e15, // 0 to 9e15
  12. // The limit on the value of `precision`, and on the value of the first argument to
  13. // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`.
  14. MAX_DIGITS = 1e9, // 0 to 1e9
  15. // Base conversion alphabet.
  16. NUMERALS = '0123456789abcdef',
  17. // The natural logarithm of 10 (1025 digits).
  18. LN10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058',
  19. // Pi (1025 digits).
  20. PI = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789',
  21. // The initial configuration properties of the Decimal constructor.
  22. DEFAULTS = {
  23. // These values must be integers within the stated ranges (inclusive).
  24. // Most of these values can be changed at run-time using the `Decimal.config` method.
  25. // The maximum number of significant digits of the result of a calculation or base conversion.
  26. // E.g. `Decimal.config({ precision: 20 });`
  27. precision: 20, // 1 to MAX_DIGITS
  28. // The rounding mode used when rounding to `precision`.
  29. //
  30. // ROUND_UP 0 Away from zero.
  31. // ROUND_DOWN 1 Towards zero.
  32. // ROUND_CEIL 2 Towards +Infinity.
  33. // ROUND_FLOOR 3 Towards -Infinity.
  34. // ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up.
  35. // ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
  36. // ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
  37. // ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
  38. // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
  39. //
  40. // E.g.
  41. // `Decimal.rounding = 4;`
  42. // `Decimal.rounding = Decimal.ROUND_HALF_UP;`
  43. rounding: 4, // 0 to 8
  44. // The modulo mode used when calculating the modulus: a mod n.
  45. // The quotient (q = a / n) is calculated according to the corresponding rounding mode.
  46. // The remainder (r) is calculated as: r = a - n * q.
  47. //
  48. // UP 0 The remainder is positive if the dividend is negative, else is negative.
  49. // DOWN 1 The remainder has the same sign as the dividend (JavaScript %).
  50. // FLOOR 3 The remainder has the same sign as the divisor (Python %).
  51. // HALF_EVEN 6 The IEEE 754 remainder function.
  52. // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). Always positive.
  53. //
  54. // Truncated division (1), floored division (3), the IEEE 754 remainder (6), and Euclidian
  55. // division (9) are commonly used for the modulus operation. The other rounding modes can also
  56. // be used, but they may not give useful results.
  57. modulo: 1, // 0 to 9
  58. // The exponent value at and beneath which `toString` returns exponential notation.
  59. // JavaScript numbers: -7
  60. toExpNeg: -7, // 0 to -EXP_LIMIT
  61. // The exponent value at and above which `toString` returns exponential notation.
  62. // JavaScript numbers: 21
  63. toExpPos: 21, // 0 to EXP_LIMIT
  64. // The minimum exponent value, beneath which underflow to zero occurs.
  65. // JavaScript numbers: -324 (5e-324)
  66. minE: -EXP_LIMIT, // -1 to -EXP_LIMIT
  67. // The maximum exponent value, above which overflow to Infinity occurs.
  68. // JavaScript numbers: 308 (1.7976931348623157e+308)
  69. maxE: EXP_LIMIT, // 1 to EXP_LIMIT
  70. // Whether to use cryptographically-secure random number generation, if available.
  71. crypto: false // true/false
  72. },
  73. // ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- //
  74. inexact, quadrant,
  75. external = true,
  76. decimalError = '[DecimalError] ',
  77. invalidArgument = decimalError + 'Invalid argument: ',
  78. precisionLimitExceeded = decimalError + 'Precision limit exceeded',
  79. cryptoUnavailable = decimalError + 'crypto unavailable',
  80. mathfloor = Math.floor,
  81. mathpow = Math.pow,
  82. isBinary = /^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,
  83. isHex = /^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,
  84. isOctal = /^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,
  85. isDecimal = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
  86. BASE = 1e7,
  87. LOG_BASE = 7,
  88. MAX_SAFE_INTEGER = 9007199254740991,
  89. LN10_PRECISION = LN10.length - 1,
  90. PI_PRECISION = PI.length - 1,
  91. // Decimal.prototype object
  92. P = { name: '[object Decimal]' };
  93. // Decimal prototype methods
  94. /*
  95. * absoluteValue abs
  96. * ceil
  97. * comparedTo cmp
  98. * cosine cos
  99. * cubeRoot cbrt
  100. * decimalPlaces dp
  101. * dividedBy div
  102. * dividedToIntegerBy divToInt
  103. * equals eq
  104. * floor
  105. * greaterThan gt
  106. * greaterThanOrEqualTo gte
  107. * hyperbolicCosine cosh
  108. * hyperbolicSine sinh
  109. * hyperbolicTangent tanh
  110. * inverseCosine acos
  111. * inverseHyperbolicCosine acosh
  112. * inverseHyperbolicSine asinh
  113. * inverseHyperbolicTangent atanh
  114. * inverseSine asin
  115. * inverseTangent atan
  116. * isFinite
  117. * isInteger isInt
  118. * isNaN
  119. * isNegative isNeg
  120. * isPositive isPos
  121. * isZero
  122. * lessThan lt
  123. * lessThanOrEqualTo lte
  124. * logarithm log
  125. * [maximum] [max]
  126. * [minimum] [min]
  127. * minus sub
  128. * modulo mod
  129. * naturalExponential exp
  130. * naturalLogarithm ln
  131. * negated neg
  132. * plus add
  133. * precision sd
  134. * round
  135. * sine sin
  136. * squareRoot sqrt
  137. * tangent tan
  138. * times mul
  139. * toBinary
  140. * toDecimalPlaces toDP
  141. * toExponential
  142. * toFixed
  143. * toFraction
  144. * toHexadecimal toHex
  145. * toNearest
  146. * toNumber
  147. * toOctal
  148. * toPower pow
  149. * toPrecision
  150. * toSignificantDigits toSD
  151. * toString
  152. * truncated trunc
  153. * valueOf toJSON
  154. */
  155. /*
  156. * Return a new Decimal whose value is the absolute value of this Decimal.
  157. *
  158. */
  159. P.absoluteValue = P.abs = function () {
  160. var x = new this.constructor(this);
  161. if (x.s < 0) x.s = 1;
  162. return finalise(x);
  163. };
  164. /*
  165. * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the
  166. * direction of positive Infinity.
  167. *
  168. */
  169. P.ceil = function () {
  170. return finalise(new this.constructor(this), this.e + 1, 2);
  171. };
  172. /*
  173. * Return
  174. * 1 if the value of this Decimal is greater than the value of `y`,
  175. * -1 if the value of this Decimal is less than the value of `y`,
  176. * 0 if they have the same value,
  177. * NaN if the value of either Decimal is NaN.
  178. *
  179. */
  180. P.comparedTo = P.cmp = function (y) {
  181. var i, j, xdL, ydL,
  182. x = this,
  183. xd = x.d,
  184. yd = (y = new x.constructor(y)).d,
  185. xs = x.s,
  186. ys = y.s;
  187. // Either NaN or ±Infinity?
  188. if (!xd || !yd) {
  189. return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1;
  190. }
  191. // Either zero?
  192. if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0;
  193. // Signs differ?
  194. if (xs !== ys) return xs;
  195. // Compare exponents.
  196. if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1;
  197. xdL = xd.length;
  198. ydL = yd.length;
  199. // Compare digit by digit.
  200. for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) {
  201. if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1;
  202. }
  203. // Compare lengths.
  204. return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1;
  205. };
  206. /*
  207. * Return a new Decimal whose value is the cosine of the value in radians of this Decimal.
  208. *
  209. * Domain: [-Infinity, Infinity]
  210. * Range: [-1, 1]
  211. *
  212. * cos(0) = 1
  213. * cos(-0) = 1
  214. * cos(Infinity) = NaN
  215. * cos(-Infinity) = NaN
  216. * cos(NaN) = NaN
  217. *
  218. */
  219. P.cosine = P.cos = function () {
  220. var pr, rm,
  221. x = this,
  222. Ctor = x.constructor;
  223. if (!x.d) return new Ctor(NaN);
  224. // cos(0) = cos(-0) = 1
  225. if (!x.d[0]) return new Ctor(1);
  226. pr = Ctor.precision;
  227. rm = Ctor.rounding;
  228. Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;
  229. Ctor.rounding = 1;
  230. x = cosine(Ctor, toLessThanHalfPi(Ctor, x));
  231. Ctor.precision = pr;
  232. Ctor.rounding = rm;
  233. return finalise(quadrant == 2 || quadrant == 3 ? x.neg() : x, pr, rm, true);
  234. };
  235. /*
  236. *
  237. * Return a new Decimal whose value is the cube root of the value of this Decimal, rounded to
  238. * `precision` significant digits using rounding mode `rounding`.
  239. *
  240. * cbrt(0) = 0
  241. * cbrt(-0) = -0
  242. * cbrt(1) = 1
  243. * cbrt(-1) = -1
  244. * cbrt(N) = N
  245. * cbrt(-I) = -I
  246. * cbrt(I) = I
  247. *
  248. * Math.cbrt(x) = (x < 0 ? -Math.pow(-x, 1/3) : Math.pow(x, 1/3))
  249. *
  250. */
  251. P.cubeRoot = P.cbrt = function () {
  252. var e, m, n, r, rep, s, sd, t, t3, t3plusx,
  253. x = this,
  254. Ctor = x.constructor;
  255. if (!x.isFinite() || x.isZero()) return new Ctor(x);
  256. external = false;
  257. // Initial estimate.
  258. s = x.s * mathpow(x.s * x, 1 / 3);
  259. // Math.cbrt underflow/overflow?
  260. // Pass x to Math.pow as integer, then adjust the exponent of the result.
  261. if (!s || Math.abs(s) == 1 / 0) {
  262. n = digitsToString(x.d);
  263. e = x.e;
  264. // Adjust n exponent so it is a multiple of 3 away from x exponent.
  265. if (s = (e - n.length + 1) % 3) n += (s == 1 || s == -2 ? '0' : '00');
  266. s = mathpow(n, 1 / 3);
  267. // Rarely, e may be one less than the result exponent value.
  268. e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2));
  269. if (s == 1 / 0) {
  270. n = '5e' + e;
  271. } else {
  272. n = s.toExponential();
  273. n = n.slice(0, n.indexOf('e') + 1) + e;
  274. }
  275. r = new Ctor(n);
  276. r.s = x.s;
  277. } else {
  278. r = new Ctor(s.toString());
  279. }
  280. sd = (e = Ctor.precision) + 3;
  281. // Halley's method.
  282. // TODO? Compare Newton's method.
  283. for (;;) {
  284. t = r;
  285. t3 = t.times(t).times(t);
  286. t3plusx = t3.plus(x);
  287. r = divide(t3plusx.plus(x).times(t), t3plusx.plus(t3), sd + 2, 1);
  288. // TODO? Replace with for-loop and checkRoundingDigits.
  289. if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {
  290. n = n.slice(sd - 3, sd + 1);
  291. // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or 4999
  292. // , i.e. approaching a rounding boundary, continue the iteration.
  293. if (n == '9999' || !rep && n == '4999') {
  294. // On the first iteration only, check to see if rounding up gives the exact result as the
  295. // nines may infinitely repeat.
  296. if (!rep) {
  297. finalise(t, e + 1, 0);
  298. if (t.times(t).times(t).eq(x)) {
  299. r = t;
  300. break;
  301. }
  302. }
  303. sd += 4;
  304. rep = 1;
  305. } else {
  306. // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.
  307. // If not, then there are further digits and m will be truthy.
  308. if (!+n || !+n.slice(1) && n.charAt(0) == '5') {
  309. // Truncate to the first rounding digit.
  310. finalise(r, e + 1, 1);
  311. m = !r.times(r).times(r).eq(x);
  312. }
  313. break;
  314. }
  315. }
  316. }
  317. external = true;
  318. return finalise(r, e, Ctor.rounding, m);
  319. };
  320. /*
  321. * Return the number of decimal places of the value of this Decimal.
  322. *
  323. */
  324. P.decimalPlaces = P.dp = function () {
  325. var w,
  326. d = this.d,
  327. n = NaN;
  328. if (d) {
  329. w = d.length - 1;
  330. n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE;
  331. // Subtract the number of trailing zeros of the last word.
  332. w = d[w];
  333. if (w) for (; w % 10 == 0; w /= 10) n--;
  334. if (n < 0) n = 0;
  335. }
  336. return n;
  337. };
  338. /*
  339. * n / 0 = I
  340. * n / N = N
  341. * n / I = 0
  342. * 0 / n = 0
  343. * 0 / 0 = N
  344. * 0 / N = N
  345. * 0 / I = 0
  346. * N / n = N
  347. * N / 0 = N
  348. * N / N = N
  349. * N / I = N
  350. * I / n = I
  351. * I / 0 = I
  352. * I / N = N
  353. * I / I = N
  354. *
  355. * Return a new Decimal whose value is the value of this Decimal divided by `y`, rounded to
  356. * `precision` significant digits using rounding mode `rounding`.
  357. *
  358. */
  359. P.dividedBy = P.div = function (y) {
  360. return divide(this, new this.constructor(y));
  361. };
  362. /*
  363. * Return a new Decimal whose value is the integer part of dividing the value of this Decimal
  364. * by the value of `y`, rounded to `precision` significant digits using rounding mode `rounding`.
  365. *
  366. */
  367. P.dividedToIntegerBy = P.divToInt = function (y) {
  368. var x = this,
  369. Ctor = x.constructor;
  370. return finalise(divide(x, new Ctor(y), 0, 1, 1), Ctor.precision, Ctor.rounding);
  371. };
  372. /*
  373. * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false.
  374. *
  375. */
  376. P.equals = P.eq = function (y) {
  377. return this.cmp(y) === 0;
  378. };
  379. /*
  380. * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the
  381. * direction of negative Infinity.
  382. *
  383. */
  384. P.floor = function () {
  385. return finalise(new this.constructor(this), this.e + 1, 3);
  386. };
  387. /*
  388. * Return true if the value of this Decimal is greater than the value of `y`, otherwise return
  389. * false.
  390. *
  391. */
  392. P.greaterThan = P.gt = function (y) {
  393. return this.cmp(y) > 0;
  394. };
  395. /*
  396. * Return true if the value of this Decimal is greater than or equal to the value of `y`,
  397. * otherwise return false.
  398. *
  399. */
  400. P.greaterThanOrEqualTo = P.gte = function (y) {
  401. var k = this.cmp(y);
  402. return k == 1 || k === 0;
  403. };
  404. /*
  405. * Return a new Decimal whose value is the hyperbolic cosine of the value in radians of this
  406. * Decimal.
  407. *
  408. * Domain: [-Infinity, Infinity]
  409. * Range: [1, Infinity]
  410. *
  411. * cosh(x) = 1 + x^2/2! + x^4/4! + x^6/6! + ...
  412. *
  413. * cosh(0) = 1
  414. * cosh(-0) = 1
  415. * cosh(Infinity) = Infinity
  416. * cosh(-Infinity) = Infinity
  417. * cosh(NaN) = NaN
  418. *
  419. * x time taken (ms) result
  420. * 1000 9 9.8503555700852349694e+433
  421. * 10000 25 4.4034091128314607936e+4342
  422. * 100000 171 1.4033316802130615897e+43429
  423. * 1000000 3817 1.5166076984010437725e+434294
  424. * 10000000 abandoned after 2 minute wait
  425. *
  426. * TODO? Compare performance of cosh(x) = 0.5 * (exp(x) + exp(-x))
  427. *
  428. */
  429. P.hyperbolicCosine = P.cosh = function () {
  430. var k, n, pr, rm, len,
  431. x = this,
  432. Ctor = x.constructor,
  433. one = new Ctor(1);
  434. if (!x.isFinite()) return new Ctor(x.s ? 1 / 0 : NaN);
  435. if (x.isZero()) return one;
  436. pr = Ctor.precision;
  437. rm = Ctor.rounding;
  438. Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;
  439. Ctor.rounding = 1;
  440. len = x.d.length;
  441. // Argument reduction: cos(4x) = 1 - 8cos^2(x) + 8cos^4(x) + 1
  442. // i.e. cos(x) = 1 - cos^2(x/4)(8 - 8cos^2(x/4))
  443. // Estimate the optimum number of times to use the argument reduction.
  444. // TODO? Estimation reused from cosine() and may not be optimal here.
  445. if (len < 32) {
  446. k = Math.ceil(len / 3);
  447. n = (1 / tinyPow(4, k)).toString();
  448. } else {
  449. k = 16;
  450. n = '2.3283064365386962890625e-10';
  451. }
  452. x = taylorSeries(Ctor, 1, x.times(n), new Ctor(1), true);
  453. // Reverse argument reduction
  454. var cosh2_x,
  455. i = k,
  456. d8 = new Ctor(8);
  457. for (; i--;) {
  458. cosh2_x = x.times(x);
  459. x = one.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8))));
  460. }
  461. return finalise(x, Ctor.precision = pr, Ctor.rounding = rm, true);
  462. };
  463. /*
  464. * Return a new Decimal whose value is the hyperbolic sine of the value in radians of this
  465. * Decimal.
  466. *
  467. * Domain: [-Infinity, Infinity]
  468. * Range: [-Infinity, Infinity]
  469. *
  470. * sinh(x) = x + x^3/3! + x^5/5! + x^7/7! + ...
  471. *
  472. * sinh(0) = 0
  473. * sinh(-0) = -0
  474. * sinh(Infinity) = Infinity
  475. * sinh(-Infinity) = -Infinity
  476. * sinh(NaN) = NaN
  477. *
  478. * x time taken (ms)
  479. * 10 2 ms
  480. * 100 5 ms
  481. * 1000 14 ms
  482. * 10000 82 ms
  483. * 100000 886 ms 1.4033316802130615897e+43429
  484. * 200000 2613 ms
  485. * 300000 5407 ms
  486. * 400000 8824 ms
  487. * 500000 13026 ms 8.7080643612718084129e+217146
  488. * 1000000 48543 ms
  489. *
  490. * TODO? Compare performance of sinh(x) = 0.5 * (exp(x) - exp(-x))
  491. *
  492. */
  493. P.hyperbolicSine = P.sinh = function () {
  494. var k, pr, rm, len,
  495. x = this,
  496. Ctor = x.constructor;
  497. if (!x.isFinite() || x.isZero()) return new Ctor(x);
  498. pr = Ctor.precision;
  499. rm = Ctor.rounding;
  500. Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;
  501. Ctor.rounding = 1;
  502. len = x.d.length;
  503. if (len < 3) {
  504. x = taylorSeries(Ctor, 2, x, x, true);
  505. } else {
  506. // Alternative argument reduction: sinh(3x) = sinh(x)(3 + 4sinh^2(x))
  507. // i.e. sinh(x) = sinh(x/3)(3 + 4sinh^2(x/3))
  508. // 3 multiplications and 1 addition
  509. // Argument reduction: sinh(5x) = sinh(x)(5 + sinh^2(x)(20 + 16sinh^2(x)))
  510. // i.e. sinh(x) = sinh(x/5)(5 + sinh^2(x/5)(20 + 16sinh^2(x/5)))
  511. // 4 multiplications and 2 additions
  512. // Estimate the optimum number of times to use the argument reduction.
  513. k = 1.4 * Math.sqrt(len);
  514. k = k > 16 ? 16 : k | 0;
  515. x = x.times(1 / tinyPow(5, k));
  516. x = taylorSeries(Ctor, 2, x, x, true);
  517. // Reverse argument reduction
  518. var sinh2_x,
  519. d5 = new Ctor(5),
  520. d16 = new Ctor(16),
  521. d20 = new Ctor(20);
  522. for (; k--;) {
  523. sinh2_x = x.times(x);
  524. x = x.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20))));
  525. }
  526. }
  527. Ctor.precision = pr;
  528. Ctor.rounding = rm;
  529. return finalise(x, pr, rm, true);
  530. };
  531. /*
  532. * Return a new Decimal whose value is the hyperbolic tangent of the value in radians of this
  533. * Decimal.
  534. *
  535. * Domain: [-Infinity, Infinity]
  536. * Range: [-1, 1]
  537. *
  538. * tanh(x) = sinh(x) / cosh(x)
  539. *
  540. * tanh(0) = 0
  541. * tanh(-0) = -0
  542. * tanh(Infinity) = 1
  543. * tanh(-Infinity) = -1
  544. * tanh(NaN) = NaN
  545. *
  546. */
  547. P.hyperbolicTangent = P.tanh = function () {
  548. var pr, rm,
  549. x = this,
  550. Ctor = x.constructor;
  551. if (!x.isFinite()) return new Ctor(x.s);
  552. if (x.isZero()) return new Ctor(x);
  553. pr = Ctor.precision;
  554. rm = Ctor.rounding;
  555. Ctor.precision = pr + 7;
  556. Ctor.rounding = 1;
  557. return divide(x.sinh(), x.cosh(), Ctor.precision = pr, Ctor.rounding = rm);
  558. };
  559. /*
  560. * Return a new Decimal whose value is the arccosine (inverse cosine) in radians of the value of
  561. * this Decimal.
  562. *
  563. * Domain: [-1, 1]
  564. * Range: [0, pi]
  565. *
  566. * acos(x) = pi/2 - asin(x)
  567. *
  568. * acos(0) = pi/2
  569. * acos(-0) = pi/2
  570. * acos(1) = 0
  571. * acos(-1) = pi
  572. * acos(1/2) = pi/3
  573. * acos(-1/2) = 2*pi/3
  574. * acos(|x| > 1) = NaN
  575. * acos(NaN) = NaN
  576. *
  577. */
  578. P.inverseCosine = P.acos = function () {
  579. var halfPi,
  580. x = this,
  581. Ctor = x.constructor,
  582. k = x.abs().cmp(1),
  583. pr = Ctor.precision,
  584. rm = Ctor.rounding;
  585. if (k !== -1) {
  586. return k === 0
  587. // |x| is 1
  588. ? x.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0)
  589. // |x| > 1 or x is NaN
  590. : new Ctor(NaN);
  591. }
  592. if (x.isZero()) return getPi(Ctor, pr + 4, rm).times(0.5);
  593. // TODO? Special case acos(0.5) = pi/3 and acos(-0.5) = 2*pi/3
  594. Ctor.precision = pr + 6;
  595. Ctor.rounding = 1;
  596. x = x.asin();
  597. halfPi = getPi(Ctor, pr + 4, rm).times(0.5);
  598. Ctor.precision = pr;
  599. Ctor.rounding = rm;
  600. return halfPi.minus(x);
  601. };
  602. /*
  603. * Return a new Decimal whose value is the inverse of the hyperbolic cosine in radians of the
  604. * value of this Decimal.
  605. *
  606. * Domain: [1, Infinity]
  607. * Range: [0, Infinity]
  608. *
  609. * acosh(x) = ln(x + sqrt(x^2 - 1))
  610. *
  611. * acosh(x < 1) = NaN
  612. * acosh(NaN) = NaN
  613. * acosh(Infinity) = Infinity
  614. * acosh(-Infinity) = NaN
  615. * acosh(0) = NaN
  616. * acosh(-0) = NaN
  617. * acosh(1) = 0
  618. * acosh(-1) = NaN
  619. *
  620. */
  621. P.inverseHyperbolicCosine = P.acosh = function () {
  622. var pr, rm,
  623. x = this,
  624. Ctor = x.constructor;
  625. if (x.lte(1)) return new Ctor(x.eq(1) ? 0 : NaN);
  626. if (!x.isFinite()) return new Ctor(x);
  627. pr = Ctor.precision;
  628. rm = Ctor.rounding;
  629. Ctor.precision = pr + Math.max(Math.abs(x.e), x.sd()) + 4;
  630. Ctor.rounding = 1;
  631. external = false;
  632. x = x.times(x).minus(1).sqrt().plus(x);
  633. external = true;
  634. Ctor.precision = pr;
  635. Ctor.rounding = rm;
  636. return x.ln();
  637. };
  638. /*
  639. * Return a new Decimal whose value is the inverse of the hyperbolic sine in radians of the value
  640. * of this Decimal.
  641. *
  642. * Domain: [-Infinity, Infinity]
  643. * Range: [-Infinity, Infinity]
  644. *
  645. * asinh(x) = ln(x + sqrt(x^2 + 1))
  646. *
  647. * asinh(NaN) = NaN
  648. * asinh(Infinity) = Infinity
  649. * asinh(-Infinity) = -Infinity
  650. * asinh(0) = 0
  651. * asinh(-0) = -0
  652. *
  653. */
  654. P.inverseHyperbolicSine = P.asinh = function () {
  655. var pr, rm,
  656. x = this,
  657. Ctor = x.constructor;
  658. if (!x.isFinite() || x.isZero()) return new Ctor(x);
  659. pr = Ctor.precision;
  660. rm = Ctor.rounding;
  661. Ctor.precision = pr + 2 * Math.max(Math.abs(x.e), x.sd()) + 6;
  662. Ctor.rounding = 1;
  663. external = false;
  664. x = x.times(x).plus(1).sqrt().plus(x);
  665. external = true;
  666. Ctor.precision = pr;
  667. Ctor.rounding = rm;
  668. return x.ln();
  669. };
  670. /*
  671. * Return a new Decimal whose value is the inverse of the hyperbolic tangent in radians of the
  672. * value of this Decimal.
  673. *
  674. * Domain: [-1, 1]
  675. * Range: [-Infinity, Infinity]
  676. *
  677. * atanh(x) = 0.5 * ln((1 + x) / (1 - x))
  678. *
  679. * atanh(|x| > 1) = NaN
  680. * atanh(NaN) = NaN
  681. * atanh(Infinity) = NaN
  682. * atanh(-Infinity) = NaN
  683. * atanh(0) = 0
  684. * atanh(-0) = -0
  685. * atanh(1) = Infinity
  686. * atanh(-1) = -Infinity
  687. *
  688. */
  689. P.inverseHyperbolicTangent = P.atanh = function () {
  690. var pr, rm, wpr, xsd,
  691. x = this,
  692. Ctor = x.constructor;
  693. if (!x.isFinite()) return new Ctor(NaN);
  694. if (x.e >= 0) return new Ctor(x.abs().eq(1) ? x.s / 0 : x.isZero() ? x : NaN);
  695. pr = Ctor.precision;
  696. rm = Ctor.rounding;
  697. xsd = x.sd();
  698. if (Math.max(xsd, pr) < 2 * -x.e - 1) return finalise(new Ctor(x), pr, rm, true);
  699. Ctor.precision = wpr = xsd - x.e;
  700. x = divide(x.plus(1), new Ctor(1).minus(x), wpr + pr, 1);
  701. Ctor.precision = pr + 4;
  702. Ctor.rounding = 1;
  703. x = x.ln();
  704. Ctor.precision = pr;
  705. Ctor.rounding = rm;
  706. return x.times(0.5);
  707. };
  708. /*
  709. * Return a new Decimal whose value is the arcsine (inverse sine) in radians of the value of this
  710. * Decimal.
  711. *
  712. * Domain: [-Infinity, Infinity]
  713. * Range: [-pi/2, pi/2]
  714. *
  715. * asin(x) = 2*atan(x/(1 + sqrt(1 - x^2)))
  716. *
  717. * asin(0) = 0
  718. * asin(-0) = -0
  719. * asin(1/2) = pi/6
  720. * asin(-1/2) = -pi/6
  721. * asin(1) = pi/2
  722. * asin(-1) = -pi/2
  723. * asin(|x| > 1) = NaN
  724. * asin(NaN) = NaN
  725. *
  726. * TODO? Compare performance of Taylor series.
  727. *
  728. */
  729. P.inverseSine = P.asin = function () {
  730. var halfPi, k,
  731. pr, rm,
  732. x = this,
  733. Ctor = x.constructor;
  734. if (x.isZero()) return new Ctor(x);
  735. k = x.abs().cmp(1);
  736. pr = Ctor.precision;
  737. rm = Ctor.rounding;
  738. if (k !== -1) {
  739. // |x| is 1
  740. if (k === 0) {
  741. halfPi = getPi(Ctor, pr + 4, rm).times(0.5);
  742. halfPi.s = x.s;
  743. return halfPi;
  744. }
  745. // |x| > 1 or x is NaN
  746. return new Ctor(NaN);
  747. }
  748. // TODO? Special case asin(1/2) = pi/6 and asin(-1/2) = -pi/6
  749. Ctor.precision = pr + 6;
  750. Ctor.rounding = 1;
  751. x = x.div(new Ctor(1).minus(x.times(x)).sqrt().plus(1)).atan();
  752. Ctor.precision = pr;
  753. Ctor.rounding = rm;
  754. return x.times(2);
  755. };
  756. /*
  757. * Return a new Decimal whose value is the arctangent (inverse tangent) in radians of the value
  758. * of this Decimal.
  759. *
  760. * Domain: [-Infinity, Infinity]
  761. * Range: [-pi/2, pi/2]
  762. *
  763. * atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...
  764. *
  765. * atan(0) = 0
  766. * atan(-0) = -0
  767. * atan(1) = pi/4
  768. * atan(-1) = -pi/4
  769. * atan(Infinity) = pi/2
  770. * atan(-Infinity) = -pi/2
  771. * atan(NaN) = NaN
  772. *
  773. */
  774. P.inverseTangent = P.atan = function () {
  775. var i, j, k, n, px, t, r, wpr, x2,
  776. x = this,
  777. Ctor = x.constructor,
  778. pr = Ctor.precision,
  779. rm = Ctor.rounding;
  780. if (!x.isFinite()) {
  781. if (!x.s) return new Ctor(NaN);
  782. if (pr + 4 <= PI_PRECISION) {
  783. r = getPi(Ctor, pr + 4, rm).times(0.5);
  784. r.s = x.s;
  785. return r;
  786. }
  787. } else if (x.isZero()) {
  788. return new Ctor(x);
  789. } else if (x.abs().eq(1) && pr + 4 <= PI_PRECISION) {
  790. r = getPi(Ctor, pr + 4, rm).times(0.25);
  791. r.s = x.s;
  792. return r;
  793. }
  794. Ctor.precision = wpr = pr + 10;
  795. Ctor.rounding = 1;
  796. // TODO? if (x >= 1 && pr <= PI_PRECISION) atan(x) = halfPi * x.s - atan(1 / x);
  797. // Argument reduction
  798. // Ensure |x| < 0.42
  799. // atan(x) = 2 * atan(x / (1 + sqrt(1 + x^2)))
  800. k = Math.min(28, wpr / LOG_BASE + 2 | 0);
  801. for (i = k; i; --i) x = x.div(x.times(x).plus(1).sqrt().plus(1));
  802. external = false;
  803. j = Math.ceil(wpr / LOG_BASE);
  804. n = 1;
  805. x2 = x.times(x);
  806. r = new Ctor(x);
  807. px = x;
  808. // atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...
  809. for (; i !== -1;) {
  810. px = px.times(x2);
  811. t = r.minus(px.div(n += 2));
  812. px = px.times(x2);
  813. r = t.plus(px.div(n += 2));
  814. if (r.d[j] !== void 0) for (i = j; r.d[i] === t.d[i] && i--;);
  815. }
  816. if (k) r = r.times(2 << (k - 1));
  817. external = true;
  818. return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true);
  819. };
  820. /*
  821. * Return true if the value of this Decimal is a finite number, otherwise return false.
  822. *
  823. */
  824. P.isFinite = function () {
  825. return !!this.d;
  826. };
  827. /*
  828. * Return true if the value of this Decimal is an integer, otherwise return false.
  829. *
  830. */
  831. P.isInteger = P.isInt = function () {
  832. return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2;
  833. };
  834. /*
  835. * Return true if the value of this Decimal is NaN, otherwise return false.
  836. *
  837. */
  838. P.isNaN = function () {
  839. return !this.s;
  840. };
  841. /*
  842. * Return true if the value of this Decimal is negative, otherwise return false.
  843. *
  844. */
  845. P.isNegative = P.isNeg = function () {
  846. return this.s < 0;
  847. };
  848. /*
  849. * Return true if the value of this Decimal is positive, otherwise return false.
  850. *
  851. */
  852. P.isPositive = P.isPos = function () {
  853. return this.s > 0;
  854. };
  855. /*
  856. * Return true if the value of this Decimal is 0 or -0, otherwise return false.
  857. *
  858. */
  859. P.isZero = function () {
  860. return !!this.d && this.d[0] === 0;
  861. };
  862. /*
  863. * Return true if the value of this Decimal is less than `y`, otherwise return false.
  864. *
  865. */
  866. P.lessThan = P.lt = function (y) {
  867. return this.cmp(y) < 0;
  868. };
  869. /*
  870. * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false.
  871. *
  872. */
  873. P.lessThanOrEqualTo = P.lte = function (y) {
  874. return this.cmp(y) < 1;
  875. };
  876. /*
  877. * Return the logarithm of the value of this Decimal to the specified base, rounded to `precision`
  878. * significant digits using rounding mode `rounding`.
  879. *
  880. * If no base is specified, return log[10](arg).
  881. *
  882. * log[base](arg) = ln(arg) / ln(base)
  883. *
  884. * The result will always be correctly rounded if the base of the log is 10, and 'almost always'
  885. * otherwise:
  886. *
  887. * Depending on the rounding mode, the result may be incorrectly rounded if the first fifteen
  888. * rounding digits are [49]99999999999999 or [50]00000000000000. In that case, the maximum error
  889. * between the result and the correctly rounded result will be one ulp (unit in the last place).
  890. *
  891. * log[-b](a) = NaN
  892. * log[0](a) = NaN
  893. * log[1](a) = NaN
  894. * log[NaN](a) = NaN
  895. * log[Infinity](a) = NaN
  896. * log[b](0) = -Infinity
  897. * log[b](-0) = -Infinity
  898. * log[b](-a) = NaN
  899. * log[b](1) = 0
  900. * log[b](Infinity) = Infinity
  901. * log[b](NaN) = NaN
  902. *
  903. * [base] {number|string|Decimal} The base of the logarithm.
  904. *
  905. */
  906. P.logarithm = P.log = function (base) {
  907. var isBase10, d, denominator, k, inf, num, sd, r,
  908. arg = this,
  909. Ctor = arg.constructor,
  910. pr = Ctor.precision,
  911. rm = Ctor.rounding,
  912. guard = 5;
  913. // Default base is 10.
  914. if (base == null) {
  915. base = new Ctor(10);
  916. isBase10 = true;
  917. } else {
  918. base = new Ctor(base);
  919. d = base.d;
  920. // Return NaN if base is negative, or non-finite, or is 0 or 1.
  921. if (base.s < 0 || !d || !d[0] || base.eq(1)) return new Ctor(NaN);
  922. isBase10 = base.eq(10);
  923. }
  924. d = arg.d;
  925. // Is arg negative, non-finite, 0 or 1?
  926. if (arg.s < 0 || !d || !d[0] || arg.eq(1)) {
  927. return new Ctor(d && !d[0] ? -1 / 0 : arg.s != 1 ? NaN : d ? 0 : 1 / 0);
  928. }
  929. // The result will have a non-terminating decimal expansion if base is 10 and arg is not an
  930. // integer power of 10.
  931. if (isBase10) {
  932. if (d.length > 1) {
  933. inf = true;
  934. } else {
  935. for (k = d[0]; k % 10 === 0;) k /= 10;
  936. inf = k !== 1;
  937. }
  938. }
  939. external = false;
  940. sd = pr + guard;
  941. num = naturalLogarithm(arg, sd);
  942. denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);
  943. // The result will have 5 rounding digits.
  944. r = divide(num, denominator, sd, 1);
  945. // If at a rounding boundary, i.e. the result's rounding digits are [49]9999 or [50]0000,
  946. // calculate 10 further digits.
  947. //
  948. // If the result is known to have an infinite decimal expansion, repeat this until it is clear
  949. // that the result is above or below the boundary. Otherwise, if after calculating the 10
  950. // further digits, the last 14 are nines, round up and assume the result is exact.
  951. // Also assume the result is exact if the last 14 are zero.
  952. //
  953. // Example of a result that will be incorrectly rounded:
  954. // log[1048576](4503599627370502) = 2.60000000000000009610279511444746...
  955. // The above result correctly rounded using ROUND_CEIL to 1 decimal place should be 2.7, but it
  956. // will be given as 2.6 as there are 15 zeros immediately after the requested decimal place, so
  957. // the exact result would be assumed to be 2.6, which rounded using ROUND_CEIL to 1 decimal
  958. // place is still 2.6.
  959. if (checkRoundingDigits(r.d, k = pr, rm)) {
  960. do {
  961. sd += 10;
  962. num = naturalLogarithm(arg, sd);
  963. denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);
  964. r = divide(num, denominator, sd, 1);
  965. if (!inf) {
  966. // Check for 14 nines from the 2nd rounding digit, as the first may be 4.
  967. if (+digitsToString(r.d).slice(k + 1, k + 15) + 1 == 1e14) {
  968. r = finalise(r, pr + 1, 0);
  969. }
  970. break;
  971. }
  972. } while (checkRoundingDigits(r.d, k += 10, rm));
  973. }
  974. external = true;
  975. return finalise(r, pr, rm);
  976. };
  977. /*
  978. * Return a new Decimal whose value is the maximum of the arguments and the value of this Decimal.
  979. *
  980. * arguments {number|string|Decimal}
  981. *
  982. P.max = function () {
  983. Array.prototype.push.call(arguments, this);
  984. return maxOrMin(this.constructor, arguments, 'lt');
  985. };
  986. */
  987. /*
  988. * Return a new Decimal whose value is the minimum of the arguments and the value of this Decimal.
  989. *
  990. * arguments {number|string|Decimal}
  991. *
  992. P.min = function () {
  993. Array.prototype.push.call(arguments, this);
  994. return maxOrMin(this.constructor, arguments, 'gt');
  995. };
  996. */
  997. /*
  998. * n - 0 = n
  999. * n - N = N
  1000. * n - I = -I
  1001. * 0 - n = -n
  1002. * 0 - 0 = 0
  1003. * 0 - N = N
  1004. * 0 - I = -I
  1005. * N - n = N
  1006. * N - 0 = N
  1007. * N - N = N
  1008. * N - I = N
  1009. * I - n = I
  1010. * I - 0 = I
  1011. * I - N = N
  1012. * I - I = N
  1013. *
  1014. * Return a new Decimal whose value is the value of this Decimal minus `y`, rounded to `precision`
  1015. * significant digits using rounding mode `rounding`.
  1016. *
  1017. */
  1018. P.minus = P.sub = function (y) {
  1019. var d, e, i, j, k, len, pr, rm, xd, xe, xLTy, yd,
  1020. x = this,
  1021. Ctor = x.constructor;
  1022. y = new Ctor(y);
  1023. // If either is not finite...
  1024. if (!x.d || !y.d) {
  1025. // Return NaN if either is NaN.
  1026. if (!x.s || !y.s) y = new Ctor(NaN);
  1027. // Return y negated if x is finite and y is ±Infinity.
  1028. else if (x.d) y.s = -y.s;
  1029. // Return x if y is finite and x is ±Infinity.
  1030. // Return x if both are ±Infinity with different signs.
  1031. // Return NaN if both are ±Infinity with the same sign.
  1032. else y = new Ctor(y.d || x.s !== y.s ? x : NaN);
  1033. return y;
  1034. }
  1035. // If signs differ...
  1036. if (x.s != y.s) {
  1037. y.s = -y.s;
  1038. return x.plus(y);
  1039. }
  1040. xd = x.d;
  1041. yd = y.d;
  1042. pr = Ctor.precision;
  1043. rm = Ctor.rounding;
  1044. // If either is zero...
  1045. if (!xd[0] || !yd[0]) {
  1046. // Return y negated if x is zero and y is non-zero.
  1047. if (yd[0]) y.s = -y.s;
  1048. // Return x if y is zero and x is non-zero.
  1049. else if (xd[0]) y = new Ctor(x);
  1050. // Return zero if both are zero.
  1051. // From IEEE 754 (2008) 6.3: 0 - 0 = -0 - -0 = -0 when rounding to -Infinity.
  1052. else return new Ctor(rm === 3 ? -0 : 0);
  1053. return external ? finalise(y, pr, rm) : y;
  1054. }
  1055. // x and y are finite, non-zero numbers with the same sign.
  1056. // Calculate base 1e7 exponents.
  1057. e = mathfloor(y.e / LOG_BASE);
  1058. xe = mathfloor(x.e / LOG_BASE);
  1059. xd = xd.slice();
  1060. k = xe - e;
  1061. // If base 1e7 exponents differ...
  1062. if (k) {
  1063. xLTy = k < 0;
  1064. if (xLTy) {
  1065. d = xd;
  1066. k = -k;
  1067. len = yd.length;
  1068. } else {
  1069. d = yd;
  1070. e = xe;
  1071. len = xd.length;
  1072. }
  1073. // Numbers with massively different exponents would result in a very high number of
  1074. // zeros needing to be prepended, but this can be avoided while still ensuring correct
  1075. // rounding by limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`.
  1076. i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2;
  1077. if (k > i) {
  1078. k = i;
  1079. d.length = 1;
  1080. }
  1081. // Prepend zeros to equalise exponents.
  1082. d.reverse();
  1083. for (i = k; i--;) d.push(0);
  1084. d.reverse();
  1085. // Base 1e7 exponents equal.
  1086. } else {
  1087. // Check digits to determine which is the bigger number.
  1088. i = xd.length;
  1089. len = yd.length;
  1090. xLTy = i < len;
  1091. if (xLTy) len = i;
  1092. for (i = 0; i < len; i++) {
  1093. if (xd[i] != yd[i]) {
  1094. xLTy = xd[i] < yd[i];
  1095. break;
  1096. }
  1097. }
  1098. k = 0;
  1099. }
  1100. if (xLTy) {
  1101. d = xd;
  1102. xd = yd;
  1103. yd = d;
  1104. y.s = -y.s;
  1105. }
  1106. len = xd.length;
  1107. // Append zeros to `xd` if shorter.
  1108. // Don't add zeros to `yd` if shorter as subtraction only needs to start at `yd` length.
  1109. for (i = yd.length - len; i > 0; --i) xd[len++] = 0;
  1110. // Subtract yd from xd.
  1111. for (i = yd.length; i > k;) {
  1112. if (xd[--i] < yd[i]) {
  1113. for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1;
  1114. --xd[j];
  1115. xd[i] += BASE;
  1116. }
  1117. xd[i] -= yd[i];
  1118. }
  1119. // Remove trailing zeros.
  1120. for (; xd[--len] === 0;) xd.pop();
  1121. // Remove leading zeros and adjust exponent accordingly.
  1122. for (; xd[0] === 0; xd.shift()) --e;
  1123. // Zero?
  1124. if (!xd[0]) return new Ctor(rm === 3 ? -0 : 0);
  1125. y.d = xd;
  1126. y.e = getBase10Exponent(xd, e);
  1127. return external ? finalise(y, pr, rm) : y;
  1128. };
  1129. /*
  1130. * n % 0 = N
  1131. * n % N = N
  1132. * n % I = n
  1133. * 0 % n = 0
  1134. * -0 % n = -0
  1135. * 0 % 0 = N
  1136. * 0 % N = N
  1137. * 0 % I = 0
  1138. * N % n = N
  1139. * N % 0 = N
  1140. * N % N = N
  1141. * N % I = N
  1142. * I % n = N
  1143. * I % 0 = N
  1144. * I % N = N
  1145. * I % I = N
  1146. *
  1147. * Return a new Decimal whose value is the value of this Decimal modulo `y`, rounded to
  1148. * `precision` significant digits using rounding mode `rounding`.
  1149. *
  1150. * The result depends on the modulo mode.
  1151. *
  1152. */
  1153. P.modulo = P.mod = function (y) {
  1154. var q,
  1155. x = this,
  1156. Ctor = x.constructor;
  1157. y = new Ctor(y);
  1158. // Return NaN if x is ±Infinity or NaN, or y is NaN or ±0.
  1159. if (!x.d || !y.s || y.d && !y.d[0]) return new Ctor(NaN);
  1160. // Return x if y is ±Infinity or x is ±0.
  1161. if (!y.d || x.d && !x.d[0]) {
  1162. return finalise(new Ctor(x), Ctor.precision, Ctor.rounding);
  1163. }
  1164. // Prevent rounding of intermediate calculations.
  1165. external = false;
  1166. if (Ctor.modulo == 9) {
  1167. // Euclidian division: q = sign(y) * floor(x / abs(y))
  1168. // result = x - q * y where 0 <= result < abs(y)
  1169. q = divide(x, y.abs(), 0, 3, 1);
  1170. q.s *= y.s;
  1171. } else {
  1172. q = divide(x, y, 0, Ctor.modulo, 1);
  1173. }
  1174. q = q.times(y);
  1175. external = true;
  1176. return x.minus(q);
  1177. };
  1178. /*
  1179. * Return a new Decimal whose value is the natural exponential of the value of this Decimal,
  1180. * i.e. the base e raised to the power the value of this Decimal, rounded to `precision`
  1181. * significant digits using rounding mode `rounding`.
  1182. *
  1183. */
  1184. P.naturalExponential = P.exp = function () {
  1185. return naturalExponential(this);
  1186. };
  1187. /*
  1188. * Return a new Decimal whose value is the natural logarithm of the value of this Decimal,
  1189. * rounded to `precision` significant digits using rounding mode `rounding`.
  1190. *
  1191. */
  1192. P.naturalLogarithm = P.ln = function () {
  1193. return naturalLogarithm(this);
  1194. };
  1195. /*
  1196. * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by
  1197. * -1.
  1198. *
  1199. */
  1200. P.negated = P.neg = function () {
  1201. var x = new this.constructor(this);
  1202. x.s = -x.s;
  1203. return finalise(x);
  1204. };
  1205. /*
  1206. * n + 0 = n
  1207. * n + N = N
  1208. * n + I = I
  1209. * 0 + n = n
  1210. * 0 + 0 = 0
  1211. * 0 + N = N
  1212. * 0 + I = I
  1213. * N + n = N
  1214. * N + 0 = N
  1215. * N + N = N
  1216. * N + I = N
  1217. * I + n = I
  1218. * I + 0 = I
  1219. * I + N = N
  1220. * I + I = I
  1221. *
  1222. * Return a new Decimal whose value is the value of this Decimal plus `y`, rounded to `precision`
  1223. * significant digits using rounding mode `rounding`.
  1224. *
  1225. */
  1226. P.plus = P.add = function (y) {
  1227. var carry, d, e, i, k, len, pr, rm, xd, yd,
  1228. x = this,
  1229. Ctor = x.constructor;
  1230. y = new Ctor(y);
  1231. // If either is not finite...
  1232. if (!x.d || !y.d) {
  1233. // Return NaN if either is NaN.
  1234. if (!x.s || !y.s) y = new Ctor(NaN);
  1235. // Return x if y is finite and x is ±Infinity.
  1236. // Return x if both are ±Infinity with the same sign.
  1237. // Return NaN if both are ±Infinity with different signs.
  1238. // Return y if x is finite and y is ±Infinity.
  1239. else if (!x.d) y = new Ctor(y.d || x.s === y.s ? x : NaN);
  1240. return y;
  1241. }
  1242. // If signs differ...
  1243. if (x.s != y.s) {
  1244. y.s = -y.s;
  1245. return x.minus(y);
  1246. }
  1247. xd = x.d;
  1248. yd = y.d;
  1249. pr = Ctor.precision;
  1250. rm = Ctor.rounding;
  1251. // If either is zero...
  1252. if (!xd[0] || !yd[0]) {
  1253. // Return x if y is zero.
  1254. // Return y if y is non-zero.
  1255. if (!yd[0]) y = new Ctor(x);
  1256. return external ? finalise(y, pr, rm) : y;
  1257. }
  1258. // x and y are finite, non-zero numbers with the same sign.
  1259. // Calculate base 1e7 exponents.
  1260. k = mathfloor(x.e / LOG_BASE);
  1261. e = mathfloor(y.e / LOG_BASE);
  1262. xd = xd.slice();
  1263. i = k - e;
  1264. // If base 1e7 exponents differ...
  1265. if (i) {
  1266. if (i < 0) {
  1267. d = xd;
  1268. i = -i;
  1269. len = yd.length;
  1270. } else {
  1271. d = yd;
  1272. e = k;
  1273. len = xd.length;
  1274. }
  1275. // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1.
  1276. k = Math.ceil(pr / LOG_BASE);
  1277. len = k > len ? k + 1 : len + 1;
  1278. if (i > len) {
  1279. i = len;
  1280. d.length = 1;
  1281. }
  1282. // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts.
  1283. d.reverse();
  1284. for (; i--;) d.push(0);
  1285. d.reverse();
  1286. }
  1287. len = xd.length;
  1288. i = yd.length;
  1289. // If yd is longer than xd, swap xd and yd so xd points to the longer array.
  1290. if (len - i < 0) {
  1291. i = len;
  1292. d = yd;
  1293. yd = xd;
  1294. xd = d;
  1295. }
  1296. // Only start adding at yd.length - 1 as the further digits of xd can be left as they are.
  1297. for (carry = 0; i;) {
  1298. carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0;
  1299. xd[i] %= BASE;
  1300. }
  1301. if (carry) {
  1302. xd.unshift(carry);
  1303. ++e;
  1304. }
  1305. // Remove trailing zeros.
  1306. // No need to check for zero, as +x + +y != 0 && -x + -y != 0
  1307. for (len = xd.length; xd[--len] == 0;) xd.pop();
  1308. y.d = xd;
  1309. y.e = getBase10Exponent(xd, e);
  1310. return external ? finalise(y, pr, rm) : y;
  1311. };
  1312. /*
  1313. * Return the number of significant digits of the value of this Decimal.
  1314. *
  1315. * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
  1316. *
  1317. */
  1318. P.precision = P.sd = function (z) {
  1319. var k,
  1320. x = this;
  1321. if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z);
  1322. if (x.d) {
  1323. k = getPrecision(x.d);
  1324. if (z && x.e + 1 > k) k = x.e + 1;
  1325. } else {
  1326. k = NaN;
  1327. }
  1328. return k;
  1329. };
  1330. /*
  1331. * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using
  1332. * rounding mode `rounding`.
  1333. *
  1334. */
  1335. P.round = function () {
  1336. var x = this,
  1337. Ctor = x.constructor;
  1338. return finalise(new Ctor(x), x.e + 1, Ctor.rounding);
  1339. };
  1340. /*
  1341. * Return a new Decimal whose value is the sine of the value in radians of this Decimal.
  1342. *
  1343. * Domain: [-Infinity, Infinity]
  1344. * Range: [-1, 1]
  1345. *
  1346. * sin(x) = x - x^3/3! + x^5/5! - ...
  1347. *
  1348. * sin(0) = 0
  1349. * sin(-0) = -0
  1350. * sin(Infinity) = NaN
  1351. * sin(-Infinity) = NaN
  1352. * sin(NaN) = NaN
  1353. *
  1354. */
  1355. P.sine = P.sin = function () {
  1356. var pr, rm,
  1357. x = this,
  1358. Ctor = x.constructor;
  1359. if (!x.isFinite()) return new Ctor(NaN);
  1360. if (x.isZero()) return new Ctor(x);
  1361. pr = Ctor.precision;
  1362. rm = Ctor.rounding;
  1363. Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;
  1364. Ctor.rounding = 1;
  1365. x = sine(Ctor, toLessThanHalfPi(Ctor, x));
  1366. Ctor.precision = pr;
  1367. Ctor.rounding = rm;
  1368. return finalise(quadrant > 2 ? x.neg() : x, pr, rm, true);
  1369. };
  1370. /*
  1371. * Return a new Decimal whose value is the square root of this Decimal, rounded to `precision`
  1372. * significant digits using rounding mode `rounding`.
  1373. *
  1374. * sqrt(-n) = N
  1375. * sqrt(N) = N
  1376. * sqrt(-I) = N
  1377. * sqrt(I) = I
  1378. * sqrt(0) = 0
  1379. * sqrt(-0) = -0
  1380. *
  1381. */
  1382. P.squareRoot = P.sqrt = function () {
  1383. var m, n, sd, r, rep, t,
  1384. x = this,
  1385. d = x.d,
  1386. e = x.e,
  1387. s = x.s,
  1388. Ctor = x.constructor;
  1389. // Negative/NaN/Infinity/zero?
  1390. if (s !== 1 || !d || !d[0]) {
  1391. return new Ctor(!s || s < 0 && (!d || d[0]) ? NaN : d ? x : 1 / 0);
  1392. }
  1393. external = false;
  1394. // Initial estimate.
  1395. s = Math.sqrt(+x);
  1396. // Math.sqrt underflow/overflow?
  1397. // Pass x to Math.sqrt as integer, then adjust the exponent of the result.
  1398. if (s == 0 || s == 1 / 0) {
  1399. n = digitsToString(d);
  1400. if ((n.length + e) % 2 == 0) n += '0';
  1401. s = Math.sqrt(n);
  1402. e = mathfloor((e + 1) / 2) - (e < 0 || e % 2);
  1403. if (s == 1 / 0) {
  1404. n = '5e' + e;
  1405. } else {
  1406. n = s.toExponential();
  1407. n = n.slice(0, n.indexOf('e') + 1) + e;
  1408. }
  1409. r = new Ctor(n);
  1410. } else {
  1411. r = new Ctor(s.toString());
  1412. }
  1413. sd = (e = Ctor.precision) + 3;
  1414. // Newton-Raphson iteration.
  1415. for (;;) {
  1416. t = r;
  1417. r = t.plus(divide(x, t, sd + 2, 1)).times(0.5);
  1418. // TODO? Replace with for-loop and checkRoundingDigits.
  1419. if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {
  1420. n = n.slice(sd - 3, sd + 1);
  1421. // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or
  1422. // 4999, i.e. approaching a rounding boundary, continue the iteration.
  1423. if (n == '9999' || !rep && n == '4999') {
  1424. // On the first iteration only, check to see if rounding up gives the exact result as the
  1425. // nines may infinitely repeat.
  1426. if (!rep) {
  1427. finalise(t, e + 1, 0);
  1428. if (t.times(t).eq(x)) {
  1429. r = t;
  1430. break;
  1431. }
  1432. }
  1433. sd += 4;
  1434. rep = 1;
  1435. } else {
  1436. // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.
  1437. // If not, then there are further digits and m will be truthy.
  1438. if (!+n || !+n.slice(1) && n.charAt(0) == '5') {
  1439. // Truncate to the first rounding digit.
  1440. finalise(r, e + 1, 1);
  1441. m = !r.times(r).eq(x);
  1442. }
  1443. break;
  1444. }
  1445. }
  1446. }
  1447. external = true;
  1448. return finalise(r, e, Ctor.rounding, m);
  1449. };
  1450. /*
  1451. * Return a new Decimal whose value is the tangent of the value in radians of this Decimal.
  1452. *
  1453. * Domain: [-Infinity, Infinity]
  1454. * Range: [-Infinity, Infinity]
  1455. *
  1456. * tan(0) = 0
  1457. * tan(-0) = -0
  1458. * tan(Infinity) = NaN
  1459. * tan(-Infinity) = NaN
  1460. * tan(NaN) = NaN
  1461. *
  1462. */
  1463. P.tangent = P.tan = function () {
  1464. var pr, rm,
  1465. x = this,
  1466. Ctor = x.constructor;
  1467. if (!x.isFinite()) return new Ctor(NaN);
  1468. if (x.isZero()) return new Ctor(x);
  1469. pr = Ctor.precision;
  1470. rm = Ctor.rounding;
  1471. Ctor.precision = pr + 10;
  1472. Ctor.rounding = 1;
  1473. x = x.sin();
  1474. x.s = 1;
  1475. x = divide(x, new Ctor(1).minus(x.times(x)).sqrt(), pr + 10, 0);
  1476. Ctor.precision = pr;
  1477. Ctor.rounding = rm;
  1478. return finalise(quadrant == 2 || quadrant == 4 ? x.neg() : x, pr, rm, true);
  1479. };
  1480. /*
  1481. * n * 0 = 0
  1482. * n * N = N
  1483. * n * I = I
  1484. * 0 * n = 0
  1485. * 0 * 0 = 0
  1486. * 0 * N = N
  1487. * 0 * I = N
  1488. * N * n = N
  1489. * N * 0 = N
  1490. * N * N = N
  1491. * N * I = N
  1492. * I * n = I
  1493. * I * 0 = N
  1494. * I * N = N
  1495. * I * I = I
  1496. *
  1497. * Return a new Decimal whose value is this Decimal times `y`, rounded to `precision` significant
  1498. * digits using rounding mode `rounding`.
  1499. *
  1500. */
  1501. P.times = P.mul = function (y) {
  1502. var carry, e, i, k, r, rL, t, xdL, ydL,
  1503. x = this,
  1504. Ctor = x.constructor,
  1505. xd = x.d,
  1506. yd = (y = new Ctor(y)).d;
  1507. y.s *= x.s;
  1508. // If either is NaN, ±Infinity or ±0...
  1509. if (!xd || !xd[0] || !yd || !yd[0]) {
  1510. return new Ctor(!y.s || xd && !xd[0] && !yd || yd && !yd[0] && !xd
  1511. // Return NaN if either is NaN.
  1512. // Return NaN if x is ±0 and y is ±Infinity, or y is ±0 and x is ±Infinity.
  1513. ? NaN
  1514. // Return ±Infinity if either is ±Infinity.
  1515. // Return ±0 if either is ±0.
  1516. : !xd || !yd ? y.s / 0 : y.s * 0);
  1517. }
  1518. e = mathfloor(x.e / LOG_BASE) + mathfloor(y.e / LOG_BASE);
  1519. xdL = xd.length;
  1520. ydL = yd.length;
  1521. // Ensure xd points to the longer array.
  1522. if (xdL < ydL) {
  1523. r = xd;
  1524. xd = yd;
  1525. yd = r;
  1526. rL = xdL;
  1527. xdL = ydL;
  1528. ydL = rL;
  1529. }
  1530. // Initialise the result array with zeros.
  1531. r = [];
  1532. rL = xdL + ydL;
  1533. for (i = rL; i--;) r.push(0);
  1534. // Multiply!
  1535. for (i = ydL; --i >= 0;) {
  1536. carry = 0;
  1537. for (k = xdL + i; k > i;) {
  1538. t = r[k] + yd[i] * xd[k - i - 1] + carry;
  1539. r[k--] = t % BASE | 0;
  1540. carry = t / BASE | 0;
  1541. }
  1542. r[k] = (r[k] + carry) % BASE | 0;
  1543. }
  1544. // Remove trailing zeros.
  1545. for (; !r[--rL];) r.pop();
  1546. if (carry) ++e;
  1547. else r.shift();
  1548. y.d = r;
  1549. y.e = getBase10Exponent(r, e);
  1550. return external ? finalise(y, Ctor.precision, Ctor.rounding) : y;
  1551. };
  1552. /*
  1553. * Return a string representing the value of this Decimal in base 2, round to `sd` significant
  1554. * digits using rounding mode `rm`.
  1555. *
  1556. * If the optional `sd` argument is present then return binary exponential notation.
  1557. *
  1558. * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
  1559. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  1560. *
  1561. */
  1562. P.toBinary = function (sd, rm) {
  1563. return toStringBinary(this, 2, sd, rm);
  1564. };
  1565. /*
  1566. * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp`
  1567. * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted.
  1568. *
  1569. * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal.
  1570. *
  1571. * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
  1572. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  1573. *
  1574. */
  1575. P.toDecimalPlaces = P.toDP = function (dp, rm) {
  1576. var x = this,
  1577. Ctor = x.constructor;
  1578. x = new Ctor(x);
  1579. if (dp === void 0) return x;
  1580. checkInt32(dp, 0, MAX_DIGITS);
  1581. if (rm === void 0) rm = Ctor.rounding;
  1582. else checkInt32(rm, 0, 8);
  1583. return finalise(x, dp + x.e + 1, rm);
  1584. };
  1585. /*
  1586. * Return a string representing the value of this Decimal in exponential notation rounded to
  1587. * `dp` fixed decimal places using rounding mode `rounding`.
  1588. *
  1589. * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
  1590. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  1591. *
  1592. */
  1593. P.toExponential = function (dp, rm) {
  1594. var str,
  1595. x = this,
  1596. Ctor = x.constructor;
  1597. if (dp === void 0) {
  1598. str = finiteToString(x, true);
  1599. } else {
  1600. checkInt32(dp, 0, MAX_DIGITS);
  1601. if (rm === void 0) rm = Ctor.rounding;
  1602. else checkInt32(rm, 0, 8);
  1603. x = finalise(new Ctor(x), dp + 1, rm);
  1604. str = finiteToString(x, true, dp + 1);
  1605. }
  1606. return x.isNeg() && !x.isZero() ? '-' + str : str;
  1607. };
  1608. /*
  1609. * Return a string representing the value of this Decimal in normal (fixed-point) notation to
  1610. * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is
  1611. * omitted.
  1612. *
  1613. * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'.
  1614. *
  1615. * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
  1616. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  1617. *
  1618. * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'.
  1619. * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'.
  1620. * (-0).toFixed(3) is '0.000'.
  1621. * (-0.5).toFixed(0) is '-0'.
  1622. *
  1623. */
  1624. P.toFixed = function (dp, rm) {
  1625. var str, y,
  1626. x = this,
  1627. Ctor = x.constructor;
  1628. if (dp === void 0) {
  1629. str = finiteToString(x);
  1630. } else {
  1631. checkInt32(dp, 0, MAX_DIGITS);
  1632. if (rm === void 0) rm = Ctor.rounding;
  1633. else checkInt32(rm, 0, 8);
  1634. y = finalise(new Ctor(x), dp + x.e + 1, rm);
  1635. str = finiteToString(y, false, dp + y.e + 1);
  1636. }
  1637. // To determine whether to add the minus sign look at the value before it was rounded,
  1638. // i.e. look at `x` rather than `y`.
  1639. return x.isNeg() && !x.isZero() ? '-' + str : str;
  1640. };
  1641. /*
  1642. * Return an array representing the value of this Decimal as a simple fraction with an integer
  1643. * numerator and an integer denominator.
  1644. *
  1645. * The denominator will be a positive non-zero value less than or equal to the specified maximum
  1646. * denominator. If a maximum denominator is not specified, the denominator will be the lowest
  1647. * value necessary to represent the number exactly.
  1648. *
  1649. * [maxD] {number|string|Decimal} Maximum denominator. Integer >= 1 and < Infinity.
  1650. *
  1651. */
  1652. P.toFraction = function (maxD) {
  1653. var d, d0, d1, d2, e, k, n, n0, n1, pr, q, r,
  1654. x = this,
  1655. xd = x.d,
  1656. Ctor = x.constructor;
  1657. if (!xd) return new Ctor(x);
  1658. n1 = d0 = new Ctor(1);
  1659. d1 = n0 = new Ctor(0);
  1660. d = new Ctor(d1);
  1661. e = d.e = getPrecision(xd) - x.e - 1;
  1662. k = e % LOG_BASE;
  1663. d.d[0] = mathpow(10, k < 0 ? LOG_BASE + k : k);
  1664. if (maxD == null) {
  1665. // d is 10**e, the minimum max-denominator needed.
  1666. maxD = e > 0 ? d : n1;
  1667. } else {
  1668. n = new Ctor(maxD);
  1669. if (!n.isInt() || n.lt(n1)) throw Error(invalidArgument + n);
  1670. maxD = n.gt(d) ? (e > 0 ? d : n1) : n;
  1671. }
  1672. external = false;
  1673. n = new Ctor(digitsToString(xd));
  1674. pr = Ctor.precision;
  1675. Ctor.precision = e = xd.length * LOG_BASE * 2;
  1676. for (;;) {
  1677. q = divide(n, d, 0, 1, 1);
  1678. d2 = d0.plus(q.times(d1));
  1679. if (d2.cmp(maxD) == 1) break;
  1680. d0 = d1;
  1681. d1 = d2;
  1682. d2 = n1;
  1683. n1 = n0.plus(q.times(d2));
  1684. n0 = d2;
  1685. d2 = d;
  1686. d = n.minus(q.times(d2));
  1687. n = d2;
  1688. }
  1689. d2 = divide(maxD.minus(d0), d1, 0, 1, 1);
  1690. n0 = n0.plus(d2.times(n1));
  1691. d0 = d0.plus(d2.times(d1));
  1692. n0.s = n1.s = x.s;
  1693. // Determine which fraction is closer to x, n0/d0 or n1/d1?
  1694. r = divide(n1, d1, e, 1).minus(x).abs().cmp(divide(n0, d0, e, 1).minus(x).abs()) < 1
  1695. ? [n1, d1] : [n0, d0];
  1696. Ctor.precision = pr;
  1697. external = true;
  1698. return r;
  1699. };
  1700. /*
  1701. * Return a string representing the value of this Decimal in base 16, round to `sd` significant
  1702. * digits using rounding mode `rm`.
  1703. *
  1704. * If the optional `sd` argument is present then return binary exponential notation.
  1705. *
  1706. * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
  1707. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  1708. *
  1709. */
  1710. P.toHexadecimal = P.toHex = function (sd, rm) {
  1711. return toStringBinary(this, 16, sd, rm);
  1712. };
  1713. /*
  1714. * Returns a new Decimal whose value is the nearest multiple of `y` in the direction of rounding
  1715. * mode `rm`, or `Decimal.rounding` if `rm` is omitted, to the value of this Decimal.
  1716. *
  1717. * The return value will always have the same sign as this Decimal, unless either this Decimal
  1718. * or `y` is NaN, in which case the return value will be also be NaN.
  1719. *
  1720. * The return value is not affected by the value of `precision`.
  1721. *
  1722. * y {number|string|Decimal} The magnitude to round to a multiple of.
  1723. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  1724. *
  1725. * 'toNearest() rounding mode not an integer: {rm}'
  1726. * 'toNearest() rounding mode out of range: {rm}'
  1727. *
  1728. */
  1729. P.toNearest = function (y, rm) {
  1730. var x = this,
  1731. Ctor = x.constructor;
  1732. x = new Ctor(x);
  1733. if (y == null) {
  1734. // If x is not finite, return x.
  1735. if (!x.d) return x;
  1736. y = new Ctor(1);
  1737. rm = Ctor.rounding;
  1738. } else {
  1739. y = new Ctor(y);
  1740. if (rm === void 0) {
  1741. rm = Ctor.rounding;
  1742. } else {
  1743. checkInt32(rm, 0, 8);
  1744. }
  1745. // If x is not finite, return x if y is not NaN, else NaN.
  1746. if (!x.d) return y.s ? x : y;
  1747. // If y is not finite, return Infinity with the sign of x if y is Infinity, else NaN.
  1748. if (!y.d) {
  1749. if (y.s) y.s = x.s;
  1750. return y;
  1751. }
  1752. }
  1753. // If y is not zero, calculate the nearest multiple of y to x.
  1754. if (y.d[0]) {
  1755. external = false;
  1756. x = divide(x, y, 0, rm, 1).times(y);
  1757. external = true;
  1758. finalise(x);
  1759. // If y is zero, return zero with the sign of x.
  1760. } else {
  1761. y.s = x.s;
  1762. x = y;
  1763. }
  1764. return x;
  1765. };
  1766. /*
  1767. * Return the value of this Decimal converted to a number primitive.
  1768. * Zero keeps its sign.
  1769. *
  1770. */
  1771. P.toNumber = function () {
  1772. return +this;
  1773. };
  1774. /*
  1775. * Return a string representing the value of this Decimal in base 8, round to `sd` significant
  1776. * digits using rounding mode `rm`.
  1777. *
  1778. * If the optional `sd` argument is present then return binary exponential notation.
  1779. *
  1780. * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
  1781. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  1782. *
  1783. */
  1784. P.toOctal = function (sd, rm) {
  1785. return toStringBinary(this, 8, sd, rm);
  1786. };
  1787. /*
  1788. * Return a new Decimal whose value is the value of this Decimal raised to the power `y`, rounded
  1789. * to `precision` significant digits using rounding mode `rounding`.
  1790. *
  1791. * ECMAScript compliant.
  1792. *
  1793. * pow(x, NaN) = NaN
  1794. * pow(x, ±0) = 1
  1795. * pow(NaN, non-zero) = NaN
  1796. * pow(abs(x) > 1, +Infinity) = +Infinity
  1797. * pow(abs(x) > 1, -Infinity) = +0
  1798. * pow(abs(x) == 1, ±Infinity) = NaN
  1799. * pow(abs(x) < 1, +Infinity) = +0
  1800. * pow(abs(x) < 1, -Infinity) = +Infinity
  1801. * pow(+Infinity, y > 0) = +Infinity
  1802. * pow(+Infinity, y < 0) = +0
  1803. * pow(-Infinity, odd integer > 0) = -Infinity
  1804. * pow(-Infinity, even integer > 0) = +Infinity
  1805. * pow(-Infinity, odd integer < 0) = -0
  1806. * pow(-Infinity, even integer < 0) = +0
  1807. * pow(+0, y > 0) = +0
  1808. * pow(+0, y < 0) = +Infinity
  1809. * pow(-0, odd integer > 0) = -0
  1810. * pow(-0, even integer > 0) = +0
  1811. * pow(-0, odd integer < 0) = -Infinity
  1812. * pow(-0, even integer < 0) = +Infinity
  1813. * pow(finite x < 0, finite non-integer) = NaN
  1814. *
  1815. * For non-integer or very large exponents pow(x, y) is calculated using
  1816. *
  1817. * x^y = exp(y*ln(x))
  1818. *
  1819. * Assuming the first 15 rounding digits are each equally likely to be any digit 0-9, the
  1820. * probability of an incorrectly rounded result
  1821. * P([49]9{14} | [50]0{14}) = 2 * 0.2 * 10^-14 = 4e-15 = 1/2.5e+14
  1822. * i.e. 1 in 250,000,000,000,000
  1823. *
  1824. * If a result is incorrectly rounded the maximum error will be 1 ulp (unit in last place).
  1825. *
  1826. * y {number|string|Decimal} The power to which to raise this Decimal.
  1827. *
  1828. */
  1829. P.toPower = P.pow = function (y) {
  1830. var e, k, pr, r, rm, s,
  1831. x = this,
  1832. Ctor = x.constructor,
  1833. yn = +(y = new Ctor(y));
  1834. // Either ±Infinity, NaN or ±0?
  1835. if (!x.d || !y.d || !x.d[0] || !y.d[0]) return new Ctor(mathpow(+x, yn));
  1836. x = new Ctor(x);
  1837. if (x.eq(1)) return x;
  1838. pr = Ctor.precision;
  1839. rm = Ctor.rounding;
  1840. if (y.eq(1)) return finalise(x, pr, rm);
  1841. // y exponent
  1842. e = mathfloor(y.e / LOG_BASE);
  1843. // If y is a small integer use the 'exponentiation by squaring' algorithm.
  1844. if (e >= y.d.length - 1 && (k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) {
  1845. r = intPow(Ctor, x, k, pr);
  1846. return y.s < 0 ? new Ctor(1).div(r) : finalise(r, pr, rm);
  1847. }
  1848. s = x.s;
  1849. // if x is negative
  1850. if (s < 0) {
  1851. // if y is not an integer
  1852. if (e < y.d.length - 1) return new Ctor(NaN);
  1853. // Result is positive if x is negative and the last digit of integer y is even.
  1854. if ((y.d[e] & 1) == 0) s = 1;
  1855. // if x.eq(-1)
  1856. if (x.e == 0 && x.d[0] == 1 && x.d.length == 1) {
  1857. x.s = s;
  1858. return x;
  1859. }
  1860. }
  1861. // Estimate result exponent.
  1862. // x^y = 10^e, where e = y * log10(x)
  1863. // log10(x) = log10(x_significand) + x_exponent
  1864. // log10(x_significand) = ln(x_significand) / ln(10)
  1865. k = mathpow(+x, yn);
  1866. e = k == 0 || !isFinite(k)
  1867. ? mathfloor(yn * (Math.log('0.' + digitsToString(x.d)) / Math.LN10 + x.e + 1))
  1868. : new Ctor(k + '').e;
  1869. // Exponent estimate may be incorrect e.g. x: 0.999999999999999999, y: 2.29, e: 0, r.e: -1.
  1870. // Overflow/underflow?
  1871. if (e > Ctor.maxE + 1 || e < Ctor.minE - 1) return new Ctor(e > 0 ? s / 0 : 0);
  1872. external = false;
  1873. Ctor.rounding = x.s = 1;
  1874. // Estimate the extra guard digits needed to ensure five correct rounding digits from
  1875. // naturalLogarithm(x). Example of failure without these extra digits (precision: 10):
  1876. // new Decimal(2.32456).pow('2087987436534566.46411')
  1877. // should be 1.162377823e+764914905173815, but is 1.162355823e+764914905173815
  1878. k = Math.min(12, (e + '').length);
  1879. // r = x^y = exp(y*ln(x))
  1880. r = naturalExponential(y.times(naturalLogarithm(x, pr + k)), pr);
  1881. // r may be Infinity, e.g. (0.9999999999999999).pow(-1e+40)
  1882. if (r.d) {
  1883. // Truncate to the required precision plus five rounding digits.
  1884. r = finalise(r, pr + 5, 1);
  1885. // If the rounding digits are [49]9999 or [50]0000 increase the precision by 10 and recalculate
  1886. // the result.
  1887. if (checkRoundingDigits(r.d, pr, rm)) {
  1888. e = pr + 10;
  1889. // Truncate to the increased precision plus five rounding digits.
  1890. r = finalise(naturalExponential(y.times(naturalLogarithm(x, e + k)), e), e + 5, 1);
  1891. // Check for 14 nines from the 2nd rounding digit (the first rounding digit may be 4 or 9).
  1892. if (+digitsToString(r.d).slice(pr + 1, pr + 15) + 1 == 1e14) {
  1893. r = finalise(r, pr + 1, 0);
  1894. }
  1895. }
  1896. }
  1897. r.s = s;
  1898. external = true;
  1899. Ctor.rounding = rm;
  1900. return finalise(r, pr, rm);
  1901. };
  1902. /*
  1903. * Return a string representing the value of this Decimal rounded to `sd` significant digits
  1904. * using rounding mode `rounding`.
  1905. *
  1906. * Return exponential notation if `sd` is less than the number of digits necessary to represent
  1907. * the integer part of the value in normal notation.
  1908. *
  1909. * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
  1910. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  1911. *
  1912. */
  1913. P.toPrecision = function (sd, rm) {
  1914. var str,
  1915. x = this,
  1916. Ctor = x.constructor;
  1917. if (sd === void 0) {
  1918. str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
  1919. } else {
  1920. checkInt32(sd, 1, MAX_DIGITS);
  1921. if (rm === void 0) rm = Ctor.rounding;
  1922. else checkInt32(rm, 0, 8);
  1923. x = finalise(new Ctor(x), sd, rm);
  1924. str = finiteToString(x, sd <= x.e || x.e <= Ctor.toExpNeg, sd);
  1925. }
  1926. return x.isNeg() && !x.isZero() ? '-' + str : str;
  1927. };
  1928. /*
  1929. * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd`
  1930. * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if
  1931. * omitted.
  1932. *
  1933. * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
  1934. * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  1935. *
  1936. * 'toSD() digits out of range: {sd}'
  1937. * 'toSD() digits not an integer: {sd}'
  1938. * 'toSD() rounding mode not an integer: {rm}'
  1939. * 'toSD() rounding mode out of range: {rm}'
  1940. *
  1941. */
  1942. P.toSignificantDigits = P.toSD = function (sd, rm) {
  1943. var x = this,
  1944. Ctor = x.constructor;
  1945. if (sd === void 0) {
  1946. sd = Ctor.precision;
  1947. rm = Ctor.rounding;
  1948. } else {
  1949. checkInt32(sd, 1, MAX_DIGITS);
  1950. if (rm === void 0) rm = Ctor.rounding;
  1951. else checkInt32(rm, 0, 8);
  1952. }
  1953. return finalise(new Ctor(x), sd, rm);
  1954. };
  1955. /*
  1956. * Return a string representing the value of this Decimal.
  1957. *
  1958. * Return exponential notation if this Decimal has a positive exponent equal to or greater than
  1959. * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`.
  1960. *
  1961. */
  1962. P.toString = function () {
  1963. var x = this,
  1964. Ctor = x.constructor,
  1965. str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
  1966. return x.isNeg() && !x.isZero() ? '-' + str : str;
  1967. };
  1968. /*
  1969. * Return a new Decimal whose value is the value of this Decimal truncated to a whole number.
  1970. *
  1971. */
  1972. P.truncated = P.trunc = function () {
  1973. return finalise(new this.constructor(this), this.e + 1, 1);
  1974. };
  1975. /*
  1976. * Return a string representing the value of this Decimal.
  1977. * Unlike `toString`, negative zero will include the minus sign.
  1978. *
  1979. */
  1980. P.valueOf = P.toJSON = function () {
  1981. var x = this,
  1982. Ctor = x.constructor,
  1983. str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
  1984. return x.isNeg() ? '-' + str : str;
  1985. };
  1986. /*
  1987. // Add aliases to match BigDecimal method names.
  1988. // P.add = P.plus;
  1989. P.subtract = P.minus;
  1990. P.multiply = P.times;
  1991. P.divide = P.div;
  1992. P.remainder = P.mod;
  1993. P.compareTo = P.cmp;
  1994. P.negate = P.neg;
  1995. */
  1996. // Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers.
  1997. /*
  1998. * digitsToString P.cubeRoot, P.logarithm, P.squareRoot, P.toFraction, P.toPower,
  1999. * finiteToString, naturalExponential, naturalLogarithm
  2000. * checkInt32 P.toDecimalPlaces, P.toExponential, P.toFixed, P.toNearest,
  2001. * P.toPrecision, P.toSignificantDigits, toStringBinary, random
  2002. * checkRoundingDigits P.logarithm, P.toPower, naturalExponential, naturalLogarithm
  2003. * convertBase toStringBinary, parseOther
  2004. * cos P.cos
  2005. * divide P.atanh, P.cubeRoot, P.dividedBy, P.dividedToIntegerBy,
  2006. * P.logarithm, P.modulo, P.squareRoot, P.tan, P.tanh, P.toFraction,
  2007. * P.toNearest, toStringBinary, naturalExponential, naturalLogarithm,
  2008. * taylorSeries, atan2, parseOther
  2009. * finalise P.absoluteValue, P.atan, P.atanh, P.ceil, P.cos, P.cosh,
  2010. * P.cubeRoot, P.dividedToIntegerBy, P.floor, P.logarithm, P.minus,
  2011. * P.modulo, P.negated, P.plus, P.round, P.sin, P.sinh, P.squareRoot,
  2012. * P.tan, P.times, P.toDecimalPlaces, P.toExponential, P.toFixed,
  2013. * P.toNearest, P.toPower, P.toPrecision, P.toSignificantDigits,
  2014. * P.truncated, divide, getLn10, getPi, naturalExponential,
  2015. * naturalLogarithm, ceil, floor, round, trunc
  2016. * finiteToString P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf,
  2017. * toStringBinary
  2018. * getBase10Exponent P.minus, P.plus, P.times, parseOther
  2019. * getLn10 P.logarithm, naturalLogarithm
  2020. * getPi P.acos, P.asin, P.atan, toLessThanHalfPi, atan2
  2021. * getPrecision P.precision, P.toFraction
  2022. * getZeroString digitsToString, finiteToString
  2023. * intPow P.toPower, parseOther
  2024. * isOdd toLessThanHalfPi
  2025. * maxOrMin max, min
  2026. * naturalExponential P.naturalExponential, P.toPower
  2027. * naturalLogarithm P.acosh, P.asinh, P.atanh, P.logarithm, P.naturalLogarithm,
  2028. * P.toPower, naturalExponential
  2029. * nonFiniteToString finiteToString, toStringBinary
  2030. * parseDecimal Decimal
  2031. * parseOther Decimal
  2032. * sin P.sin
  2033. * taylorSeries P.cosh, P.sinh, cos, sin
  2034. * toLessThanHalfPi P.cos, P.sin
  2035. * toStringBinary P.toBinary, P.toHexadecimal, P.toOctal
  2036. * truncate intPow
  2037. *
  2038. * Throws: P.logarithm, P.precision, P.toFraction, checkInt32, getLn10, getPi,
  2039. * naturalLogarithm, config, parseOther, random, Decimal
  2040. */
  2041. function digitsToString(d) {
  2042. var i, k, ws,
  2043. indexOfLastWord = d.length - 1,
  2044. str = '',
  2045. w = d[0];
  2046. if (indexOfLastWord > 0) {
  2047. str += w;
  2048. for (i = 1; i < indexOfLastWord; i++) {
  2049. ws = d[i] + '';
  2050. k = LOG_BASE - ws.length;
  2051. if (k) str += getZeroString(k);
  2052. str += ws;
  2053. }
  2054. w = d[i];
  2055. ws = w + '';
  2056. k = LOG_BASE - ws.length;
  2057. if (k) str += getZeroString(k);
  2058. } else if (w === 0) {
  2059. return '0';
  2060. }
  2061. // Remove trailing zeros of last w.
  2062. for (; w % 10 === 0;) w /= 10;
  2063. return str + w;
  2064. }
  2065. function checkInt32(i, min, max) {
  2066. if (i !== ~~i || i < min || i > max) {
  2067. throw Error(invalidArgument + i);
  2068. }
  2069. }
  2070. /*
  2071. * Check 5 rounding digits if `repeating` is null, 4 otherwise.
  2072. * `repeating == null` if caller is `log` or `pow`,
  2073. * `repeating != null` if caller is `naturalLogarithm` or `naturalExponential`.
  2074. */
  2075. function checkRoundingDigits(d, i, rm, repeating) {
  2076. var di, k, r, rd;
  2077. // Get the length of the first word of the array d.
  2078. for (k = d[0]; k >= 10; k /= 10) --i;
  2079. // Is the rounding digit in the first word of d?
  2080. if (--i < 0) {
  2081. i += LOG_BASE;
  2082. di = 0;
  2083. } else {
  2084. di = Math.ceil((i + 1) / LOG_BASE);
  2085. i %= LOG_BASE;
  2086. }
  2087. // i is the index (0 - 6) of the rounding digit.
  2088. // E.g. if within the word 3487563 the first rounding digit is 5,
  2089. // then i = 4, k = 1000, rd = 3487563 % 1000 = 563
  2090. k = mathpow(10, LOG_BASE - i);
  2091. rd = d[di] % k | 0;
  2092. if (repeating == null) {
  2093. if (i < 3) {
  2094. if (i == 0) rd = rd / 100 | 0;
  2095. else if (i == 1) rd = rd / 10 | 0;
  2096. r = rm < 4 && rd == 99999 || rm > 3 && rd == 49999 || rd == 50000 || rd == 0;
  2097. } else {
  2098. r = (rm < 4 && rd + 1 == k || rm > 3 && rd + 1 == k / 2) &&
  2099. (d[di + 1] / k / 100 | 0) == mathpow(10, i - 2) - 1 ||
  2100. (rd == k / 2 || rd == 0) && (d[di + 1] / k / 100 | 0) == 0;
  2101. }
  2102. } else {
  2103. if (i < 4) {
  2104. if (i == 0) rd = rd / 1000 | 0;
  2105. else if (i == 1) rd = rd / 100 | 0;
  2106. else if (i == 2) rd = rd / 10 | 0;
  2107. r = (repeating || rm < 4) && rd == 9999 || !repeating && rm > 3 && rd == 4999;
  2108. } else {
  2109. r = ((repeating || rm < 4) && rd + 1 == k ||
  2110. (!repeating && rm > 3) && rd + 1 == k / 2) &&
  2111. (d[di + 1] / k / 1000 | 0) == mathpow(10, i - 3) - 1;
  2112. }
  2113. }
  2114. return r;
  2115. }
  2116. // Convert string of `baseIn` to an array of numbers of `baseOut`.
  2117. // Eg. convertBase('255', 10, 16) returns [15, 15].
  2118. // Eg. convertBase('ff', 16, 10) returns [2, 5, 5].
  2119. function convertBase(str, baseIn, baseOut) {
  2120. var j,
  2121. arr = [0],
  2122. arrL,
  2123. i = 0,
  2124. strL = str.length;
  2125. for (; i < strL;) {
  2126. for (arrL = arr.length; arrL--;) arr[arrL] *= baseIn;
  2127. arr[0] += NUMERALS.indexOf(str.charAt(i++));
  2128. for (j = 0; j < arr.length; j++) {
  2129. if (arr[j] > baseOut - 1) {
  2130. if (arr[j + 1] === void 0) arr[j + 1] = 0;
  2131. arr[j + 1] += arr[j] / baseOut | 0;
  2132. arr[j] %= baseOut;
  2133. }
  2134. }
  2135. }
  2136. return arr.reverse();
  2137. }
  2138. /*
  2139. * cos(x) = 1 - x^2/2! + x^4/4! - ...
  2140. * |x| < pi/2
  2141. *
  2142. */
  2143. function cosine(Ctor, x) {
  2144. var k, y,
  2145. len = x.d.length;
  2146. // Argument reduction: cos(4x) = 8*(cos^4(x) - cos^2(x)) + 1
  2147. // i.e. cos(x) = 8*(cos^4(x/4) - cos^2(x/4)) + 1
  2148. // Estimate the optimum number of times to use the argument reduction.
  2149. if (len < 32) {
  2150. k = Math.ceil(len / 3);
  2151. y = (1 / tinyPow(4, k)).toString();
  2152. } else {
  2153. k = 16;
  2154. y = '2.3283064365386962890625e-10';
  2155. }
  2156. Ctor.precision += k;
  2157. x = taylorSeries(Ctor, 1, x.times(y), new Ctor(1));
  2158. // Reverse argument reduction
  2159. for (var i = k; i--;) {
  2160. var cos2x = x.times(x);
  2161. x = cos2x.times(cos2x).minus(cos2x).times(8).plus(1);
  2162. }
  2163. Ctor.precision -= k;
  2164. return x;
  2165. }
  2166. /*
  2167. * Perform division in the specified base.
  2168. */
  2169. var divide = (function () {
  2170. // Assumes non-zero x and k, and hence non-zero result.
  2171. function multiplyInteger(x, k, base) {
  2172. var temp,
  2173. carry = 0,
  2174. i = x.length;
  2175. for (x = x.slice(); i--;) {
  2176. temp = x[i] * k + carry;
  2177. x[i] = temp % base | 0;
  2178. carry = temp / base | 0;
  2179. }
  2180. if (carry) x.unshift(carry);
  2181. return x;
  2182. }
  2183. function compare(a, b, aL, bL) {
  2184. var i, r;
  2185. if (aL != bL) {
  2186. r = aL > bL ? 1 : -1;
  2187. } else {
  2188. for (i = r = 0; i < aL; i++) {
  2189. if (a[i] != b[i]) {
  2190. r = a[i] > b[i] ? 1 : -1;
  2191. break;
  2192. }
  2193. }
  2194. }
  2195. return r;
  2196. }
  2197. function subtract(a, b, aL, base) {
  2198. var i = 0;
  2199. // Subtract b from a.
  2200. for (; aL--;) {
  2201. a[aL] -= i;
  2202. i = a[aL] < b[aL] ? 1 : 0;
  2203. a[aL] = i * base + a[aL] - b[aL];
  2204. }
  2205. // Remove leading zeros.
  2206. for (; !a[0] && a.length > 1;) a.shift();
  2207. }
  2208. return function (x, y, pr, rm, dp, base) {
  2209. var cmp, e, i, k, logBase, more, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0,
  2210. yL, yz,
  2211. Ctor = x.constructor,
  2212. sign = x.s == y.s ? 1 : -1,
  2213. xd = x.d,
  2214. yd = y.d;
  2215. // Either NaN, Infinity or 0?
  2216. if (!xd || !xd[0] || !yd || !yd[0]) {
  2217. return new Ctor(// Return NaN if either NaN, or both Infinity or 0.
  2218. !x.s || !y.s || (xd ? yd && xd[0] == yd[0] : !yd) ? NaN :
  2219. // Return ±0 if x is 0 or y is ±Infinity, or return ±Infinity as y is 0.
  2220. xd && xd[0] == 0 || !yd ? sign * 0 : sign / 0);
  2221. }
  2222. if (base) {
  2223. logBase = 1;
  2224. e = x.e - y.e;
  2225. } else {
  2226. base = BASE;
  2227. logBase = LOG_BASE;
  2228. e = mathfloor(x.e / logBase) - mathfloor(y.e / logBase);
  2229. }
  2230. yL = yd.length;
  2231. xL = xd.length;
  2232. q = new Ctor(sign);
  2233. qd = q.d = [];
  2234. // Result exponent may be one less than e.
  2235. // The digit array of a Decimal from toStringBinary may have trailing zeros.
  2236. for (i = 0; yd[i] == (xd[i] || 0); i++);
  2237. if (yd[i] > (xd[i] || 0)) e--;
  2238. if (pr == null) {
  2239. sd = pr = Ctor.precision;
  2240. rm = Ctor.rounding;
  2241. } else if (dp) {
  2242. sd = pr + (x.e - y.e) + 1;
  2243. } else {
  2244. sd = pr;
  2245. }
  2246. if (sd < 0) {
  2247. qd.push(1);
  2248. more = true;
  2249. } else {
  2250. // Convert precision in number of base 10 digits to base 1e7 digits.
  2251. sd = sd / logBase + 2 | 0;
  2252. i = 0;
  2253. // divisor < 1e7
  2254. if (yL == 1) {
  2255. k = 0;
  2256. yd = yd[0];
  2257. sd++;
  2258. // k is the carry.
  2259. for (; (i < xL || k) && sd--; i++) {
  2260. t = k * base + (xd[i] || 0);
  2261. qd[i] = t / yd | 0;
  2262. k = t % yd | 0;
  2263. }
  2264. more = k || i < xL;
  2265. // divisor >= 1e7
  2266. } else {
  2267. // Normalise xd and yd so highest order digit of yd is >= base/2
  2268. k = base / (yd[0] + 1) | 0;
  2269. if (k > 1) {
  2270. yd = multiplyInteger(yd, k, base);
  2271. xd = multiplyInteger(xd, k, base);
  2272. yL = yd.length;
  2273. xL = xd.length;
  2274. }
  2275. xi = yL;
  2276. rem = xd.slice(0, yL);
  2277. remL = rem.length;
  2278. // Add zeros to make remainder as long as divisor.
  2279. for (; remL < yL;) rem[remL++] = 0;
  2280. yz = yd.slice();
  2281. yz.unshift(0);
  2282. yd0 = yd[0];
  2283. if (yd[1] >= base / 2) ++yd0;
  2284. do {
  2285. k = 0;
  2286. // Compare divisor and remainder.
  2287. cmp = compare(yd, rem, yL, remL);
  2288. // If divisor < remainder.
  2289. if (cmp < 0) {
  2290. // Calculate trial digit, k.
  2291. rem0 = rem[0];
  2292. if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);
  2293. // k will be how many times the divisor goes into the current remainder.
  2294. k = rem0 / yd0 | 0;
  2295. // Algorithm:
  2296. // 1. product = divisor * trial digit (k)
  2297. // 2. if product > remainder: product -= divisor, k--
  2298. // 3. remainder -= product
  2299. // 4. if product was < remainder at 2:
  2300. // 5. compare new remainder and divisor
  2301. // 6. If remainder > divisor: remainder -= divisor, k++
  2302. if (k > 1) {
  2303. if (k >= base) k = base - 1;
  2304. // product = divisor * trial digit.
  2305. prod = multiplyInteger(yd, k, base);
  2306. prodL = prod.length;
  2307. remL = rem.length;
  2308. // Compare product and remainder.
  2309. cmp = compare(prod, rem, prodL, remL);
  2310. // product > remainder.
  2311. if (cmp == 1) {
  2312. k--;
  2313. // Subtract divisor from product.
  2314. subtract(prod, yL < prodL ? yz : yd, prodL, base);
  2315. }
  2316. } else {
  2317. // cmp is -1.
  2318. // If k is 0, there is no need to compare yd and rem again below, so change cmp to 1
  2319. // to avoid it. If k is 1 there is a need to compare yd and rem again below.
  2320. if (k == 0) cmp = k = 1;
  2321. prod = yd.slice();
  2322. }
  2323. prodL = prod.length;
  2324. if (prodL < remL) prod.unshift(0);
  2325. // Subtract product from remainder.
  2326. subtract(rem, prod, remL, base);
  2327. // If product was < previous remainder.
  2328. if (cmp == -1) {
  2329. remL = rem.length;
  2330. // Compare divisor and new remainder.
  2331. cmp = compare(yd, rem, yL, remL);
  2332. // If divisor < new remainder, subtract divisor from remainder.
  2333. if (cmp < 1) {
  2334. k++;
  2335. // Subtract divisor from remainder.
  2336. subtract(rem, yL < remL ? yz : yd, remL, base);
  2337. }
  2338. }
  2339. remL = rem.length;
  2340. } else if (cmp === 0) {
  2341. k++;
  2342. rem = [0];
  2343. } // if cmp === 1, k will be 0
  2344. // Add the next digit, k, to the result array.
  2345. qd[i++] = k;
  2346. // Update the remainder.
  2347. if (cmp && rem[0]) {
  2348. rem[remL++] = xd[xi] || 0;
  2349. } else {
  2350. rem = [xd[xi]];
  2351. remL = 1;
  2352. }
  2353. } while ((xi++ < xL || rem[0] !== void 0) && sd--);
  2354. more = rem[0] !== void 0;
  2355. }
  2356. // Leading zero?
  2357. if (!qd[0]) qd.shift();
  2358. }
  2359. // logBase is 1 when divide is being used for base conversion.
  2360. if (logBase == 1) {
  2361. q.e = e;
  2362. inexact = more;
  2363. } else {
  2364. // To calculate q.e, first get the number of digits of qd[0].
  2365. for (i = 1, k = qd[0]; k >= 10; k /= 10) i++;
  2366. q.e = i + e * logBase - 1;
  2367. finalise(q, dp ? pr + q.e + 1 : pr, rm, more);
  2368. }
  2369. return q;
  2370. };
  2371. })();
  2372. /*
  2373. * Round `x` to `sd` significant digits using rounding mode `rm`.
  2374. * Check for over/under-flow.
  2375. */
  2376. function finalise(x, sd, rm, isTruncated) {
  2377. var digits, i, j, k, rd, roundUp, w, xd, xdi,
  2378. Ctor = x.constructor;
  2379. // Don't round if sd is null or undefined.
  2380. out: if (sd != null) {
  2381. xd = x.d;
  2382. // Infinity/NaN.
  2383. if (!xd) return x;
  2384. // rd: the rounding digit, i.e. the digit after the digit that may be rounded up.
  2385. // w: the word of xd containing rd, a base 1e7 number.
  2386. // xdi: the index of w within xd.
  2387. // digits: the number of digits of w.
  2388. // i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if
  2389. // they had leading zeros)
  2390. // j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero).
  2391. // Get the length of the first word of the digits array xd.
  2392. for (digits = 1, k = xd[0]; k >= 10; k /= 10) digits++;
  2393. i = sd - digits;
  2394. // Is the rounding digit in the first word of xd?
  2395. if (i < 0) {
  2396. i += LOG_BASE;
  2397. j = sd;
  2398. w = xd[xdi = 0];
  2399. // Get the rounding digit at index j of w.
  2400. rd = w / mathpow(10, digits - j - 1) % 10 | 0;
  2401. } else {
  2402. xdi = Math.ceil((i + 1) / LOG_BASE);
  2403. k = xd.length;
  2404. if (xdi >= k) {
  2405. if (isTruncated) {
  2406. // Needed by `naturalExponential`, `naturalLogarithm` and `squareRoot`.
  2407. for (; k++ <= xdi;) xd.push(0);
  2408. w = rd = 0;
  2409. digits = 1;
  2410. i %= LOG_BASE;
  2411. j = i - LOG_BASE + 1;
  2412. } else {
  2413. break out;
  2414. }
  2415. } else {
  2416. w = k = xd[xdi];
  2417. // Get the number of digits of w.
  2418. for (digits = 1; k >= 10; k /= 10) digits++;
  2419. // Get the index of rd within w.
  2420. i %= LOG_BASE;
  2421. // Get the index of rd within w, adjusted for leading zeros.
  2422. // The number of leading zeros of w is given by LOG_BASE - digits.
  2423. j = i - LOG_BASE + digits;
  2424. // Get the rounding digit at index j of w.
  2425. rd = j < 0 ? 0 : w / mathpow(10, digits - j - 1) % 10 | 0;
  2426. }
  2427. }
  2428. // Are there any non-zero digits after the rounding digit?
  2429. isTruncated = isTruncated || sd < 0 ||
  2430. xd[xdi + 1] !== void 0 || (j < 0 ? w : w % mathpow(10, digits - j - 1));
  2431. // The expression `w % mathpow(10, digits - j - 1)` returns all the digits of w to the right
  2432. // of the digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression
  2433. // will give 714.
  2434. roundUp = rm < 4
  2435. ? (rd || isTruncated) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))
  2436. : rd > 5 || rd == 5 && (rm == 4 || isTruncated || rm == 6 &&
  2437. // Check whether the digit to the left of the rounding digit is odd.
  2438. ((i > 0 ? j > 0 ? w / mathpow(10, digits - j) : 0 : xd[xdi - 1]) % 10) & 1 ||
  2439. rm == (x.s < 0 ? 8 : 7));
  2440. if (sd < 1 || !xd[0]) {
  2441. xd.length = 0;
  2442. if (roundUp) {
  2443. // Convert sd to decimal places.
  2444. sd -= x.e + 1;
  2445. // 1, 0.1, 0.01, 0.001, 0.0001 etc.
  2446. xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE);
  2447. x.e = -sd || 0;
  2448. } else {
  2449. // Zero.
  2450. xd[0] = x.e = 0;
  2451. }
  2452. return x;
  2453. }
  2454. // Remove excess digits.
  2455. if (i == 0) {
  2456. xd.length = xdi;
  2457. k = 1;
  2458. xdi--;
  2459. } else {
  2460. xd.length = xdi + 1;
  2461. k = mathpow(10, LOG_BASE - i);
  2462. // E.g. 56700 becomes 56000 if 7 is the rounding digit.
  2463. // j > 0 means i > number of leading zeros of w.
  2464. xd[xdi] = j > 0 ? (w / mathpow(10, digits - j) % mathpow(10, j) | 0) * k : 0;
  2465. }
  2466. if (roundUp) {
  2467. for (;;) {
  2468. // Is the digit to be rounded up in the first word of xd?
  2469. if (xdi == 0) {
  2470. // i will be the length of xd[0] before k is added.
  2471. for (i = 1, j = xd[0]; j >= 10; j /= 10) i++;
  2472. j = xd[0] += k;
  2473. for (k = 1; j >= 10; j /= 10) k++;
  2474. // if i != k the length has increased.
  2475. if (i != k) {
  2476. x.e++;
  2477. if (xd[0] == BASE) xd[0] = 1;
  2478. }
  2479. break;
  2480. } else {
  2481. xd[xdi] += k;
  2482. if (xd[xdi] != BASE) break;
  2483. xd[xdi--] = 0;
  2484. k = 1;
  2485. }
  2486. }
  2487. }
  2488. // Remove trailing zeros.
  2489. for (i = xd.length; xd[--i] === 0;) xd.pop();
  2490. }
  2491. if (external) {
  2492. // Overflow?
  2493. if (x.e > Ctor.maxE) {
  2494. // Infinity.
  2495. x.d = null;
  2496. x.e = NaN;
  2497. // Underflow?
  2498. } else if (x.e < Ctor.minE) {
  2499. // Zero.
  2500. x.e = 0;
  2501. x.d = [0];
  2502. // Ctor.underflow = true;
  2503. } // else Ctor.underflow = false;
  2504. }
  2505. return x;
  2506. }
  2507. function finiteToString(x, isExp, sd) {
  2508. if (!x.isFinite()) return nonFiniteToString(x);
  2509. var k,
  2510. e = x.e,
  2511. str = digitsToString(x.d),
  2512. len = str.length;
  2513. if (isExp) {
  2514. if (sd && (k = sd - len) > 0) {
  2515. str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k);
  2516. } else if (len > 1) {
  2517. str = str.charAt(0) + '.' + str.slice(1);
  2518. }
  2519. str = str + (x.e < 0 ? 'e' : 'e+') + x.e;
  2520. } else if (e < 0) {
  2521. str = '0.' + getZeroString(-e - 1) + str;
  2522. if (sd && (k = sd - len) > 0) str += getZeroString(k);
  2523. } else if (e >= len) {
  2524. str += getZeroString(e + 1 - len);
  2525. if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k);
  2526. } else {
  2527. if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k);
  2528. if (sd && (k = sd - len) > 0) {
  2529. if (e + 1 === len) str += '.';
  2530. str += getZeroString(k);
  2531. }
  2532. }
  2533. return str;
  2534. }
  2535. // Calculate the base 10 exponent from the base 1e7 exponent.
  2536. function getBase10Exponent(digits, e) {
  2537. var w = digits[0];
  2538. // Add the number of digits of the first word of the digits array.
  2539. for ( e *= LOG_BASE; w >= 10; w /= 10) e++;
  2540. return e;
  2541. }
  2542. function getLn10(Ctor, sd, pr) {
  2543. if (sd > LN10_PRECISION) {
  2544. // Reset global state in case the exception is caught.
  2545. external = true;
  2546. if (pr) Ctor.precision = pr;
  2547. throw Error(precisionLimitExceeded);
  2548. }
  2549. return finalise(new Ctor(LN10), sd, 1, true);
  2550. }
  2551. function getPi(Ctor, sd, rm) {
  2552. if (sd > PI_PRECISION) throw Error(precisionLimitExceeded);
  2553. return finalise(new Ctor(PI), sd, rm, true);
  2554. }
  2555. function getPrecision(digits) {
  2556. var w = digits.length - 1,
  2557. len = w * LOG_BASE + 1;
  2558. w = digits[w];
  2559. // If non-zero...
  2560. if (w) {
  2561. // Subtract the number of trailing zeros of the last word.
  2562. for (; w % 10 == 0; w /= 10) len--;
  2563. // Add the number of digits of the first word.
  2564. for (w = digits[0]; w >= 10; w /= 10) len++;
  2565. }
  2566. return len;
  2567. }
  2568. function getZeroString(k) {
  2569. var zs = '';
  2570. for (; k--;) zs += '0';
  2571. return zs;
  2572. }
  2573. /*
  2574. * Return a new Decimal whose value is the value of Decimal `x` to the power `n`, where `n` is an
  2575. * integer of type number.
  2576. *
  2577. * Implements 'exponentiation by squaring'. Called by `pow` and `parseOther`.
  2578. *
  2579. */
  2580. function intPow(Ctor, x, n, pr) {
  2581. var isTruncated,
  2582. r = new Ctor(1),
  2583. // Max n of 9007199254740991 takes 53 loop iterations.
  2584. // Maximum digits array length; leaves [28, 34] guard digits.
  2585. k = Math.ceil(pr / LOG_BASE + 4);
  2586. external = false;
  2587. for (;;) {
  2588. if (n % 2) {
  2589. r = r.times(x);
  2590. if (truncate(r.d, k)) isTruncated = true;
  2591. }
  2592. n = mathfloor(n / 2);
  2593. if (n === 0) {
  2594. // To ensure correct rounding when r.d is truncated, increment the last word if it is zero.
  2595. n = r.d.length - 1;
  2596. if (isTruncated && r.d[n] === 0) ++r.d[n];
  2597. break;
  2598. }
  2599. x = x.times(x);
  2600. truncate(x.d, k);
  2601. }
  2602. external = true;
  2603. return r;
  2604. }
  2605. function isOdd(n) {
  2606. return n.d[n.d.length - 1] & 1;
  2607. }
  2608. /*
  2609. * Handle `max` and `min`. `ltgt` is 'lt' or 'gt'.
  2610. */
  2611. function maxOrMin(Ctor, args, ltgt) {
  2612. var y,
  2613. x = new Ctor(args[0]),
  2614. i = 0;
  2615. for (; ++i < args.length;) {
  2616. y = new Ctor(args[i]);
  2617. if (!y.s) {
  2618. x = y;
  2619. break;
  2620. } else if (x[ltgt](y)) {
  2621. x = y;
  2622. }
  2623. }
  2624. return x;
  2625. }
  2626. /*
  2627. * Return a new Decimal whose value is the natural exponential of `x` rounded to `sd` significant
  2628. * digits.
  2629. *
  2630. * Taylor/Maclaurin series.
  2631. *
  2632. * exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ...
  2633. *
  2634. * Argument reduction:
  2635. * Repeat x = x / 32, k += 5, until |x| < 0.1
  2636. * exp(x) = exp(x / 2^k)^(2^k)
  2637. *
  2638. * Previously, the argument was initially reduced by
  2639. * exp(x) = exp(r) * 10^k where r = x - k * ln10, k = floor(x / ln10)
  2640. * to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was
  2641. * found to be slower than just dividing repeatedly by 32 as above.
  2642. *
  2643. * Max integer argument: exp('20723265836946413') = 6.3e+9000000000000000
  2644. * Min integer argument: exp('-20723265836946411') = 1.2e-9000000000000000
  2645. * (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324)
  2646. *
  2647. * exp(Infinity) = Infinity
  2648. * exp(-Infinity) = 0
  2649. * exp(NaN) = NaN
  2650. * exp(±0) = 1
  2651. *
  2652. * exp(x) is non-terminating for any finite, non-zero x.
  2653. *
  2654. * The result will always be correctly rounded.
  2655. *
  2656. */
  2657. function naturalExponential(x, sd) {
  2658. var denominator, guard, j, pow, sum, t, wpr,
  2659. rep = 0,
  2660. i = 0,
  2661. k = 0,
  2662. Ctor = x.constructor,
  2663. rm = Ctor.rounding,
  2664. pr = Ctor.precision;
  2665. // 0/NaN/Infinity?
  2666. if (!x.d || !x.d[0] || x.e > 17) {
  2667. return new Ctor(x.d
  2668. ? !x.d[0] ? 1 : x.s < 0 ? 0 : 1 / 0
  2669. : x.s ? x.s < 0 ? 0 : x : 0 / 0);
  2670. }
  2671. if (sd == null) {
  2672. external = false;
  2673. wpr = pr;
  2674. } else {
  2675. wpr = sd;
  2676. }
  2677. t = new Ctor(0.03125);
  2678. // while abs(x) >= 0.1
  2679. while (x.e > -2) {
  2680. // x = x / 2^5
  2681. x = x.times(t);
  2682. k += 5;
  2683. }
  2684. // Use 2 * log10(2^k) + 5 (empirically derived) to estimate the increase in precision
  2685. // necessary to ensure the first 4 rounding digits are correct.
  2686. guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0;
  2687. wpr += guard;
  2688. denominator = pow = sum = new Ctor(1);
  2689. Ctor.precision = wpr;
  2690. for (;;) {
  2691. pow = finalise(pow.times(x), wpr, 1);
  2692. denominator = denominator.times(++i);
  2693. t = sum.plus(divide(pow, denominator, wpr, 1));
  2694. if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
  2695. j = k;
  2696. while (j--) sum = finalise(sum.times(sum), wpr, 1);
  2697. // Check to see if the first 4 rounding digits are [49]999.
  2698. // If so, repeat the summation with a higher precision, otherwise
  2699. // e.g. with precision: 18, rounding: 1
  2700. // exp(18.404272462595034083567793919843761) = 98372560.1229999999 (should be 98372560.123)
  2701. // `wpr - guard` is the index of first rounding digit.
  2702. if (sd == null) {
  2703. if (rep < 3 && checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {
  2704. Ctor.precision = wpr += 10;
  2705. denominator = pow = t = new Ctor(1);
  2706. i = 0;
  2707. rep++;
  2708. } else {
  2709. return finalise(sum, Ctor.precision = pr, rm, external = true);
  2710. }
  2711. } else {
  2712. Ctor.precision = pr;
  2713. return sum;
  2714. }
  2715. }
  2716. sum = t;
  2717. }
  2718. }
  2719. /*
  2720. * Return a new Decimal whose value is the natural logarithm of `x` rounded to `sd` significant
  2721. * digits.
  2722. *
  2723. * ln(-n) = NaN
  2724. * ln(0) = -Infinity
  2725. * ln(-0) = -Infinity
  2726. * ln(1) = 0
  2727. * ln(Infinity) = Infinity
  2728. * ln(-Infinity) = NaN
  2729. * ln(NaN) = NaN
  2730. *
  2731. * ln(n) (n != 1) is non-terminating.
  2732. *
  2733. */
  2734. function naturalLogarithm(y, sd) {
  2735. var c, c0, denominator, e, numerator, rep, sum, t, wpr, x1, x2,
  2736. n = 1,
  2737. guard = 10,
  2738. x = y,
  2739. xd = x.d,
  2740. Ctor = x.constructor,
  2741. rm = Ctor.rounding,
  2742. pr = Ctor.precision;
  2743. // Is x negative or Infinity, NaN, 0 or 1?
  2744. if (x.s < 0 || !xd || !xd[0] || !x.e && xd[0] == 1 && xd.length == 1) {
  2745. return new Ctor(xd && !xd[0] ? -1 / 0 : x.s != 1 ? NaN : xd ? 0 : x);
  2746. }
  2747. if (sd == null) {
  2748. external = false;
  2749. wpr = pr;
  2750. } else {
  2751. wpr = sd;
  2752. }
  2753. Ctor.precision = wpr += guard;
  2754. c = digitsToString(xd);
  2755. c0 = c.charAt(0);
  2756. if (Math.abs(e = x.e) < 1.5e15) {
  2757. // Argument reduction.
  2758. // The series converges faster the closer the argument is to 1, so using
  2759. // ln(a^b) = b * ln(a), ln(a) = ln(a^b) / b
  2760. // multiply the argument by itself until the leading digits of the significand are 7, 8, 9,
  2761. // 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can
  2762. // later be divided by this number, then separate out the power of 10 using
  2763. // ln(a*10^b) = ln(a) + b*ln(10).
  2764. // max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14).
  2765. //while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) {
  2766. // max n is 6 (gives 0.7 - 1.3)
  2767. while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) {
  2768. x = x.times(y);
  2769. c = digitsToString(x.d);
  2770. c0 = c.charAt(0);
  2771. n++;
  2772. }
  2773. e = x.e;
  2774. if (c0 > 1) {
  2775. x = new Ctor('0.' + c);
  2776. e++;
  2777. } else {
  2778. x = new Ctor(c0 + '.' + c.slice(1));
  2779. }
  2780. } else {
  2781. // The argument reduction method above may result in overflow if the argument y is a massive
  2782. // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this
  2783. // function using ln(x*10^e) = ln(x) + e*ln(10).
  2784. t = getLn10(Ctor, wpr + 2, pr).times(e + '');
  2785. x = naturalLogarithm(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t);
  2786. Ctor.precision = pr;
  2787. return sd == null ? finalise(x, pr, rm, external = true) : x;
  2788. }
  2789. // x1 is x reduced to a value near 1.
  2790. x1 = x;
  2791. // Taylor series.
  2792. // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...)
  2793. // where x = (y - 1)/(y + 1) (|x| < 1)
  2794. sum = numerator = x = divide(x.minus(1), x.plus(1), wpr, 1);
  2795. x2 = finalise(x.times(x), wpr, 1);
  2796. denominator = 3;
  2797. for (;;) {
  2798. numerator = finalise(numerator.times(x2), wpr, 1);
  2799. t = sum.plus(divide(numerator, new Ctor(denominator), wpr, 1));
  2800. if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
  2801. sum = sum.times(2);
  2802. // Reverse the argument reduction. Check that e is not 0 because, besides preventing an
  2803. // unnecessary calculation, -0 + 0 = +0 and to ensure correct rounding -0 needs to stay -0.
  2804. if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + ''));
  2805. sum = divide(sum, new Ctor(n), wpr, 1);
  2806. // Is rm > 3 and the first 4 rounding digits 4999, or rm < 4 (or the summation has
  2807. // been repeated previously) and the first 4 rounding digits 9999?
  2808. // If so, restart the summation with a higher precision, otherwise
  2809. // e.g. with precision: 12, rounding: 1
  2810. // ln(135520028.6126091714265381533) = 18.7246299999 when it should be 18.72463.
  2811. // `wpr - guard` is the index of first rounding digit.
  2812. if (sd == null) {
  2813. if (checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {
  2814. Ctor.precision = wpr += guard;
  2815. t = numerator = x = divide(x1.minus(1), x1.plus(1), wpr, 1);
  2816. x2 = finalise(x.times(x), wpr, 1);
  2817. denominator = rep = 1;
  2818. } else {
  2819. return finalise(sum, Ctor.precision = pr, rm, external = true);
  2820. }
  2821. } else {
  2822. Ctor.precision = pr;
  2823. return sum;
  2824. }
  2825. }
  2826. sum = t;
  2827. denominator += 2;
  2828. }
  2829. }
  2830. // ±Infinity, NaN.
  2831. function nonFiniteToString(x) {
  2832. // Unsigned.
  2833. return String(x.s * x.s / 0);
  2834. }
  2835. /*
  2836. * Parse the value of a new Decimal `x` from string `str`.
  2837. */
  2838. function parseDecimal(x, str) {
  2839. var e, i, len;
  2840. // Decimal point?
  2841. if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');
  2842. // Exponential form?
  2843. if ((i = str.search(/e/i)) > 0) {
  2844. // Determine exponent.
  2845. if (e < 0) e = i;
  2846. e += +str.slice(i + 1);
  2847. str = str.substring(0, i);
  2848. } else if (e < 0) {
  2849. // Integer.
  2850. e = str.length;
  2851. }
  2852. // Determine leading zeros.
  2853. for (i = 0; str.charCodeAt(i) === 48; i++);
  2854. // Determine trailing zeros.
  2855. for (len = str.length; str.charCodeAt(len - 1) === 48; --len);
  2856. str = str.slice(i, len);
  2857. if (str) {
  2858. len -= i;
  2859. x.e = e = e - i - 1;
  2860. x.d = [];
  2861. // Transform base
  2862. // e is the base 10 exponent.
  2863. // i is where to slice str to get the first word of the digits array.
  2864. i = (e + 1) % LOG_BASE;
  2865. if (e < 0) i += LOG_BASE;
  2866. if (i < len) {
  2867. if (i) x.d.push(+str.slice(0, i));
  2868. for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE));
  2869. str = str.slice(i);
  2870. i = LOG_BASE - str.length;
  2871. } else {
  2872. i -= len;
  2873. }
  2874. for (; i--;) str += '0';
  2875. x.d.push(+str);
  2876. if (external) {
  2877. // Overflow?
  2878. if (x.e > x.constructor.maxE) {
  2879. // Infinity.
  2880. x.d = null;
  2881. x.e = NaN;
  2882. // Underflow?
  2883. } else if (x.e < x.constructor.minE) {
  2884. // Zero.
  2885. x.e = 0;
  2886. x.d = [0];
  2887. // x.constructor.underflow = true;
  2888. } // else x.constructor.underflow = false;
  2889. }
  2890. } else {
  2891. // Zero.
  2892. x.e = 0;
  2893. x.d = [0];
  2894. }
  2895. return x;
  2896. }
  2897. /*
  2898. * Parse the value of a new Decimal `x` from a string `str`, which is not a decimal value.
  2899. */
  2900. function parseOther(x, str) {
  2901. var base, Ctor, divisor, i, isFloat, len, p, xd, xe;
  2902. if (str === 'Infinity' || str === 'NaN') {
  2903. if (!+str) x.s = NaN;
  2904. x.e = NaN;
  2905. x.d = null;
  2906. return x;
  2907. }
  2908. if (isHex.test(str)) {
  2909. base = 16;
  2910. str = str.toLowerCase();
  2911. } else if (isBinary.test(str)) {
  2912. base = 2;
  2913. } else if (isOctal.test(str)) {
  2914. base = 8;
  2915. } else {
  2916. throw Error(invalidArgument + str);
  2917. }
  2918. // Is there a binary exponent part?
  2919. i = str.search(/p/i);
  2920. if (i > 0) {
  2921. p = +str.slice(i + 1);
  2922. str = str.substring(2, i);
  2923. } else {
  2924. str = str.slice(2);
  2925. }
  2926. // Convert `str` as an integer then divide the result by `base` raised to a power such that the
  2927. // fraction part will be restored.
  2928. i = str.indexOf('.');
  2929. isFloat = i >= 0;
  2930. Ctor = x.constructor;
  2931. if (isFloat) {
  2932. str = str.replace('.', '');
  2933. len = str.length;
  2934. i = len - i;
  2935. // log[10](16) = 1.2041... , log[10](88) = 1.9444....
  2936. divisor = intPow(Ctor, new Ctor(base), i, i * 2);
  2937. }
  2938. xd = convertBase(str, base, BASE);
  2939. xe = xd.length - 1;
  2940. // Remove trailing zeros.
  2941. for (i = xe; xd[i] === 0; --i) xd.pop();
  2942. if (i < 0) return new Ctor(x.s * 0);
  2943. x.e = getBase10Exponent(xd, xe);
  2944. x.d = xd;
  2945. external = false;
  2946. // At what precision to perform the division to ensure exact conversion?
  2947. // maxDecimalIntegerPartDigitCount = ceil(log[10](b) * otherBaseIntegerPartDigitCount)
  2948. // log[10](2) = 0.30103, log[10](8) = 0.90309, log[10](16) = 1.20412
  2949. // E.g. ceil(1.2 * 3) = 4, so up to 4 decimal digits are needed to represent 3 hex int digits.
  2950. // maxDecimalFractionPartDigitCount = {Hex:4|Oct:3|Bin:1} * otherBaseFractionPartDigitCount
  2951. // Therefore using 4 * the number of digits of str will always be enough.
  2952. if (isFloat) x = divide(x, divisor, len * 4);
  2953. // Multiply by the binary exponent part if present.
  2954. if (p) x = x.times(Math.abs(p) < 54 ? mathpow(2, p) : Decimal.pow(2, p));
  2955. external = true;
  2956. return x;
  2957. }
  2958. /*
  2959. * sin(x) = x - x^3/3! + x^5/5! - ...
  2960. * |x| < pi/2
  2961. *
  2962. */
  2963. function sine(Ctor, x) {
  2964. var k,
  2965. len = x.d.length;
  2966. if (len < 3) return taylorSeries(Ctor, 2, x, x);
  2967. // Argument reduction: sin(5x) = 16*sin^5(x) - 20*sin^3(x) + 5*sin(x)
  2968. // i.e. sin(x) = 16*sin^5(x/5) - 20*sin^3(x/5) + 5*sin(x/5)
  2969. // and sin(x) = sin(x/5)(5 + sin^2(x/5)(16sin^2(x/5) - 20))
  2970. // Estimate the optimum number of times to use the argument reduction.
  2971. k = 1.4 * Math.sqrt(len);
  2972. k = k > 16 ? 16 : k | 0;
  2973. x = x.times(1 / tinyPow(5, k));
  2974. x = taylorSeries(Ctor, 2, x, x);
  2975. // Reverse argument reduction
  2976. var sin2_x,
  2977. d5 = new Ctor(5),
  2978. d16 = new Ctor(16),
  2979. d20 = new Ctor(20);
  2980. for (; k--;) {
  2981. sin2_x = x.times(x);
  2982. x = x.times(d5.plus(sin2_x.times(d16.times(sin2_x).minus(d20))));
  2983. }
  2984. return x;
  2985. }
  2986. // Calculate Taylor series for `cos`, `cosh`, `sin` and `sinh`.
  2987. function taylorSeries(Ctor, n, x, y, isHyperbolic) {
  2988. var j, t, u, x2,
  2989. i = 1,
  2990. pr = Ctor.precision,
  2991. k = Math.ceil(pr / LOG_BASE);
  2992. external = false;
  2993. x2 = x.times(x);
  2994. u = new Ctor(y);
  2995. for (;;) {
  2996. t = divide(u.times(x2), new Ctor(n++ * n++), pr, 1);
  2997. u = isHyperbolic ? y.plus(t) : y.minus(t);
  2998. y = divide(t.times(x2), new Ctor(n++ * n++), pr, 1);
  2999. t = u.plus(y);
  3000. if (t.d[k] !== void 0) {
  3001. for (j = k; t.d[j] === u.d[j] && j--;);
  3002. if (j == -1) break;
  3003. }
  3004. j = u;
  3005. u = y;
  3006. y = t;
  3007. t = j;
  3008. i++;
  3009. }
  3010. external = true;
  3011. t.d.length = k + 1;
  3012. return t;
  3013. }
  3014. // Exponent e must be positive and non-zero.
  3015. function tinyPow(b, e) {
  3016. var n = b;
  3017. while (--e) n *= b;
  3018. return n;
  3019. }
  3020. // Return the absolute value of `x` reduced to less than or equal to half pi.
  3021. function toLessThanHalfPi(Ctor, x) {
  3022. var t,
  3023. isNeg = x.s < 0,
  3024. pi = getPi(Ctor, Ctor.precision, 1),
  3025. halfPi = pi.times(0.5);
  3026. x = x.abs();
  3027. if (x.lte(halfPi)) {
  3028. quadrant = isNeg ? 4 : 1;
  3029. return x;
  3030. }
  3031. t = x.divToInt(pi);
  3032. if (t.isZero()) {
  3033. quadrant = isNeg ? 3 : 2;
  3034. } else {
  3035. x = x.minus(t.times(pi));
  3036. // 0 <= x < pi
  3037. if (x.lte(halfPi)) {
  3038. quadrant = isOdd(t) ? (isNeg ? 2 : 3) : (isNeg ? 4 : 1);
  3039. return x;
  3040. }
  3041. quadrant = isOdd(t) ? (isNeg ? 1 : 4) : (isNeg ? 3 : 2);
  3042. }
  3043. return x.minus(pi).abs();
  3044. }
  3045. /*
  3046. * Return the value of Decimal `x` as a string in base `baseOut`.
  3047. *
  3048. * If the optional `sd` argument is present include a binary exponent suffix.
  3049. */
  3050. function toStringBinary(x, baseOut, sd, rm) {
  3051. var base, e, i, k, len, roundUp, str, xd, y,
  3052. Ctor = x.constructor,
  3053. isExp = sd !== void 0;
  3054. if (isExp) {
  3055. checkInt32(sd, 1, MAX_DIGITS);
  3056. if (rm === void 0) rm = Ctor.rounding;
  3057. else checkInt32(rm, 0, 8);
  3058. } else {
  3059. sd = Ctor.precision;
  3060. rm = Ctor.rounding;
  3061. }
  3062. if (!x.isFinite()) {
  3063. str = nonFiniteToString(x);
  3064. } else {
  3065. str = finiteToString(x);
  3066. i = str.indexOf('.');
  3067. // Use exponential notation according to `toExpPos` and `toExpNeg`? No, but if required:
  3068. // maxBinaryExponent = floor((decimalExponent + 1) * log[2](10))
  3069. // minBinaryExponent = floor(decimalExponent * log[2](10))
  3070. // log[2](10) = 3.321928094887362347870319429489390175864
  3071. if (isExp) {
  3072. base = 2;
  3073. if (baseOut == 16) {
  3074. sd = sd * 4 - 3;
  3075. } else if (baseOut == 8) {
  3076. sd = sd * 3 - 2;
  3077. }
  3078. } else {
  3079. base = baseOut;
  3080. }
  3081. // Convert the number as an integer then divide the result by its base raised to a power such
  3082. // that the fraction part will be restored.
  3083. // Non-integer.
  3084. if (i >= 0) {
  3085. str = str.replace('.', '');
  3086. y = new Ctor(1);
  3087. y.e = str.length - i;
  3088. y.d = convertBase(finiteToString(y), 10, base);
  3089. y.e = y.d.length;
  3090. }
  3091. xd = convertBase(str, 10, base);
  3092. e = len = xd.length;
  3093. // Remove trailing zeros.
  3094. for (; xd[--len] == 0;) xd.pop();
  3095. if (!xd[0]) {
  3096. str = isExp ? '0p+0' : '0';
  3097. } else {
  3098. if (i < 0) {
  3099. e--;
  3100. } else {
  3101. x = new Ctor(x);
  3102. x.d = xd;
  3103. x.e = e;
  3104. x = divide(x, y, sd, rm, 0, base);
  3105. xd = x.d;
  3106. e = x.e;
  3107. roundUp = inexact;
  3108. }
  3109. // The rounding digit, i.e. the digit after the digit that may be rounded up.
  3110. i = xd[sd];
  3111. k = base / 2;
  3112. roundUp = roundUp || xd[sd + 1] !== void 0;
  3113. roundUp = rm < 4
  3114. ? (i !== void 0 || roundUp) && (rm === 0 || rm === (x.s < 0 ? 3 : 2))
  3115. : i > k || i === k && (rm === 4 || roundUp || rm === 6 && xd[sd - 1] & 1 ||
  3116. rm === (x.s < 0 ? 8 : 7));
  3117. xd.length = sd;
  3118. if (roundUp) {
  3119. // Rounding up may mean the previous digit has to be rounded up and so on.
  3120. for (; ++xd[--sd] > base - 1;) {
  3121. xd[sd] = 0;
  3122. if (!sd) {
  3123. ++e;
  3124. xd.unshift(1);
  3125. }
  3126. }
  3127. }
  3128. // Determine trailing zeros.
  3129. for (len = xd.length; !xd[len - 1]; --len);
  3130. // E.g. [4, 11, 15] becomes 4bf.
  3131. for (i = 0, str = ''; i < len; i++) str += NUMERALS.charAt(xd[i]);
  3132. // Add binary exponent suffix?
  3133. if (isExp) {
  3134. if (len > 1) {
  3135. if (baseOut == 16 || baseOut == 8) {
  3136. i = baseOut == 16 ? 4 : 3;
  3137. for (--len; len % i; len++) str += '0';
  3138. xd = convertBase(str, base, baseOut);
  3139. for (len = xd.length; !xd[len - 1]; --len);
  3140. // xd[0] will always be be 1
  3141. for (i = 1, str = '1.'; i < len; i++) str += NUMERALS.charAt(xd[i]);
  3142. } else {
  3143. str = str.charAt(0) + '.' + str.slice(1);
  3144. }
  3145. }
  3146. str = str + (e < 0 ? 'p' : 'p+') + e;
  3147. } else if (e < 0) {
  3148. for (; ++e;) str = '0' + str;
  3149. str = '0.' + str;
  3150. } else {
  3151. if (++e > len) for (e -= len; e-- ;) str += '0';
  3152. else if (e < len) str = str.slice(0, e) + '.' + str.slice(e);
  3153. }
  3154. }
  3155. str = (baseOut == 16 ? '0x' : baseOut == 2 ? '0b' : baseOut == 8 ? '0o' : '') + str;
  3156. }
  3157. return x.s < 0 ? '-' + str : str;
  3158. }
  3159. // Does not strip trailing zeros.
  3160. function truncate(arr, len) {
  3161. if (arr.length > len) {
  3162. arr.length = len;
  3163. return true;
  3164. }
  3165. }
  3166. // Decimal methods
  3167. /*
  3168. * abs
  3169. * acos
  3170. * acosh
  3171. * add
  3172. * asin
  3173. * asinh
  3174. * atan
  3175. * atanh
  3176. * atan2
  3177. * cbrt
  3178. * ceil
  3179. * clone
  3180. * config
  3181. * cos
  3182. * cosh
  3183. * div
  3184. * exp
  3185. * floor
  3186. * hypot
  3187. * ln
  3188. * log
  3189. * log2
  3190. * log10
  3191. * max
  3192. * min
  3193. * mod
  3194. * mul
  3195. * pow
  3196. * random
  3197. * round
  3198. * set
  3199. * sign
  3200. * sin
  3201. * sinh
  3202. * sqrt
  3203. * sub
  3204. * tan
  3205. * tanh
  3206. * trunc
  3207. */
  3208. /*
  3209. * Return a new Decimal whose value is the absolute value of `x`.
  3210. *
  3211. * x {number|string|Decimal}
  3212. *
  3213. */
  3214. function abs(x) {
  3215. return new this(x).abs();
  3216. }
  3217. /*
  3218. * Return a new Decimal whose value is the arccosine in radians of `x`.
  3219. *
  3220. * x {number|string|Decimal}
  3221. *
  3222. */
  3223. function acos(x) {
  3224. return new this(x).acos();
  3225. }
  3226. /*
  3227. * Return a new Decimal whose value is the inverse of the hyperbolic cosine of `x`, rounded to
  3228. * `precision` significant digits using rounding mode `rounding`.
  3229. *
  3230. * x {number|string|Decimal} A value in radians.
  3231. *
  3232. */
  3233. function acosh(x) {
  3234. return new this(x).acosh();
  3235. }
  3236. /*
  3237. * Return a new Decimal whose value is the sum of `x` and `y`, rounded to `precision` significant
  3238. * digits using rounding mode `rounding`.
  3239. *
  3240. * x {number|string|Decimal}
  3241. * y {number|string|Decimal}
  3242. *
  3243. */
  3244. function add(x, y) {
  3245. return new this(x).plus(y);
  3246. }
  3247. /*
  3248. * Return a new Decimal whose value is the arcsine in radians of `x`, rounded to `precision`
  3249. * significant digits using rounding mode `rounding`.
  3250. *
  3251. * x {number|string|Decimal}
  3252. *
  3253. */
  3254. function asin(x) {
  3255. return new this(x).asin();
  3256. }
  3257. /*
  3258. * Return a new Decimal whose value is the inverse of the hyperbolic sine of `x`, rounded to
  3259. * `precision` significant digits using rounding mode `rounding`.
  3260. *
  3261. * x {number|string|Decimal} A value in radians.
  3262. *
  3263. */
  3264. function asinh(x) {
  3265. return new this(x).asinh();
  3266. }
  3267. /*
  3268. * Return a new Decimal whose value is the arctangent in radians of `x`, rounded to `precision`
  3269. * significant digits using rounding mode `rounding`.
  3270. *
  3271. * x {number|string|Decimal}
  3272. *
  3273. */
  3274. function atan(x) {
  3275. return new this(x).atan();
  3276. }
  3277. /*
  3278. * Return a new Decimal whose value is the inverse of the hyperbolic tangent of `x`, rounded to
  3279. * `precision` significant digits using rounding mode `rounding`.
  3280. *
  3281. * x {number|string|Decimal} A value in radians.
  3282. *
  3283. */
  3284. function atanh(x) {
  3285. return new this(x).atanh();
  3286. }
  3287. /*
  3288. * Return a new Decimal whose value is the arctangent in radians of `y/x` in the range -pi to pi
  3289. * (inclusive), rounded to `precision` significant digits using rounding mode `rounding`.
  3290. *
  3291. * Domain: [-Infinity, Infinity]
  3292. * Range: [-pi, pi]
  3293. *
  3294. * y {number|string|Decimal} The y-coordinate.
  3295. * x {number|string|Decimal} The x-coordinate.
  3296. *
  3297. * atan2(±0, -0) = ±pi
  3298. * atan2(±0, +0) = ±0
  3299. * atan2(±0, -x) = ±pi for x > 0
  3300. * atan2(±0, x) = ±0 for x > 0
  3301. * atan2(-y, ±0) = -pi/2 for y > 0
  3302. * atan2(y, ±0) = pi/2 for y > 0
  3303. * atan2(±y, -Infinity) = ±pi for finite y > 0
  3304. * atan2(±y, +Infinity) = ±0 for finite y > 0
  3305. * atan2(±Infinity, x) = ±pi/2 for finite x
  3306. * atan2(±Infinity, -Infinity) = ±3*pi/4
  3307. * atan2(±Infinity, +Infinity) = ±pi/4
  3308. * atan2(NaN, x) = NaN
  3309. * atan2(y, NaN) = NaN
  3310. *
  3311. */
  3312. function atan2(y, x) {
  3313. y = new this(y);
  3314. x = new this(x);
  3315. var r,
  3316. pr = this.precision,
  3317. rm = this.rounding,
  3318. wpr = pr + 4;
  3319. // Either NaN
  3320. if (!y.s || !x.s) {
  3321. r = new this(NaN);
  3322. // Both ±Infinity
  3323. } else if (!y.d && !x.d) {
  3324. r = getPi(this, wpr, 1).times(x.s > 0 ? 0.25 : 0.75);
  3325. r.s = y.s;
  3326. // x is ±Infinity or y is ±0
  3327. } else if (!x.d || y.isZero()) {
  3328. r = x.s < 0 ? getPi(this, pr, rm) : new this(0);
  3329. r.s = y.s;
  3330. // y is ±Infinity or x is ±0
  3331. } else if (!y.d || x.isZero()) {
  3332. r = getPi(this, wpr, 1).times(0.5);
  3333. r.s = y.s;
  3334. // Both non-zero and finite
  3335. } else if (x.s < 0) {
  3336. this.precision = wpr;
  3337. this.rounding = 1;
  3338. r = this.atan(divide(y, x, wpr, 1));
  3339. x = getPi(this, wpr, 1);
  3340. this.precision = pr;
  3341. this.rounding = rm;
  3342. r = y.s < 0 ? r.minus(x) : r.plus(x);
  3343. } else {
  3344. r = this.atan(divide(y, x, wpr, 1));
  3345. }
  3346. return r;
  3347. }
  3348. /*
  3349. * Return a new Decimal whose value is the cube root of `x`, rounded to `precision` significant
  3350. * digits using rounding mode `rounding`.
  3351. *
  3352. * x {number|string|Decimal}
  3353. *
  3354. */
  3355. function cbrt(x) {
  3356. return new this(x).cbrt();
  3357. }
  3358. /*
  3359. * Return a new Decimal whose value is `x` rounded to an integer using `ROUND_CEIL`.
  3360. *
  3361. * x {number|string|Decimal}
  3362. *
  3363. */
  3364. function ceil(x) {
  3365. return finalise(x = new this(x), x.e + 1, 2);
  3366. }
  3367. /*
  3368. * Configure global settings for a Decimal constructor.
  3369. *
  3370. * `obj` is an object with one or more of the following properties,
  3371. *
  3372. * precision {number}
  3373. * rounding {number}
  3374. * toExpNeg {number}
  3375. * toExpPos {number}
  3376. * maxE {number}
  3377. * minE {number}
  3378. * modulo {number}
  3379. * crypto {boolean|number}
  3380. * defaults {true}
  3381. *
  3382. * E.g. Decimal.config({ precision: 20, rounding: 4 })
  3383. *
  3384. */
  3385. function config(obj) {
  3386. if (!obj || typeof obj !== 'object') throw Error(decimalError + 'Object expected');
  3387. var i, p, v,
  3388. useDefaults = obj.defaults === true,
  3389. ps = [
  3390. 'precision', 1, MAX_DIGITS,
  3391. 'rounding', 0, 8,
  3392. 'toExpNeg', -EXP_LIMIT, 0,
  3393. 'toExpPos', 0, EXP_LIMIT,
  3394. 'maxE', 0, EXP_LIMIT,
  3395. 'minE', -EXP_LIMIT, 0,
  3396. 'modulo', 0, 9
  3397. ];
  3398. for (i = 0; i < ps.length; i += 3) {
  3399. if (p = ps[i], useDefaults) this[p] = DEFAULTS[p];
  3400. if ((v = obj[p]) !== void 0) {
  3401. if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v;
  3402. else throw Error(invalidArgument + p + ': ' + v);
  3403. }
  3404. }
  3405. if (p = 'crypto', useDefaults) this[p] = DEFAULTS[p];
  3406. if ((v = obj[p]) !== void 0) {
  3407. if (v === true || v === false || v === 0 || v === 1) {
  3408. if (v) {
  3409. if (typeof crypto != 'undefined' && crypto &&
  3410. (crypto.getRandomValues || crypto.randomBytes)) {
  3411. this[p] = true;
  3412. } else {
  3413. throw Error(cryptoUnavailable);
  3414. }
  3415. } else {
  3416. this[p] = false;
  3417. }
  3418. } else {
  3419. throw Error(invalidArgument + p + ': ' + v);
  3420. }
  3421. }
  3422. return this;
  3423. }
  3424. /*
  3425. * Return a new Decimal whose value is the cosine of `x`, rounded to `precision` significant
  3426. * digits using rounding mode `rounding`.
  3427. *
  3428. * x {number|string|Decimal} A value in radians.
  3429. *
  3430. */
  3431. function cos(x) {
  3432. return new this(x).cos();
  3433. }
  3434. /*
  3435. * Return a new Decimal whose value is the hyperbolic cosine of `x`, rounded to precision
  3436. * significant digits using rounding mode `rounding`.
  3437. *
  3438. * x {number|string|Decimal} A value in radians.
  3439. *
  3440. */
  3441. function cosh(x) {
  3442. return new this(x).cosh();
  3443. }
  3444. /*
  3445. * Create and return a Decimal constructor with the same configuration properties as this Decimal
  3446. * constructor.
  3447. *
  3448. */
  3449. function clone(obj) {
  3450. var i, p, ps;
  3451. /*
  3452. * The Decimal constructor and exported function.
  3453. * Return a new Decimal instance.
  3454. *
  3455. * v {number|string|Decimal} A numeric value.
  3456. *
  3457. */
  3458. function Decimal(v) {
  3459. var e, i, t,
  3460. x = this;
  3461. // Decimal called without new.
  3462. if (!(x instanceof Decimal)) return new Decimal(v);
  3463. // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor
  3464. // which points to Object.
  3465. x.constructor = Decimal;
  3466. // Duplicate.
  3467. if (v instanceof Decimal) {
  3468. x.s = v.s;
  3469. if (external) {
  3470. if (!v.d || v.e > Decimal.maxE) {
  3471. // Infinity.
  3472. x.e = NaN;
  3473. x.d = null;
  3474. } else if (v.e < Decimal.minE) {
  3475. // Zero.
  3476. x.e = 0;
  3477. x.d = [0];
  3478. } else {
  3479. x.e = v.e;
  3480. x.d = v.d.slice();
  3481. }
  3482. } else {
  3483. x.e = v.e;
  3484. x.d = v.d ? v.d.slice() : v.d;
  3485. }
  3486. return;
  3487. }
  3488. t = typeof v;
  3489. if (t === 'number') {
  3490. if (v === 0) {
  3491. x.s = 1 / v < 0 ? -1 : 1;
  3492. x.e = 0;
  3493. x.d = [0];
  3494. return;
  3495. }
  3496. if (v < 0) {
  3497. v = -v;
  3498. x.s = -1;
  3499. } else {
  3500. x.s = 1;
  3501. }
  3502. // Fast path for small integers.
  3503. if (v === ~~v && v < 1e7) {
  3504. for (e = 0, i = v; i >= 10; i /= 10) e++;
  3505. if (external) {
  3506. if (e > Decimal.maxE) {
  3507. x.e = NaN;
  3508. x.d = null;
  3509. } else if (e < Decimal.minE) {
  3510. x.e = 0;
  3511. x.d = [0];
  3512. } else {
  3513. x.e = e;
  3514. x.d = [v];
  3515. }
  3516. } else {
  3517. x.e = e;
  3518. x.d = [v];
  3519. }
  3520. return;
  3521. // Infinity, NaN.
  3522. } else if (v * 0 !== 0) {
  3523. if (!v) x.s = NaN;
  3524. x.e = NaN;
  3525. x.d = null;
  3526. return;
  3527. }
  3528. return parseDecimal(x, v.toString());
  3529. } else if (t !== 'string') {
  3530. throw Error(invalidArgument + v);
  3531. }
  3532. // Minus sign?
  3533. if ((i = v.charCodeAt(0)) === 45) {
  3534. v = v.slice(1);
  3535. x.s = -1;
  3536. } else {
  3537. // Plus sign?
  3538. if (i === 43) v = v.slice(1);
  3539. x.s = 1;
  3540. }
  3541. return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v);
  3542. }
  3543. Decimal.prototype = P;
  3544. Decimal.ROUND_UP = 0;
  3545. Decimal.ROUND_DOWN = 1;
  3546. Decimal.ROUND_CEIL = 2;
  3547. Decimal.ROUND_FLOOR = 3;
  3548. Decimal.ROUND_HALF_UP = 4;
  3549. Decimal.ROUND_HALF_DOWN = 5;
  3550. Decimal.ROUND_HALF_EVEN = 6;
  3551. Decimal.ROUND_HALF_CEIL = 7;
  3552. Decimal.ROUND_HALF_FLOOR = 8;
  3553. Decimal.EUCLID = 9;
  3554. Decimal.config = Decimal.set = config;
  3555. Decimal.clone = clone;
  3556. Decimal.isDecimal = isDecimalInstance;
  3557. Decimal.abs = abs;
  3558. Decimal.acos = acos;
  3559. Decimal.acosh = acosh; // ES6
  3560. Decimal.add = add;
  3561. Decimal.asin = asin;
  3562. Decimal.asinh = asinh; // ES6
  3563. Decimal.atan = atan;
  3564. Decimal.atanh = atanh; // ES6
  3565. Decimal.atan2 = atan2;
  3566. Decimal.cbrt = cbrt; // ES6
  3567. Decimal.ceil = ceil;
  3568. Decimal.cos = cos;
  3569. Decimal.cosh = cosh; // ES6
  3570. Decimal.div = div;
  3571. Decimal.exp = exp;
  3572. Decimal.floor = floor;
  3573. Decimal.hypot = hypot; // ES6
  3574. Decimal.ln = ln;
  3575. Decimal.log = log;
  3576. Decimal.log10 = log10; // ES6
  3577. Decimal.log2 = log2; // ES6
  3578. Decimal.max = max;
  3579. Decimal.min = min;
  3580. Decimal.mod = mod;
  3581. Decimal.mul = mul;
  3582. Decimal.pow = pow;
  3583. Decimal.random = random;
  3584. Decimal.round = round;
  3585. Decimal.sign = sign; // ES6
  3586. Decimal.sin = sin;
  3587. Decimal.sinh = sinh; // ES6
  3588. Decimal.sqrt = sqrt;
  3589. Decimal.sub = sub;
  3590. Decimal.tan = tan;
  3591. Decimal.tanh = tanh; // ES6
  3592. Decimal.trunc = trunc; // ES6
  3593. if (obj === void 0) obj = {};
  3594. if (obj) {
  3595. if (obj.defaults !== true) {
  3596. ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'maxE', 'minE', 'modulo', 'crypto'];
  3597. for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p];
  3598. }
  3599. }
  3600. Decimal.config(obj);
  3601. return Decimal;
  3602. }
  3603. /*
  3604. * Return a new Decimal whose value is `x` divided by `y`, rounded to `precision` significant
  3605. * digits using rounding mode `rounding`.
  3606. *
  3607. * x {number|string|Decimal}
  3608. * y {number|string|Decimal}
  3609. *
  3610. */
  3611. function div(x, y) {
  3612. return new this(x).div(y);
  3613. }
  3614. /*
  3615. * Return a new Decimal whose value is the natural exponential of `x`, rounded to `precision`
  3616. * significant digits using rounding mode `rounding`.
  3617. *
  3618. * x {number|string|Decimal} The power to which to raise the base of the natural log.
  3619. *
  3620. */
  3621. function exp(x) {
  3622. return new this(x).exp();
  3623. }
  3624. /*
  3625. * Return a new Decimal whose value is `x` round to an integer using `ROUND_FLOOR`.
  3626. *
  3627. * x {number|string|Decimal}
  3628. *
  3629. */
  3630. function floor(x) {
  3631. return finalise(x = new this(x), x.e + 1, 3);
  3632. }
  3633. /*
  3634. * Return a new Decimal whose value is the square root of the sum of the squares of the arguments,
  3635. * rounded to `precision` significant digits using rounding mode `rounding`.
  3636. *
  3637. * hypot(a, b, ...) = sqrt(a^2 + b^2 + ...)
  3638. *
  3639. * arguments {number|string|Decimal}
  3640. *
  3641. */
  3642. function hypot() {
  3643. var i, n,
  3644. t = new this(0);
  3645. external = false;
  3646. for (i = 0; i < arguments.length;) {
  3647. n = new this(arguments[i++]);
  3648. if (!n.d) {
  3649. if (n.s) {
  3650. external = true;
  3651. return new this(1 / 0);
  3652. }
  3653. t = n;
  3654. } else if (t.d) {
  3655. t = t.plus(n.times(n));
  3656. }
  3657. }
  3658. external = true;
  3659. return t.sqrt();
  3660. }
  3661. /*
  3662. * Return true if object is a Decimal instance (where Decimal is any Decimal constructor),
  3663. * otherwise return false.
  3664. *
  3665. */
  3666. function isDecimalInstance(obj) {
  3667. return obj instanceof Decimal || obj && obj.name === '[object Decimal]' || false;
  3668. }
  3669. /*
  3670. * Return a new Decimal whose value is the natural logarithm of `x`, rounded to `precision`
  3671. * significant digits using rounding mode `rounding`.
  3672. *
  3673. * x {number|string|Decimal}
  3674. *
  3675. */
  3676. function ln(x) {
  3677. return new this(x).ln();
  3678. }
  3679. /*
  3680. * Return a new Decimal whose value is the log of `x` to the base `y`, or to base 10 if no base
  3681. * is specified, rounded to `precision` significant digits using rounding mode `rounding`.
  3682. *
  3683. * log[y](x)
  3684. *
  3685. * x {number|string|Decimal} The argument of the logarithm.
  3686. * y {number|string|Decimal} The base of the logarithm.
  3687. *
  3688. */
  3689. function log(x, y) {
  3690. return new this(x).log(y);
  3691. }
  3692. /*
  3693. * Return a new Decimal whose value is the base 2 logarithm of `x`, rounded to `precision`
  3694. * significant digits using rounding mode `rounding`.
  3695. *
  3696. * x {number|string|Decimal}
  3697. *
  3698. */
  3699. function log2(x) {
  3700. return new this(x).log(2);
  3701. }
  3702. /*
  3703. * Return a new Decimal whose value is the base 10 logarithm of `x`, rounded to `precision`
  3704. * significant digits using rounding mode `rounding`.
  3705. *
  3706. * x {number|string|Decimal}
  3707. *
  3708. */
  3709. function log10(x) {
  3710. return new this(x).log(10);
  3711. }
  3712. /*
  3713. * Return a new Decimal whose value is the maximum of the arguments.
  3714. *
  3715. * arguments {number|string|Decimal}
  3716. *
  3717. */
  3718. function max() {
  3719. return maxOrMin(this, arguments, 'lt');
  3720. }
  3721. /*
  3722. * Return a new Decimal whose value is the minimum of the arguments.
  3723. *
  3724. * arguments {number|string|Decimal}
  3725. *
  3726. */
  3727. function min() {
  3728. return maxOrMin(this, arguments, 'gt');
  3729. }
  3730. /*
  3731. * Return a new Decimal whose value is `x` modulo `y`, rounded to `precision` significant digits
  3732. * using rounding mode `rounding`.
  3733. *
  3734. * x {number|string|Decimal}
  3735. * y {number|string|Decimal}
  3736. *
  3737. */
  3738. function mod(x, y) {
  3739. return new this(x).mod(y);
  3740. }
  3741. /*
  3742. * Return a new Decimal whose value is `x` multiplied by `y`, rounded to `precision` significant
  3743. * digits using rounding mode `rounding`.
  3744. *
  3745. * x {number|string|Decimal}
  3746. * y {number|string|Decimal}
  3747. *
  3748. */
  3749. function mul(x, y) {
  3750. return new this(x).mul(y);
  3751. }
  3752. /*
  3753. * Return a new Decimal whose value is `x` raised to the power `y`, rounded to precision
  3754. * significant digits using rounding mode `rounding`.
  3755. *
  3756. * x {number|string|Decimal} The base.
  3757. * y {number|string|Decimal} The exponent.
  3758. *
  3759. */
  3760. function pow(x, y) {
  3761. return new this(x).pow(y);
  3762. }
  3763. /*
  3764. * Returns a new Decimal with a random value equal to or greater than 0 and less than 1, and with
  3765. * `sd`, or `Decimal.precision` if `sd` is omitted, significant digits (or less if trailing zeros
  3766. * are produced).
  3767. *
  3768. * [sd] {number} Significant digits. Integer, 0 to MAX_DIGITS inclusive.
  3769. *
  3770. */
  3771. function random(sd) {
  3772. var d, e, k, n,
  3773. i = 0,
  3774. r = new this(1),
  3775. rd = [];
  3776. if (sd === void 0) sd = this.precision;
  3777. else checkInt32(sd, 1, MAX_DIGITS);
  3778. k = Math.ceil(sd / LOG_BASE);
  3779. if (!this.crypto) {
  3780. for (; i < k;) rd[i++] = Math.random() * 1e7 | 0;
  3781. // Browsers supporting crypto.getRandomValues.
  3782. } else if (crypto.getRandomValues) {
  3783. d = crypto.getRandomValues(new Uint32Array(k));
  3784. for (; i < k;) {
  3785. n = d[i];
  3786. // 0 <= n < 4294967296
  3787. // Probability n >= 4.29e9, is 4967296 / 4294967296 = 0.00116 (1 in 865).
  3788. if (n >= 4.29e9) {
  3789. d[i] = crypto.getRandomValues(new Uint32Array(1))[0];
  3790. } else {
  3791. // 0 <= n <= 4289999999
  3792. // 0 <= (n % 1e7) <= 9999999
  3793. rd[i++] = n % 1e7;
  3794. }
  3795. }
  3796. // Node.js supporting crypto.randomBytes.
  3797. } else if (crypto.randomBytes) {
  3798. // buffer
  3799. d = crypto.randomBytes(k *= 4);
  3800. for (; i < k;) {
  3801. // 0 <= n < 2147483648
  3802. n = d[i] + (d[i + 1] << 8) + (d[i + 2] << 16) + ((d[i + 3] & 0x7f) << 24);
  3803. // Probability n >= 2.14e9, is 7483648 / 2147483648 = 0.0035 (1 in 286).
  3804. if (n >= 2.14e9) {
  3805. crypto.randomBytes(4).copy(d, i);
  3806. } else {
  3807. // 0 <= n <= 2139999999
  3808. // 0 <= (n % 1e7) <= 9999999
  3809. rd.push(n % 1e7);
  3810. i += 4;
  3811. }
  3812. }
  3813. i = k / 4;
  3814. } else {
  3815. throw Error(cryptoUnavailable);
  3816. }
  3817. k = rd[--i];
  3818. sd %= LOG_BASE;
  3819. // Convert trailing digits to zeros according to sd.
  3820. if (k && sd) {
  3821. n = mathpow(10, LOG_BASE - sd);
  3822. rd[i] = (k / n | 0) * n;
  3823. }
  3824. // Remove trailing words which are zero.
  3825. for (; rd[i] === 0; i--) rd.pop();
  3826. // Zero?
  3827. if (i < 0) {
  3828. e = 0;
  3829. rd = [0];
  3830. } else {
  3831. e = -1;
  3832. // Remove leading words which are zero and adjust exponent accordingly.
  3833. for (; rd[0] === 0; e -= LOG_BASE) rd.shift();
  3834. // Count the digits of the first word of rd to determine leading zeros.
  3835. for (k = 1, n = rd[0]; n >= 10; n /= 10) k++;
  3836. // Adjust the exponent for leading zeros of the first word of rd.
  3837. if (k < LOG_BASE) e -= LOG_BASE - k;
  3838. }
  3839. r.e = e;
  3840. r.d = rd;
  3841. return r;
  3842. }
  3843. /*
  3844. * Return a new Decimal whose value is `x` rounded to an integer using rounding mode `rounding`.
  3845. *
  3846. * To emulate `Math.round`, set rounding to 7 (ROUND_HALF_CEIL).
  3847. *
  3848. * x {number|string|Decimal}
  3849. *
  3850. */
  3851. function round(x) {
  3852. return finalise(x = new this(x), x.e + 1, this.rounding);
  3853. }
  3854. /*
  3855. * Return
  3856. * 1 if x > 0,
  3857. * -1 if x < 0,
  3858. * 0 if x is 0,
  3859. * -0 if x is -0,
  3860. * NaN otherwise
  3861. *
  3862. * x {number|string|Decimal}
  3863. *
  3864. */
  3865. function sign(x) {
  3866. x = new this(x);
  3867. return x.d ? (x.d[0] ? x.s : 0 * x.s) : x.s || NaN;
  3868. }
  3869. /*
  3870. * Return a new Decimal whose value is the sine of `x`, rounded to `precision` significant digits
  3871. * using rounding mode `rounding`.
  3872. *
  3873. * x {number|string|Decimal} A value in radians.
  3874. *
  3875. */
  3876. function sin(x) {
  3877. return new this(x).sin();
  3878. }
  3879. /*
  3880. * Return a new Decimal whose value is the hyperbolic sine of `x`, rounded to `precision`
  3881. * significant digits using rounding mode `rounding`.
  3882. *
  3883. * x {number|string|Decimal} A value in radians.
  3884. *
  3885. */
  3886. function sinh(x) {
  3887. return new this(x).sinh();
  3888. }
  3889. /*
  3890. * Return a new Decimal whose value is the square root of `x`, rounded to `precision` significant
  3891. * digits using rounding mode `rounding`.
  3892. *
  3893. * x {number|string|Decimal}
  3894. *
  3895. */
  3896. function sqrt(x) {
  3897. return new this(x).sqrt();
  3898. }
  3899. /*
  3900. * Return a new Decimal whose value is `x` minus `y`, rounded to `precision` significant digits
  3901. * using rounding mode `rounding`.
  3902. *
  3903. * x {number|string|Decimal}
  3904. * y {number|string|Decimal}
  3905. *
  3906. */
  3907. function sub(x, y) {
  3908. return new this(x).sub(y);
  3909. }
  3910. /*
  3911. * Return a new Decimal whose value is the tangent of `x`, rounded to `precision` significant
  3912. * digits using rounding mode `rounding`.
  3913. *
  3914. * x {number|string|Decimal} A value in radians.
  3915. *
  3916. */
  3917. function tan(x) {
  3918. return new this(x).tan();
  3919. }
  3920. /*
  3921. * Return a new Decimal whose value is the hyperbolic tangent of `x`, rounded to `precision`
  3922. * significant digits using rounding mode `rounding`.
  3923. *
  3924. * x {number|string|Decimal} A value in radians.
  3925. *
  3926. */
  3927. function tanh(x) {
  3928. return new this(x).tanh();
  3929. }
  3930. /*
  3931. * Return a new Decimal whose value is `x` truncated to an integer.
  3932. *
  3933. * x {number|string|Decimal}
  3934. *
  3935. */
  3936. function trunc(x) {
  3937. return finalise(x = new this(x), x.e + 1, 1);
  3938. }
  3939. P[Symbol.for('nodejs.util.inspect.custom')] = P.toString;
  3940. P[Symbol.toStringTag] = 'Decimal';
  3941. // Create and configure initial Decimal constructor.
  3942. export var Decimal = clone(DEFAULTS);
  3943. // Create the internal constants from their string values.
  3944. LN10 = new Decimal(LN10);
  3945. PI = new Decimal(PI);
  3946. export default Decimal;