Merge lp:~rpadovani/ubuntu-calculator-app/cleanUp into lp:ubuntu-calculator-app

Proposed by Riccardo Padovani
Status: Merged
Approved by: Bartosz Kosiorek
Approved revision: no longer in the source branch.
Merged at revision: 4
Proposed branch: lp:~rpadovani/ubuntu-calculator-app/cleanUp
Merge into: lp:ubuntu-calculator-app
Diff against target: 10449 lines (+4642/-5439)
11 files modified
app/Storage.qml (+0/-138)
app/components/CMakeLists.txt (+0/-7)
app/components/HelloComponent.qml (+0/-15)
app/formula.js (+0/-77)
app/js/math.js (+4577/-4583)
app/ubuntu-calculator-app.qml (+44/-6)
app/ui/CalcHistory.qml (+0/-67)
app/ui/CalcKeyboard.qml (+17/-57)
app/ui/Memory.qml (+0/-30)
app/ui/Screen.qml (+4/-99)
app/ui/SimplePage.qml (+0/-360)
To merge this branch: bzr merge lp:~rpadovani/ubuntu-calculator-app/cleanUp
Reviewer Review Type Date Requested Status
Bartosz Kosiorek Approve
Review via email: mp+242881@code.launchpad.net

Commit message

Cleaned up the code, have working engine now

Description of the change

Starting from Bartosz's changes I cleaned up the project and fixed the engine.

I deleted a lot of old components: now the calculator has a lot of miss functionality (no history, no current typing calc and so on) but I think is a good start point to create the new calculator.

The only old thing I didn't modify is the keyboard, that needs some rework.

atm the only working thing is the engine (but it works very well): when you do a calc, and press equal, the result appears

To post a comment you must log in.
Revision history for this message
Bartosz Kosiorek (gang65) wrote :

ok for me

review: Approve
4. By Bartosz Kosiorek

Cleaned up the code, have working engine now

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== removed file 'app/Storage.qml'
2--- app/Storage.qml 2014-11-19 22:34:53 +0000
3+++ app/Storage.qml 1970-01-01 00:00:00 +0000
4@@ -1,138 +0,0 @@
5-/*
6- * Copyright 2013 Canonical Ltd.
7- *
8- * This file is part of ubuntu-calculator-app.
9- *
10- * ubuntu-calculator-app is free software; you can redistribute it and/or modify
11- * it under the terms of the GNU General Public License as published by
12- * the Free Software Foundation; version 3.
13- *
14- * ubuntu-calculator-app is distributed in the hope that it will be useful,
15- * but WITHOUT ANY WARRANTY; without even the implied warranty of
16- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17- * GNU General Public License for more details.
18- *
19- * You should have received a copy of the GNU General Public License
20- * along with this program. If not, see <http://www.gnu.org/licenses/>.
21- */
22-
23-import QtQuick 2.3
24-import QtQuick.LocalStorage 2.0
25-
26-Item {
27- property var db: null
28-
29- function openDB() {
30- if(db !== null) return;
31-
32- db = LocalStorage.openDatabaseSync("ubuntu-calculator-app", "", "Default Ubuntu touch calculator", 100000);
33- if (db.version !== "0.2")
34- upgradeDB(db.version);
35- }
36-
37- /* We need this function because db.version is in the .ini file, that is update only by Javascript Garbage Collection.
38- * So, we have to upgrade from actual version to the last version using only once db.changeVersion.
39- * To avoid to have a lot of switch and spaghetti-code, this function allow to add new db version without modify old sql
40- *
41- * IMPORTANT: NUMBER OF VERSION HAVE TO BE INT (e.g. 0.1, not 0.1.1)
42- */
43- function upgradeDB() {
44- // This is the array with all the sql code, insert your update at the last
45- var sqlcode = [
46- 'CREATE TABLE IF NOT EXISTS Calculations(id INTEGER PRIMARY KEY, calc TEXT)',
47- 'ALTER TABLE Calculations ADD insertDate INTEGER NOT NULL DEFAULT 0'
48- ]
49-
50- // This is the last version of the DB, remember to update when you insert a new version
51- var lastVersion = "0.2";
52-
53- // Hack for change old numeration with new one
54- if (db.version === "0.1.1") {
55- db.changeVersion("0.1.1", "0.2");
56- console.log("Fixed DB!");
57- }
58-
59- // So, let's start the version change...
60- db.changeVersion(db.version, lastVersion,
61- function(tx) {
62- if (db.version < 0.1) {
63- tx.executeSql(sqlcode[0]);
64- console.log('Database upgraded to 0.1');
65- }
66- if (db.version < 0.2) {
67- tx.executeSql(sqlcode[1]);
68- console.log('Database upgraded to 0.2');
69- }
70-
71- /* This is the structure of the update:
72- * n is the number of version that sql update to
73- * m is the number of the sql element in the array. Remember that the number of the first element of array is 0 ;)
74- if (db.version < n) {
75- tx.executeSql(sqlcode[m]);
76- console.log('Database upgraded to n');
77- }
78- */
79- }); // Finish db.changeVersion
80- }
81-
82- function getCalculation(dbId) {
83- openDB();
84- var calc;
85- db.transaction(
86- function(tx){
87- var calculation = tx.executeSql('SELECT calc FROM Calculations WHERE id = ?', dbId);
88- calc = JSON.parse(calculation.rows.item(0).calc);
89- });
90- return calc;
91- }
92-
93- function getCalculations(callback){
94- openDB();
95- db.transaction(
96- function(tx){
97- var res = tx.executeSql('SELECT * FROM Calculations');
98- for(var i=res.rows.length - 1; i >= 0; i--){
99- var obj = JSON.parse(res.rows.item(i).calc);
100- obj.dbId = res.rows.item(i).id;
101- // TRANSLATORS: this is a time formatting string,
102- // see http://qt-project.org/doc/qt-5/qml-qtqml-date.html#details for valid expressions
103- obj.dateText = Qt.formatDateTime(parseDate(res.rows.item(i).insertDate), i18n.tr("MMM dd yyyy, hh:mm"))
104-
105- if (!('mainLabel' in obj))
106- obj.mainLabel = ''
107-
108- callback(obj);
109- }
110- }
111- );
112- }
113-
114- function parseDate(dateAsStr) {
115- return new Date(dateAsStr);
116- }
117-
118- function saveCalculations(calculations){
119- openDB();
120- var res;
121- db.transaction( function(tx){
122- var r = tx.executeSql('INSERT INTO Calculations(calc, insertDate) VALUES(?, ?)', [JSON.stringify(calculations[0].calc), calculations[0].date]);
123- res = r.insertId;
124- });
125- return res;
126- }
127-
128- function updateCalculation(calculation, dbId){
129- openDB();
130- db.transaction(
131- function(tx){
132- tx.executeSql('UPDATE Calculations SET calc = ? WHERE id = ?', [JSON.stringify(calculation[0].calc), dbId]);
133- });
134- }
135-
136- function removeCalculation(calc){
137- openDB();
138- db.transaction(function(tx){
139- tx.executeSql('DELETE FROM Calculations WHERE id = ?', [calc.dbId]);
140- });
141- }
142-}
143
144=== removed directory 'app/components'
145=== removed file 'app/components/CMakeLists.txt'
146--- app/components/CMakeLists.txt 2014-11-10 09:28:27 +0000
147+++ app/components/CMakeLists.txt 1970-01-01 00:00:00 +0000
148@@ -1,7 +0,0 @@
149-file(GLOB COMPONENTS_QML_JS_FILES *.qml *.js)
150-
151-# Make the files visible in the qtcreator tree
152-add_custom_target(ubuntu-calculator-app_components_QMlFiles ALL SOURCES ${COMPONENTS_QML_JS_FILES})
153-
154-install(FILES ${COMPONENTS_QML_JS_FILES} DESTINATION ${UBUNTU-CALCULATOR-APP_DIR}/components)
155-
156
157=== removed file 'app/components/HelloComponent.qml'
158--- app/components/HelloComponent.qml 2014-11-10 09:28:27 +0000
159+++ app/components/HelloComponent.qml 1970-01-01 00:00:00 +0000
160@@ -1,15 +0,0 @@
161-import QtQuick 2.0
162-import Ubuntu.Components 1.1
163-
164-UbuntuShape {
165- width: 200
166- height: width
167-
168- property alias text : myText.text
169-
170- Label {
171- id: myText
172- anchors.centerIn: parent
173- }
174-}
175-
176
177=== removed file 'app/formula.js'
178--- app/formula.js 2014-11-19 22:34:53 +0000
179+++ app/formula.js 1970-01-01 00:00:00 +0000
180@@ -1,77 +0,0 @@
181-/*
182- * Copyright 2013 Canonical Ltd.
183- *
184- * This file is part of ubuntu-calculator-app.
185- *
186- * ubuntu-calculator-app is free software; you can redistribute it and/or modify
187- * it under the terms of the GNU General Public License as published by
188- * the Free Software Foundation; version 3.
189- *
190- * ubuntu-calculator-app is distributed in the hope that it will be useful,
191- * but WITHOUT ANY WARRANTY; without even the implied warranty of
192- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
193- * GNU General Public License for more details.
194- *
195- * You should have received a copy of the GNU General Public License
196- * along with this program. If not, see <http://www.gnu.org/licenses/>.
197- */
198-
199-
200-
201-function Formula() {
202- var formula = '';
203- var previousFormula = {};
204- var previousFormulaCounter = -1;
205- var lookupTbl = {
206- '-': '−',
207- '/': '÷',
208- '*': '×'
209- };
210- var table = {
211- "65" : "+",
212- "66" : "-",
213- "67" : "*",
214- "68" : "/"
215- }
216-
217- var isLastResult = false; // This var becames true if the last button pressed by user is equal
218- var isChangeSign = false; // This var becames true if user want to change the sign of a result
219-
220- function operatorToString(digit) {
221- }
222-
223- // Check if the given digit is one of the valid operators or not.
224- function isOperator(digit){
225- }
226-
227- var _calculate = function(func){
228- }
229-
230- this.push = function(digit){
231- };
232-
233- this.pop = function() {
234- };
235-
236- this.numeralPop = function() {
237- };
238-
239-
240- this.calculate = function() {
241-
242- }
243-
244- this.changeSign = function() {
245-
246- }
247-
248- this.hasResults = function(){
249- }
250-
251- this.restorePreviousFormula = function() {
252- if (previousFormulaCounter > -1) {
253- formula = previousFormula[previousFormulaCounter];
254- previousFormulaCounter--;
255- }
256- }
257-}
258
259=== added directory 'app/js'
260=== renamed file 'app/components/math.js' => 'app/js/math.js'
261--- app/components/math.js 2014-11-20 23:07:48 +0000
262+++ app/js/math.js 2014-11-26 08:43:24 +0000
263@@ -1,3 +1,4 @@
264+var mathJs;
265 /**
266 * math.js
267 * https://github.com/josdejong/mathjs
268@@ -26,14 +27,7 @@
269 */
270
271 (function webpackUniversalModuleDefinition(root, factory) {
272- if(typeof exports === 'object' && typeof module === 'object')
273- module.exports = factory();
274- else if(typeof define === 'function' && define.amd)
275- define(factory);
276- else if(typeof exports === 'object')
277- exports["math"] = factory();
278- else
279- root["math"] = factory();
280+ mathJs = factory();
281 })(this, function() {
282 return /******/ (function(modules) { // webpackBootstrap
283 /******/ // The module cache
284@@ -1062,7 +1056,7 @@
285 this.im = construct.im;
286 break;
287 }
288- }
289+ }
290 throw new SyntaxError('Object with the re and im or r and phi properties expected.');
291
292 case 2:
293@@ -8265,7 +8259,7 @@
294 var util = __webpack_require__(147),
295
296 array = __webpack_require__(140),
297-
298+
299 BigNumber = math.type.BigNumber,
300 Complex = __webpack_require__(6),
301 Matrix = __webpack_require__(9),
302@@ -11356,7 +11350,7 @@
303 } else if ('r' in arg && 'phi' in arg) {
304 return Complex.fromPolar(arg.r, arg.phi);
305 }
306- }
307+ }
308
309 throw new TypeError('Two numbers, single string or an fitting object expected in function complex');
310
311@@ -14136,12 +14130,12 @@
312 if (!isInteger(n) || n < 0) {
313 throw new TypeError('Positive integer value expected in function permutations');
314 }
315-
316+
317 // Permute n objects
318 if (arity == 1) {
319 return math.factorial(n);
320 }
321-
322+
323 // Permute n objects, k at a time
324 if (arity == 2) {
325 if (isNumber(k)) {
326@@ -15525,82 +15519,82 @@
327 /* 118 */
328 /***/ function(module, exports, __webpack_require__) {
329
330- 'use strict';
331-
332- module.exports = function (math) {
333- var util = __webpack_require__(147),
334-
335- BigNumber = math.type.BigNumber,
336- Complex = __webpack_require__(6),
337- Unit = __webpack_require__(10),
338- collection = __webpack_require__(13),
339-
340- isNumber = util.number.isNumber,
341- isBoolean = util['boolean'].isBoolean,
342- isComplex = Complex.isComplex,
343- isUnit = Unit.isUnit,
344- isCollection = collection.isCollection;
345-
346- /**
347- * Calculate the hyperbolic cosine of a value,
348- * defined as `cosh(x) = 1/2 * (exp(x) + exp(-x))`.
349- *
350- * For matrices, the function is evaluated element wise.
351- *
352- * Syntax:
353- *
354- * math.cosh(x)
355- *
356- * Examples:
357- *
358- * math.cosh(0.5); // returns Number 1.1276259652063807
359- *
360- * See also:
361- *
362- * sinh, tanh
363- *
364- * @param {Number | Boolean | Complex | Unit | Array | Matrix | null} x Function input
365- * @return {Number | Complex | Array | Matrix} Hyperbolic cosine of x
366- */
367- math.cosh = function cosh(x) {
368- if (arguments.length != 1) {
369- throw new math.error.ArgumentsError('cosh', arguments.length, 1);
370- }
371-
372- if (isNumber(x)) {
373- return (Math.exp(x) + Math.exp(-x)) / 2;
374- }
375-
376- if (isComplex(x)) {
377- var ep = Math.exp(x.re);
378- var en = Math.exp(-x.re);
379- return new Complex(Math.cos(x.im) * (ep + en) / 2, Math.sin(x.im) * (ep - en) / 2);
380- }
381-
382- if (isUnit(x)) {
383- if (!x.hasBase(Unit.BASE_UNITS.ANGLE)) {
384- throw new TypeError ('Unit in function cosh is no angle');
385- }
386- return cosh(x.value);
387- }
388-
389- if (isCollection(x)) {
390- return collection.deepMap(x, cosh);
391- }
392-
393- if (isBoolean(x) || x === null) {
394- return cosh(x ? 1 : 0);
395- }
396-
397- if (x instanceof BigNumber) {
398- // TODO: implement BigNumber support
399- // downgrade to Number
400- return cosh(x.toNumber());
401- }
402-
403- throw new math.error.UnsupportedTypeError('cosh', math['typeof'](x));
404- };
405- };
406+ 'use strict';
407+
408+ module.exports = function (math) {
409+ var util = __webpack_require__(147),
410+
411+ BigNumber = math.type.BigNumber,
412+ Complex = __webpack_require__(6),
413+ Unit = __webpack_require__(10),
414+ collection = __webpack_require__(13),
415+
416+ isNumber = util.number.isNumber,
417+ isBoolean = util['boolean'].isBoolean,
418+ isComplex = Complex.isComplex,
419+ isUnit = Unit.isUnit,
420+ isCollection = collection.isCollection;
421+
422+ /**
423+ * Calculate the hyperbolic cosine of a value,
424+ * defined as `cosh(x) = 1/2 * (exp(x) + exp(-x))`.
425+ *
426+ * For matrices, the function is evaluated element wise.
427+ *
428+ * Syntax:
429+ *
430+ * math.cosh(x)
431+ *
432+ * Examples:
433+ *
434+ * math.cosh(0.5); // returns Number 1.1276259652063807
435+ *
436+ * See also:
437+ *
438+ * sinh, tanh
439+ *
440+ * @param {Number | Boolean | Complex | Unit | Array | Matrix | null} x Function input
441+ * @return {Number | Complex | Array | Matrix} Hyperbolic cosine of x
442+ */
443+ math.cosh = function cosh(x) {
444+ if (arguments.length != 1) {
445+ throw new math.error.ArgumentsError('cosh', arguments.length, 1);
446+ }
447+
448+ if (isNumber(x)) {
449+ return (Math.exp(x) + Math.exp(-x)) / 2;
450+ }
451+
452+ if (isComplex(x)) {
453+ var ep = Math.exp(x.re);
454+ var en = Math.exp(-x.re);
455+ return new Complex(Math.cos(x.im) * (ep + en) / 2, Math.sin(x.im) * (ep - en) / 2);
456+ }
457+
458+ if (isUnit(x)) {
459+ if (!x.hasBase(Unit.BASE_UNITS.ANGLE)) {
460+ throw new TypeError ('Unit in function cosh is no angle');
461+ }
462+ return cosh(x.value);
463+ }
464+
465+ if (isCollection(x)) {
466+ return collection.deepMap(x, cosh);
467+ }
468+
469+ if (isBoolean(x) || x === null) {
470+ return cosh(x ? 1 : 0);
471+ }
472+
473+ if (x instanceof BigNumber) {
474+ // TODO: implement BigNumber support
475+ // downgrade to Number
476+ return cosh(x.toNumber());
477+ }
478+
479+ throw new math.error.UnsupportedTypeError('cosh', math['typeof'](x));
480+ };
481+ };
482
483
484 /***/ },
485@@ -15693,90 +15687,90 @@
486 /* 120 */
487 /***/ function(module, exports, __webpack_require__) {
488
489- 'use strict';
490-
491- module.exports = function (math) {
492- var util = __webpack_require__(147),
493-
494- BigNumber = math.type.BigNumber,
495- Complex = __webpack_require__(6),
496- Unit = __webpack_require__(10),
497- collection = __webpack_require__(13),
498-
499- isNumber = util.number.isNumber,
500- isBoolean = util['boolean'].isBoolean,
501- isComplex = Complex.isComplex,
502- isUnit = Unit.isUnit,
503- isCollection = collection.isCollection;
504-
505- /**
506- * Calculate the hyperbolic cotangent of a value,
507- * defined as `coth(x) = 1 / tanh(x)`.
508- *
509- * For matrices, the function is evaluated element wise.
510- *
511- * Syntax:
512- *
513- * math.coth(x)
514- *
515- * Examples:
516- *
517- * // coth(x) = 1 / tanh(x)
518- * math.coth(2); // returns 1.0373147207275482
519- * 1 / math.tanh(2); // returns 1.0373147207275482
520- *
521- * See also:
522- *
523- * sinh, tanh, cosh
524- *
525- * @param {Number | Boolean | Complex | Unit | Array | Matrix | null} x Function input
526- * @return {Number | Complex | Array | Matrix} Hyperbolic cotangent of x
527- */
528- math.coth = function coth(x) {
529- if (arguments.length != 1) {
530- throw new math.error.ArgumentsError('coth', arguments.length, 1);
531- }
532-
533- if (isNumber(x)) {
534- var e = Math.exp(2 * x);
535- return (e + 1) / (e - 1);
536- }
537-
538- if (isComplex(x)) {
539- var r = Math.exp(2 * x.re);
540- var re = r * Math.cos(2 * x.im);
541- var im = r * Math.sin(2 * x.im);
542- var den = (re - 1) * (re - 1) + im * im;
543- return new Complex(
544- ((re + 1) * (re - 1) + im * im) / den,
545- -2 * im / den
546- );
547- }
548-
549- if (isUnit(x)) {
550- if (!x.hasBase(Unit.BASE_UNITS.ANGLE)) {
551- throw new TypeError ('Unit in function coth is no angle');
552- }
553- return coth(x.value);
554- }
555-
556- if (isCollection(x)) {
557- return collection.deepMap(x, coth);
558- }
559-
560- if (isBoolean(x) || x === null) {
561- return coth(x ? 1 : 0);
562- }
563-
564- if (x instanceof BigNumber) {
565- // TODO: implement BigNumber support
566- // downgrade to Number
567- return coth(x.toNumber());
568- }
569-
570- throw new math.error.UnsupportedTypeError('coth', math['typeof'](x));
571- };
572- };
573+ 'use strict';
574+
575+ module.exports = function (math) {
576+ var util = __webpack_require__(147),
577+
578+ BigNumber = math.type.BigNumber,
579+ Complex = __webpack_require__(6),
580+ Unit = __webpack_require__(10),
581+ collection = __webpack_require__(13),
582+
583+ isNumber = util.number.isNumber,
584+ isBoolean = util['boolean'].isBoolean,
585+ isComplex = Complex.isComplex,
586+ isUnit = Unit.isUnit,
587+ isCollection = collection.isCollection;
588+
589+ /**
590+ * Calculate the hyperbolic cotangent of a value,
591+ * defined as `coth(x) = 1 / tanh(x)`.
592+ *
593+ * For matrices, the function is evaluated element wise.
594+ *
595+ * Syntax:
596+ *
597+ * math.coth(x)
598+ *
599+ * Examples:
600+ *
601+ * // coth(x) = 1 / tanh(x)
602+ * math.coth(2); // returns 1.0373147207275482
603+ * 1 / math.tanh(2); // returns 1.0373147207275482
604+ *
605+ * See also:
606+ *
607+ * sinh, tanh, cosh
608+ *
609+ * @param {Number | Boolean | Complex | Unit | Array | Matrix | null} x Function input
610+ * @return {Number | Complex | Array | Matrix} Hyperbolic cotangent of x
611+ */
612+ math.coth = function coth(x) {
613+ if (arguments.length != 1) {
614+ throw new math.error.ArgumentsError('coth', arguments.length, 1);
615+ }
616+
617+ if (isNumber(x)) {
618+ var e = Math.exp(2 * x);
619+ return (e + 1) / (e - 1);
620+ }
621+
622+ if (isComplex(x)) {
623+ var r = Math.exp(2 * x.re);
624+ var re = r * Math.cos(2 * x.im);
625+ var im = r * Math.sin(2 * x.im);
626+ var den = (re - 1) * (re - 1) + im * im;
627+ return new Complex(
628+ ((re + 1) * (re - 1) + im * im) / den,
629+ -2 * im / den
630+ );
631+ }
632+
633+ if (isUnit(x)) {
634+ if (!x.hasBase(Unit.BASE_UNITS.ANGLE)) {
635+ throw new TypeError ('Unit in function coth is no angle');
636+ }
637+ return coth(x.value);
638+ }
639+
640+ if (isCollection(x)) {
641+ return collection.deepMap(x, coth);
642+ }
643+
644+ if (isBoolean(x) || x === null) {
645+ return coth(x ? 1 : 0);
646+ }
647+
648+ if (x instanceof BigNumber) {
649+ // TODO: implement BigNumber support
650+ // downgrade to Number
651+ return coth(x.toNumber());
652+ }
653+
654+ throw new math.error.UnsupportedTypeError('coth', math['typeof'](x));
655+ };
656+ };
657
658
659 /***/ },
660@@ -15870,91 +15864,91 @@
661 /* 122 */
662 /***/ function(module, exports, __webpack_require__) {
663
664- 'use strict';
665-
666- module.exports = function (math) {
667- var util = __webpack_require__(147),
668-
669- BigNumber = math.type.BigNumber,
670- Complex = __webpack_require__(6),
671- Unit = __webpack_require__(10),
672- collection = __webpack_require__(13),
673- number = util.number,
674-
675- isNumber = util.number.isNumber,
676- isBoolean = util['boolean'].isBoolean,
677- isComplex = Complex.isComplex,
678- isUnit = Unit.isUnit,
679- isCollection = collection.isCollection;
680-
681- /**
682- * Calculate the hyperbolic cosecant of a value,
683- * defined as `csch(x) = 1 / sinh(x)`.
684- *
685- * For matrices, the function is evaluated element wise.
686- *
687- * Syntax:
688- *
689- * math.csch(x)
690- *
691- * Examples:
692- *
693- * // csch(x) = 1/ sinh(x)
694- * math.csch(0.5); // returns 1.9190347513349437
695- * 1 / math.sinh(0.5); // returns 1.9190347513349437
696- *
697- * See also:
698- *
699- * sinh, sech, coth
700- *
701- * @param {Number | Boolean | Complex | Unit | Array | Matrix | null} x Function input
702- * @return {Number | Complex | Array | Matrix} Hyperbolic cosecant of x
703- */
704- math.csch = function csch(x) {
705- if (arguments.length != 1) {
706- throw new math.error.ArgumentsError('csch', arguments.length, 1);
707- }
708-
709- if (isNumber(x)) {
710- // x == 0
711- if (x == 0) return Number.NaN;
712- // consider values close to zero (+/-)
713- return Math.abs(2 / (Math.exp(x) - Math.exp(-x))) * number.sign(x);
714- }
715-
716- if (isComplex(x)) {
717- var ep = Math.exp(x.re);
718- var en = Math.exp(-x.re);
719- var re = Math.cos(x.im) * (ep - en);
720- var im = Math.sin(x.im) * (ep + en);
721- var den = re * re + im * im;
722- return new Complex(2 * re / den, -2 * im /den);
723- }
724-
725- if (isUnit(x)) {
726- if (!x.hasBase(Unit.BASE_UNITS.ANGLE)) {
727- throw new TypeError ('Unit in function csch is no angle');
728- }
729- return csch(x.value);
730- }
731-
732- if (isCollection(x)) {
733- return collection.deepMap(x, csch);
734- }
735-
736- if (isBoolean(x) || x === null) {
737- return csch(x ? 1 : 0);
738- }
739-
740- if (x instanceof BigNumber) {
741- // TODO: implement BigNumber support
742- // downgrade to Number
743- return csch(x.toNumber());
744- }
745-
746- throw new math.error.UnsupportedTypeError('csch', math['typeof'](x));
747- };
748- };
749+ 'use strict';
750+
751+ module.exports = function (math) {
752+ var util = __webpack_require__(147),
753+
754+ BigNumber = math.type.BigNumber,
755+ Complex = __webpack_require__(6),
756+ Unit = __webpack_require__(10),
757+ collection = __webpack_require__(13),
758+ number = util.number,
759+
760+ isNumber = util.number.isNumber,
761+ isBoolean = util['boolean'].isBoolean,
762+ isComplex = Complex.isComplex,
763+ isUnit = Unit.isUnit,
764+ isCollection = collection.isCollection;
765+
766+ /**
767+ * Calculate the hyperbolic cosecant of a value,
768+ * defined as `csch(x) = 1 / sinh(x)`.
769+ *
770+ * For matrices, the function is evaluated element wise.
771+ *
772+ * Syntax:
773+ *
774+ * math.csch(x)
775+ *
776+ * Examples:
777+ *
778+ * // csch(x) = 1/ sinh(x)
779+ * math.csch(0.5); // returns 1.9190347513349437
780+ * 1 / math.sinh(0.5); // returns 1.9190347513349437
781+ *
782+ * See also:
783+ *
784+ * sinh, sech, coth
785+ *
786+ * @param {Number | Boolean | Complex | Unit | Array | Matrix | null} x Function input
787+ * @return {Number | Complex | Array | Matrix} Hyperbolic cosecant of x
788+ */
789+ math.csch = function csch(x) {
790+ if (arguments.length != 1) {
791+ throw new math.error.ArgumentsError('csch', arguments.length, 1);
792+ }
793+
794+ if (isNumber(x)) {
795+ // x == 0
796+ if (x == 0) return Number.NaN;
797+ // consider values close to zero (+/-)
798+ return Math.abs(2 / (Math.exp(x) - Math.exp(-x))) * number.sign(x);
799+ }
800+
801+ if (isComplex(x)) {
802+ var ep = Math.exp(x.re);
803+ var en = Math.exp(-x.re);
804+ var re = Math.cos(x.im) * (ep - en);
805+ var im = Math.sin(x.im) * (ep + en);
806+ var den = re * re + im * im;
807+ return new Complex(2 * re / den, -2 * im /den);
808+ }
809+
810+ if (isUnit(x)) {
811+ if (!x.hasBase(Unit.BASE_UNITS.ANGLE)) {
812+ throw new TypeError ('Unit in function csch is no angle');
813+ }
814+ return csch(x.value);
815+ }
816+
817+ if (isCollection(x)) {
818+ return collection.deepMap(x, csch);
819+ }
820+
821+ if (isBoolean(x) || x === null) {
822+ return csch(x ? 1 : 0);
823+ }
824+
825+ if (x instanceof BigNumber) {
826+ // TODO: implement BigNumber support
827+ // downgrade to Number
828+ return csch(x.toNumber());
829+ }
830+
831+ throw new math.error.UnsupportedTypeError('csch', math['typeof'](x));
832+ };
833+ };
834
835
836 /***/ },
837@@ -16048,87 +16042,87 @@
838 /* 124 */
839 /***/ function(module, exports, __webpack_require__) {
840
841- 'use strict';
842-
843- module.exports = function (math) {
844- var util = __webpack_require__(147),
845-
846- BigNumber = math.type.BigNumber,
847- Complex = __webpack_require__(6),
848- Unit = __webpack_require__(10),
849- collection = __webpack_require__(13),
850-
851- isNumber = util.number.isNumber,
852- isBoolean = util['boolean'].isBoolean,
853- isComplex = Complex.isComplex,
854- isUnit = Unit.isUnit,
855- isCollection = collection.isCollection;
856-
857- /**
858- * Calculate the hyperbolic secant of a value,
859- * defined as `sech(x) = 1 / cosh(x)`.
860- *
861- * For matrices, the function is evaluated element wise.
862- *
863- * Syntax:
864- *
865- * math.sech(x)
866- *
867- * Examples:
868- *
869- * // sech(x) = 1/ cosh(x)
870- * math.sech(0.5); // returns 0.886818883970074
871- * 1 / math.cosh(0.5); // returns 1.9190347513349437
872- *
873- * See also:
874- *
875- * cosh, csch, coth
876- *
877- * @param {Number | Boolean | Complex | Unit | Array | Matrix | null} x Function input
878- * @return {Number | Complex | Array | Matrix} Hyperbolic secant of x
879- */
880- math.sech = function sech(x) {
881- if (arguments.length != 1) {
882- throw new math.error.ArgumentsError('sech', arguments.length, 1);
883- }
884-
885- if (isNumber(x)) {
886- return 2 / (Math.exp(x) + Math.exp(-x));
887- }
888-
889- if (isComplex(x)) {
890- var ep = Math.exp(x.re);
891- var en = Math.exp(-x.re);
892- var re = Math.cos(x.im) * (ep + en);
893- var im = Math.sin(x.im) * (ep - en);
894- var den = re * re + im * im;
895- return new Complex(2 * re / den, -2 * im / den);
896- }
897-
898- if (isUnit(x)) {
899- if (!x.hasBase(Unit.BASE_UNITS.ANGLE)) {
900- throw new TypeError ('Unit in function sech is no angle');
901- }
902- return sech(x.value);
903- }
904-
905- if (isCollection(x)) {
906- return collection.deepMap(x, sech);
907- }
908-
909- if (isBoolean(x) || x === null) {
910- return sech(x ? 1 : 0);
911- }
912-
913- if (x instanceof BigNumber) {
914- // TODO: implement BigNumber support
915- // downgrade to Number
916- return sech(x.toNumber());
917- }
918-
919- throw new math.error.UnsupportedTypeError('sech', math['typeof'](x));
920- };
921- };
922+ 'use strict';
923+
924+ module.exports = function (math) {
925+ var util = __webpack_require__(147),
926+
927+ BigNumber = math.type.BigNumber,
928+ Complex = __webpack_require__(6),
929+ Unit = __webpack_require__(10),
930+ collection = __webpack_require__(13),
931+
932+ isNumber = util.number.isNumber,
933+ isBoolean = util['boolean'].isBoolean,
934+ isComplex = Complex.isComplex,
935+ isUnit = Unit.isUnit,
936+ isCollection = collection.isCollection;
937+
938+ /**
939+ * Calculate the hyperbolic secant of a value,
940+ * defined as `sech(x) = 1 / cosh(x)`.
941+ *
942+ * For matrices, the function is evaluated element wise.
943+ *
944+ * Syntax:
945+ *
946+ * math.sech(x)
947+ *
948+ * Examples:
949+ *
950+ * // sech(x) = 1/ cosh(x)
951+ * math.sech(0.5); // returns 0.886818883970074
952+ * 1 / math.cosh(0.5); // returns 1.9190347513349437
953+ *
954+ * See also:
955+ *
956+ * cosh, csch, coth
957+ *
958+ * @param {Number | Boolean | Complex | Unit | Array | Matrix | null} x Function input
959+ * @return {Number | Complex | Array | Matrix} Hyperbolic secant of x
960+ */
961+ math.sech = function sech(x) {
962+ if (arguments.length != 1) {
963+ throw new math.error.ArgumentsError('sech', arguments.length, 1);
964+ }
965+
966+ if (isNumber(x)) {
967+ return 2 / (Math.exp(x) + Math.exp(-x));
968+ }
969+
970+ if (isComplex(x)) {
971+ var ep = Math.exp(x.re);
972+ var en = Math.exp(-x.re);
973+ var re = Math.cos(x.im) * (ep + en);
974+ var im = Math.sin(x.im) * (ep - en);
975+ var den = re * re + im * im;
976+ return new Complex(2 * re / den, -2 * im / den);
977+ }
978+
979+ if (isUnit(x)) {
980+ if (!x.hasBase(Unit.BASE_UNITS.ANGLE)) {
981+ throw new TypeError ('Unit in function sech is no angle');
982+ }
983+ return sech(x.value);
984+ }
985+
986+ if (isCollection(x)) {
987+ return collection.deepMap(x, sech);
988+ }
989+
990+ if (isBoolean(x) || x === null) {
991+ return sech(x ? 1 : 0);
992+ }
993+
994+ if (x instanceof BigNumber) {
995+ // TODO: implement BigNumber support
996+ // downgrade to Number
997+ return sech(x.toNumber());
998+ }
999+
1000+ throw new math.error.UnsupportedTypeError('sech', math['typeof'](x));
1001+ };
1002+ };
1003
1004
1005 /***/ },
1006@@ -16223,84 +16217,84 @@
1007 /* 126 */
1008 /***/ function(module, exports, __webpack_require__) {
1009
1010- 'use strict';
1011-
1012- module.exports = function (math) {
1013- var util = __webpack_require__(147),
1014-
1015- BigNumber = math.type.BigNumber,
1016- Complex = __webpack_require__(6),
1017- Unit = __webpack_require__(10),
1018- collection = __webpack_require__(13),
1019-
1020- isNumber = util.number.isNumber,
1021- isBoolean = util['boolean'].isBoolean,
1022- isComplex = Complex.isComplex,
1023- isUnit = Unit.isUnit,
1024- isCollection = collection.isCollection;
1025-
1026- /**
1027- * Calculate the hyperbolic sine of a value,
1028- * defined as `sinh(x) = 1/2 * (exp(x) - exp(-x))`.
1029- *
1030- * For matrices, the function is evaluated element wise.
1031- *
1032- * Syntax:
1033- *
1034- * math.sinh(x)
1035- *
1036- * Examples:
1037- *
1038- * math.sinh(0.5); // returns Number 0.5210953054937474
1039- *
1040- * See also:
1041- *
1042- * cosh, tanh
1043- *
1044- * @param {Number | Boolean | Complex | Unit | Array | Matrix | null} x Function input
1045- * @return {Number | Complex | Array | Matrix} Hyperbolic sine of x
1046- */
1047- math.sinh = function sinh(x) {
1048- if (arguments.length != 1) {
1049- throw new math.error.ArgumentsError('sinh', arguments.length, 1);
1050- }
1051-
1052- if (isNumber(x)) {
1053- return (Math.exp(x) - Math.exp(-x)) / 2;
1054- }
1055-
1056- if (isComplex(x)) {
1057- var cim = Math.cos(x.im);
1058- var sim = Math.sin(x.im);
1059- var ep = Math.exp(x.re);
1060- var en = Math.exp(-x.re);
1061- return new Complex(cim * (ep - en) / 2, sim * (ep + en) / 2);
1062- }
1063-
1064- if (isUnit(x)) {
1065- if (!x.hasBase(Unit.BASE_UNITS.ANGLE)) {
1066- throw new TypeError ('Unit in function sinh is no angle');
1067- }
1068- return sinh(x.value);
1069- }
1070-
1071- if (isCollection(x)) {
1072- return collection.deepMap(x, sinh);
1073- }
1074-
1075- if (isBoolean(x) || x === null) {
1076- return sinh(x ? 1 : 0);
1077- }
1078-
1079- if (x instanceof BigNumber) {
1080- // TODO: implement BigNumber support
1081- // downgrade to Number
1082- return sinh(x.toNumber());
1083- }
1084-
1085- throw new math.error.UnsupportedTypeError('sinh', math['typeof'](x));
1086- };
1087- };
1088+ 'use strict';
1089+
1090+ module.exports = function (math) {
1091+ var util = __webpack_require__(147),
1092+
1093+ BigNumber = math.type.BigNumber,
1094+ Complex = __webpack_require__(6),
1095+ Unit = __webpack_require__(10),
1096+ collection = __webpack_require__(13),
1097+
1098+ isNumber = util.number.isNumber,
1099+ isBoolean = util['boolean'].isBoolean,
1100+ isComplex = Complex.isComplex,
1101+ isUnit = Unit.isUnit,
1102+ isCollection = collection.isCollection;
1103+
1104+ /**
1105+ * Calculate the hyperbolic sine of a value,
1106+ * defined as `sinh(x) = 1/2 * (exp(x) - exp(-x))`.
1107+ *
1108+ * For matrices, the function is evaluated element wise.
1109+ *
1110+ * Syntax:
1111+ *
1112+ * math.sinh(x)
1113+ *
1114+ * Examples:
1115+ *
1116+ * math.sinh(0.5); // returns Number 0.5210953054937474
1117+ *
1118+ * See also:
1119+ *
1120+ * cosh, tanh
1121+ *
1122+ * @param {Number | Boolean | Complex | Unit | Array | Matrix | null} x Function input
1123+ * @return {Number | Complex | Array | Matrix} Hyperbolic sine of x
1124+ */
1125+ math.sinh = function sinh(x) {
1126+ if (arguments.length != 1) {
1127+ throw new math.error.ArgumentsError('sinh', arguments.length, 1);
1128+ }
1129+
1130+ if (isNumber(x)) {
1131+ return (Math.exp(x) - Math.exp(-x)) / 2;
1132+ }
1133+
1134+ if (isComplex(x)) {
1135+ var cim = Math.cos(x.im);
1136+ var sim = Math.sin(x.im);
1137+ var ep = Math.exp(x.re);
1138+ var en = Math.exp(-x.re);
1139+ return new Complex(cim * (ep - en) / 2, sim * (ep + en) / 2);
1140+ }
1141+
1142+ if (isUnit(x)) {
1143+ if (!x.hasBase(Unit.BASE_UNITS.ANGLE)) {
1144+ throw new TypeError ('Unit in function sinh is no angle');
1145+ }
1146+ return sinh(x.value);
1147+ }
1148+
1149+ if (isCollection(x)) {
1150+ return collection.deepMap(x, sinh);
1151+ }
1152+
1153+ if (isBoolean(x) || x === null) {
1154+ return sinh(x ? 1 : 0);
1155+ }
1156+
1157+ if (x instanceof BigNumber) {
1158+ // TODO: implement BigNumber support
1159+ // downgrade to Number
1160+ return sinh(x.toNumber());
1161+ }
1162+
1163+ throw new math.error.UnsupportedTypeError('sinh', math['typeof'](x));
1164+ };
1165+ };
1166
1167
1168 /***/ },
1169@@ -16396,91 +16390,91 @@
1170 /* 128 */
1171 /***/ function(module, exports, __webpack_require__) {
1172
1173- 'use strict';
1174-
1175- module.exports = function (math) {
1176- var util = __webpack_require__(147),
1177-
1178- BigNumber = math.type.BigNumber,
1179- Complex = __webpack_require__(6),
1180- Unit = __webpack_require__(10),
1181- collection = __webpack_require__(13),
1182-
1183- isNumber = util.number.isNumber,
1184- isBoolean = util['boolean'].isBoolean,
1185- isComplex = Complex.isComplex,
1186- isUnit = Unit.isUnit,
1187- isCollection = collection.isCollection;
1188-
1189- /**
1190- * Calculate the hyperbolic tangent of a value,
1191- * defined as `tanh(x) = (exp(2 * x) - 1) / (exp(2 * x) + 1)`.
1192- *
1193- * For matrices, the function is evaluated element wise.
1194- *
1195- * Syntax:
1196- *
1197- * math.tanh(x)
1198- *
1199- * Examples:
1200- *
1201- * // tanh(x) = sinh(x) / cosh(x) = 1 / coth(x)
1202- * math.tanh(0.5); // returns 0.46211715726000974
1203- * math.sinh(0.5) / math.cosh(0.5); // returns 0.46211715726000974
1204- * 1 / math.coth(0.5); // returns 0.46211715726000974
1205- *
1206- * See also:
1207- *
1208- * sinh, cosh, coth
1209- *
1210- * @param {Number | Boolean | Complex | Unit | Array | Matrix | null} x Function input
1211- * @return {Number | Complex | Array | Matrix} Hyperbolic tangent of x
1212- */
1213- math.tanh = function tanh(x) {
1214- if (arguments.length != 1) {
1215- throw new math.error.ArgumentsError('tanh', arguments.length, 1);
1216- }
1217-
1218- if (isNumber(x)) {
1219- var e = Math.exp(2 * x);
1220- return (e - 1) / (e + 1);
1221- }
1222-
1223- if (isComplex(x)) {
1224- var r = Math.exp(2 * x.re);
1225- var re = r * Math.cos(2 * x.im);
1226- var im = r * Math.sin(2 * x.im);
1227- var den = (re + 1) * (re + 1) + im * im;
1228- return new Complex(
1229- ((re - 1) * (re + 1) + im * im) / den,
1230- im * 2 / den
1231- );
1232- }
1233-
1234- if (isUnit(x)) {
1235- if (!x.hasBase(Unit.BASE_UNITS.ANGLE)) {
1236- throw new TypeError ('Unit in function tanh is no angle');
1237- }
1238- return tanh(x.value);
1239- }
1240-
1241- if (isCollection(x)) {
1242- return collection.deepMap(x, tanh);
1243- }
1244-
1245- if (isBoolean(x) || x === null) {
1246- return tanh(x ? 1 : 0);
1247- }
1248-
1249- if (x instanceof BigNumber) {
1250- // TODO: implement BigNumber support
1251- // downgrade to Number
1252- return tanh(x.toNumber());
1253- }
1254-
1255- throw new math.error.UnsupportedTypeError('tanh', math['typeof'](x));
1256- };
1257- };
1258+ 'use strict';
1259+
1260+ module.exports = function (math) {
1261+ var util = __webpack_require__(147),
1262+
1263+ BigNumber = math.type.BigNumber,
1264+ Complex = __webpack_require__(6),
1265+ Unit = __webpack_require__(10),
1266+ collection = __webpack_require__(13),
1267+
1268+ isNumber = util.number.isNumber,
1269+ isBoolean = util['boolean'].isBoolean,
1270+ isComplex = Complex.isComplex,
1271+ isUnit = Unit.isUnit,
1272+ isCollection = collection.isCollection;
1273+
1274+ /**
1275+ * Calculate the hyperbolic tangent of a value,
1276+ * defined as `tanh(x) = (exp(2 * x) - 1) / (exp(2 * x) + 1)`.
1277+ *
1278+ * For matrices, the function is evaluated element wise.
1279+ *
1280+ * Syntax:
1281+ *
1282+ * math.tanh(x)
1283+ *
1284+ * Examples:
1285+ *
1286+ * // tanh(x) = sinh(x) / cosh(x) = 1 / coth(x)
1287+ * math.tanh(0.5); // returns 0.46211715726000974
1288+ * math.sinh(0.5) / math.cosh(0.5); // returns 0.46211715726000974
1289+ * 1 / math.coth(0.5); // returns 0.46211715726000974
1290+ *
1291+ * See also:
1292+ *
1293+ * sinh, cosh, coth
1294+ *
1295+ * @param {Number | Boolean | Complex | Unit | Array | Matrix | null} x Function input
1296+ * @return {Number | Complex | Array | Matrix} Hyperbolic tangent of x
1297+ */
1298+ math.tanh = function tanh(x) {
1299+ if (arguments.length != 1) {
1300+ throw new math.error.ArgumentsError('tanh', arguments.length, 1);
1301+ }
1302+
1303+ if (isNumber(x)) {
1304+ var e = Math.exp(2 * x);
1305+ return (e - 1) / (e + 1);
1306+ }
1307+
1308+ if (isComplex(x)) {
1309+ var r = Math.exp(2 * x.re);
1310+ var re = r * Math.cos(2 * x.im);
1311+ var im = r * Math.sin(2 * x.im);
1312+ var den = (re + 1) * (re + 1) + im * im;
1313+ return new Complex(
1314+ ((re - 1) * (re + 1) + im * im) / den,
1315+ im * 2 / den
1316+ );
1317+ }
1318+
1319+ if (isUnit(x)) {
1320+ if (!x.hasBase(Unit.BASE_UNITS.ANGLE)) {
1321+ throw new TypeError ('Unit in function tanh is no angle');
1322+ }
1323+ return tanh(x.value);
1324+ }
1325+
1326+ if (isCollection(x)) {
1327+ return collection.deepMap(x, tanh);
1328+ }
1329+
1330+ if (isBoolean(x) || x === null) {
1331+ return tanh(x ? 1 : 0);
1332+ }
1333+
1334+ if (x instanceof BigNumber) {
1335+ // TODO: implement BigNumber support
1336+ // downgrade to Number
1337+ return tanh(x.toNumber());
1338+ }
1339+
1340+ throw new math.error.UnsupportedTypeError('tanh', math['typeof'](x));
1341+ };
1342+ };
1343
1344
1345 /***/ },
1346@@ -17873,3989 +17867,3989 @@
1347 /* 142 */
1348 /***/ function(module, exports, __webpack_require__) {
1349
1350- var __WEBPACK_AMD_DEFINE_RESULT__;/*! decimal.js v3.0.1 https://github.com/MikeMcl/decimal.js/LICENCE */
1351- ;(function (global) {
1352- 'use strict';
1353-
1354-
1355- /*
1356- * decimal.js v3.0.1
1357- * An arbitrary-precision Decimal type for JavaScript.
1358- * https://github.com/MikeMcl/decimal.js
1359- * Copyright (c) 2014 Michael Mclaughlin <M8ch88l@gmail.com>
1360- * MIT Expat Licence
1361- */
1362-
1363-
1364- var convertBase, DecimalConstructor, noConflict,
1365- crypto = global['crypto'],
1366- external = true,
1367- id = 0,
1368- mathfloor = Math.floor,
1369- mathpow = Math.pow,
1370- outOfRange,
1371- toString = Object.prototype.toString,
1372- BASE = 1e7,
1373- LOGBASE = 7,
1374- NUMERALS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_',
1375- P = {},
1376-
1377- /*
1378- The maximum exponent magnitude.
1379- The limit on the value of toExpNeg, toExpPos, minE and maxE.
1380- */
1381- EXP_LIMIT = 9e15, // 0 to 9e15
1382-
1383- /*
1384- The limit on the value of precision, and on the argument to toDecimalPlaces,
1385- toExponential, toFixed, toFormat, toPrecision and toSignificantDigits.
1386- */
1387- MAX_DIGITS = 1E9, // 0 to 1e+9
1388-
1389- /*
1390- To decide whether or not to calculate x.pow(integer y) using the 'exponentiation by
1391- squaring' algorithm or by exp(y*ln(x)), the number of significant digits of x is multiplied
1392- by y. If this number is less than INT_POW_LIMIT then the former algorithm is used.
1393- */
1394- INT_POW_LIMIT = 3000, // 0 to 5000
1395-
1396- // The natural logarithm of 10 (1025 digits).
1397- LN10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058';
1398-
1399-
1400- // Decimal prototype methods
1401-
1402-
1403- /*
1404- * Return a new Decimal whose value is the absolute value of this Decimal.
1405- *
1406- */
1407- P['absoluteValue'] = P['abs'] = function () {
1408- var x = new this['constructor'](this);
1409-
1410- if ( x['s'] < 0 ) {
1411- x['s'] = 1;
1412- }
1413-
1414- return rnd(x);
1415- };
1416-
1417-
1418- /*
1419- * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in
1420- * the direction of positive Infinity.
1421- *
1422- */
1423- P['ceil'] = function () {
1424-
1425- return rnd( new this['constructor'](this), this['e'] + 1, 2 );
1426- };
1427-
1428-
1429- /*
1430- * Return
1431- * 1 if the value of this Decimal is greater than the value of Decimal(y, b),
1432- * -1 if the value of this Decimal is less than the value of Decimal(y, b),
1433- * 0 if they have the same value,
1434- * null if the value of either Decimal is NaN.
1435- *
1436- */
1437- P['comparedTo'] = P['cmp'] = function ( y, b ) {
1438- var a,
1439- x = this,
1440- xc = x['c'],
1441- yc = ( id = -id, y = new x['constructor']( y, b ), y['c'] ),
1442- i = x['s'],
1443- j = y['s'],
1444- k = x['e'],
1445- l = y['e'];
1446-
1447- // Either NaN?
1448- if ( !i || !j ) {
1449- return null;
1450- }
1451-
1452- a = xc && !xc[0];
1453- b = yc && !yc[0];
1454-
1455- // Either zero?
1456- if ( a || b ) {
1457- return a ? b ? 0 : -j : i;
1458- }
1459-
1460- // Signs differ?
1461- if ( i != j ) {
1462- return i;
1463- }
1464-
1465- a = i < 0;
1466-
1467- // Either Infinity?
1468- if ( !xc || !yc ) {
1469- return k == l ? 0 : !xc ^ a ? 1 : -1;
1470- }
1471-
1472- // Compare exponents.
1473- if ( k != l ) {
1474- return k > l ^ a ? 1 : -1;
1475- }
1476-
1477- // Compare digit by digit.
1478- for ( i = -1,
1479- j = ( k = xc.length ) < ( l = yc.length ) ? k : l;
1480- ++i < j; ) {
1481-
1482- if ( xc[i] != yc[i] ) {
1483- return xc[i] > yc[i] ^ a ? 1 : -1;
1484- }
1485- }
1486-
1487- // Compare lengths.
1488- return k == l ? 0 : k > l ^ a ? 1 : -1;
1489- };
1490-
1491-
1492- /*
1493- * Return the number of decimal places of the value of this Decimal.
1494- *
1495- */
1496- P['decimalPlaces'] = P['dp'] = function () {
1497- var c, v,
1498- n = null;
1499-
1500- if ( c = this['c'] ) {
1501- n = ( ( v = c.length - 1 ) - mathfloor( this['e'] / LOGBASE ) ) * LOGBASE;
1502-
1503- if ( v = c[v] ) {
1504-
1505- // Subtract the number of trailing zeros of the last number.
1506- for ( ; v % 10 == 0; v /= 10, n-- );
1507- }
1508-
1509- if ( n < 0 ) {
1510- n = 0;
1511- }
1512- }
1513-
1514- return n;
1515- };
1516-
1517-
1518- /*
1519- * n / 0 = I
1520- * n / N = N
1521- * n / I = 0
1522- * 0 / n = 0
1523- * 0 / 0 = N
1524- * 0 / N = N
1525- * 0 / I = 0
1526- * N / n = N
1527- * N / 0 = N
1528- * N / N = N
1529- * N / I = N
1530- * I / n = I
1531- * I / 0 = I
1532- * I / N = N
1533- * I / I = N
1534- *
1535- * Return a new Decimal whose value is the value of this Decimal divided by Decimal(y, b),
1536- * rounded to precision significant digits using rounding mode rounding.
1537- *
1538- */
1539- P['dividedBy'] = P['div'] = function ( y, b ) {
1540- id = 2;
1541-
1542- return div( this, new this['constructor']( y, b ) );
1543- };
1544-
1545-
1546- /*
1547- * Return a new Decimal whose value is the integer part of dividing the value of this Decimal by
1548- * the value of Decimal(y, b), rounded to precision significant digits using rounding mode
1549- * rounding.
1550- *
1551- */
1552- P['dividedToIntegerBy'] = P['divToInt'] = function ( y, b ) {
1553- var x = this,
1554- Decimal = x['constructor'];
1555- id = 18;
1556-
1557- return rnd(
1558- div( x, new Decimal( y, b ), 0, 1, 1 ), Decimal['precision'], Decimal['rounding']
1559- );
1560- };
1561-
1562-
1563- /*
1564- * Return true if the value of this Decimal is equal to the value of Decimal(n, b), otherwise
1565- * return false.
1566- *
1567- */
1568- P['equals'] = P['eq'] = function ( n, b ) {
1569- id = 3;
1570-
1571- return this['cmp']( n, b ) === 0;
1572- };
1573-
1574-
1575- /*
1576- * Return a new Decimal whose value is the exponential of the value of this Decimal, i.e. the
1577- * base e raised to the power the value of this Decimal, rounded to precision significant digits
1578- * using rounding mode rounding.
1579- *
1580- */
1581- P['exponential'] = P['exp'] = function () {
1582-
1583- return exp(this);
1584- };
1585-
1586-
1587- /*
1588- * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in
1589- * the direction of negative Infinity.
1590- *
1591- */
1592- P['floor'] = function () {
1593-
1594- return rnd( new this['constructor'](this), this['e'] + 1, 3 );
1595- };
1596-
1597-
1598- /*
1599- * Return true if the value of this Decimal is greater than the value of Decimal(n, b), otherwise
1600- * return false.
1601- *
1602- */
1603- P['greaterThan'] = P['gt'] = function ( n, b ) {
1604- id = 4;
1605-
1606- return this['cmp']( n, b ) > 0;
1607- };
1608-
1609-
1610- /*
1611- * Return true if the value of this Decimal is greater than or equal to the value of
1612- * Decimal(n, b), otherwise return false.
1613- *
1614- */
1615- P['greaterThanOrEqualTo'] = P['gte'] = function ( n, b ) {
1616- id = 5;
1617- b = this['cmp']( n, b );
1618-
1619- return b == 1 || b === 0;
1620- };
1621-
1622-
1623- /*
1624- * Return true if the value of this Decimal is a finite number, otherwise return false.
1625- *
1626- */
1627- P['isFinite'] = function () {
1628-
1629- return !!this['c'];
1630- };
1631-
1632-
1633- /*
1634- * Return true if the value of this Decimal is an integer, otherwise return false.
1635- *
1636- */
1637- P['isInteger'] = P['isInt'] = function () {
1638-
1639- return !!this['c'] && mathfloor( this['e'] / LOGBASE ) > this['c'].length - 2;
1640- };
1641-
1642-
1643- /*
1644- * Return true if the value of this Decimal is NaN, otherwise return false.
1645- *
1646- */
1647- P['isNaN'] = function () {
1648-
1649- return !this['s'];
1650- };
1651-
1652-
1653- /*
1654- * Return true if the value of this Decimal is negative, otherwise return false.
1655- *
1656- */
1657- P['isNegative'] = P['isNeg'] = function () {
1658-
1659- return this['s'] < 0;
1660- };
1661-
1662-
1663- /*
1664- * Return true if the value of this Decimal is 0 or -0, otherwise return false.
1665- *
1666- */
1667- P['isZero'] = function () {
1668-
1669- return !!this['c'] && this['c'][0] == 0;
1670- };
1671-
1672-
1673- /*
1674- * Return true if the value of this Decimal is less than Decimal(n, b), otherwise return false.
1675- *
1676- */
1677- P['lessThan'] = P['lt'] = function ( n, b ) {
1678- id = 6;
1679-
1680- return this['cmp']( n, b ) < 0;
1681- };
1682-
1683-
1684- /*
1685- * Return true if the value of this Decimal is less than or equal to Decimal(n, b), otherwise
1686- * return false.
1687- *
1688- */
1689- P['lessThanOrEqualTo'] = P['lte'] = function ( n, b ) {
1690- id = 7;
1691- b = this['cmp']( n, b );
1692-
1693- return b == -1 || b === 0;
1694- };
1695-
1696-
1697- /*
1698- * Return the logarithm of the value of this Decimal to the specified base, rounded
1699- * to precision significant digits using rounding mode rounding.
1700- *
1701- * If no base is specified, return log[10](arg).
1702- *
1703- * log[base](arg) = ln(arg) / ln(base)
1704- *
1705- * The result will always be correctly rounded if the base of the log is 2 or 10, and
1706- * 'almost always' if not:
1707- *
1708- * Depending on the rounding mode, the result may be incorrectly rounded if the first fifteen
1709- * rounding digits are [49]99999999999999 or [50]00000000000000. In that case, the maximum error
1710- * between the result and the correctly rounded result will be one ulp (unit in the last place).
1711- *
1712- * log[-b](a) = NaN
1713- * log[0](a) = NaN
1714- * log[1](a) = NaN
1715- * log[NaN](a) = NaN
1716- * log[Infinity](a) = NaN
1717- * log[b](0) = -Infinity
1718- * log[b](-0) = -Infinity
1719- * log[b](-a) = NaN
1720- * log[b](1) = 0
1721- * log[b](Infinity) = Infinity
1722- * log[b](NaN) = NaN
1723- *
1724- * [base] {number|string|Decimal} The base of the logarithm.
1725- * [b] {number} The base of base.
1726- *
1727- */
1728- P['logarithm'] = P['log'] = function ( base, b ) {
1729- var base10, c, denom, i, inf, num, sd, sd10, r,
1730- arg = this,
1731- Decimal = arg['constructor'],
1732- pr = Decimal['precision'],
1733- rm = Decimal['rounding'],
1734- guard = 5;
1735-
1736- // Default base is 10.
1737- if ( base == null ) {
1738- base = new Decimal(10);
1739- base10 = true;
1740- } else {
1741- id = 15;
1742- base = new Decimal( base, b );
1743- c = base['c'];
1744-
1745- // If base < 0 or +-Infinity/NaN or 0 or 1.
1746- if ( base['s'] < 0 || !c || !c[0] || !base['e'] && c[0] == 1 && c.length == 1 ) {
1747-
1748- return new Decimal(NaN);
1749- }
1750- base10 = base['eq'](10);
1751- }
1752- c = arg['c'];
1753-
1754- // If arg < 0 or +-Infinity/NaN or 0 or 1.
1755- if ( arg['s'] < 0 || !c || !c[0] || !arg['e'] && c[0] == 1 && c.length == 1 ) {
1756-
1757- return new Decimal( c && !c[0] ? -1 / 0 : arg['s'] != 1 ? NaN : c ? 0 : 1 / 0 );
1758- }
1759-
1760- /*
1761- The result will have an infinite decimal expansion if base is 10 and arg is not an
1762- integer power of 10...
1763- */
1764- inf = base10 && ( i = c[0], c.length > 1 || i != 1 && i != 10 &&
1765- i != 1e2 && i != 1e3 && i != 1e4 && i != 1e5 && i != 1e6 );
1766- /*
1767- // or if base last digit's evenness is not the same as arg last digit's evenness...
1768- // (FAILS when e.g. base.c[0] = 10 and c[0] = 1)
1769- || ( base['c'][ base['c'].length - 1 ] & 1 ) != ( c[ c.length - 1 ] & 1 )
1770- // or if base is 2 and there is more than one 1 in arg in base 2.
1771- // (SLOWS the method down significantly)
1772- || base['eq'](2) && arg.toString(2).replace( /[^1]+/g, '' ) != '1';
1773- */
1774-
1775- external = false;
1776- sd = pr + guard;
1777- sd10 = sd + 10;
1778-
1779- num = ln( arg, sd );
1780-
1781- if (base10) {
1782-
1783- if ( sd10 > LN10.length ) {
1784- ifExceptionsThrow( Decimal, 1, sd10, 'log' );
1785- }
1786- denom = new Decimal( LN10.slice( 0, sd10 ) );
1787- } else {
1788- denom = ln( base, sd );
1789- }
1790-
1791- // The result will have 5 rounding digits.
1792- r = div( num, denom, sd, 1 );
1793-
1794- /*
1795- If at a rounding boundary, i.e. the result's rounding digits are [49]9999 or [50]0000,
1796- calculate 10 further digits.
1797-
1798- If the result is known to have an infinite decimal expansion, repeat this until it is
1799- clear that the result is above or below the boundary. Otherwise, if after calculating
1800- the 10 further digits, the last 14 are nines, round up and assume the result is exact.
1801- Also assume the result is exact if the last 14 are zero.
1802-
1803- Example of a result that will be incorrectly rounded:
1804- log[1048576](4503599627370502) = 2.60000000000000009610279511444746...
1805- The above result correctly rounded using ROUND_CEIL to 1 decimal place should be 2.7,
1806- but it will be given as 2.6 as there are 15 zeros immediately after the requested
1807- decimal place, so the exact result would be assumed to be 2.6, which rounded using
1808- ROUND_CEIL to 1 decimal place is still 2.6.
1809- */
1810- if ( checkRoundingDigits( r['c'], i = pr, rm ) ) {
1811-
1812- do {
1813- sd += 10;
1814- num = ln( arg, sd );
1815-
1816- if (base10) {
1817- sd10 = sd + 10;
1818-
1819- if ( sd10 > LN10.length ) {
1820- ifExceptionsThrow( Decimal, 1, sd10, 'log' );
1821- }
1822- denom = new Decimal( LN10.slice( 0, sd10 ) );
1823- } else {
1824- denom = ln( base, sd );
1825- }
1826-
1827- r = div( num, denom, sd, 1 );
1828-
1829- if ( !inf ) {
1830-
1831- // Check for 14 nines from the 2nd rounding digit, as the first may be 4.
1832- if ( +coefficientToString( r['c'] ).slice( i + 1, i + 15 ) + 1 == 1e14 ) {
1833- r = rnd( r, pr + 1, 0 );
1834- }
1835-
1836- break;
1837- }
1838- } while ( checkRoundingDigits( r['c'], i += 10, rm ) );
1839- }
1840- external = true;
1841-
1842- return rnd( r, pr, rm );
1843- };
1844-
1845-
1846- /*
1847- * n - 0 = n
1848- * n - N = N
1849- * n - I = -I
1850- * 0 - n = -n
1851- * 0 - 0 = 0
1852- * 0 - N = N
1853- * 0 - I = -I
1854- * N - n = N
1855- * N - 0 = N
1856- * N - N = N
1857- * N - I = N
1858- * I - n = I
1859- * I - 0 = I
1860- * I - N = N
1861- * I - I = N
1862- *
1863- * Return a new Decimal whose value is the value of this Decimal minus Decimal(y, b), rounded
1864- * to precision significant digits using rounding mode rounding.
1865- *
1866- */
1867- P['minus'] = function ( y, b ) {
1868- var t, i, j, xLTy,
1869- x = this,
1870- Decimal = x['constructor'],
1871- a = x['s'];
1872-
1873- id = 8;
1874- y = new Decimal( y, b );
1875- b = y['s'];
1876-
1877- // Either NaN?
1878- if ( !a || !b ) {
1879-
1880- return new Decimal(NaN);
1881- }
1882-
1883- // Signs differ?
1884- if ( a != b ) {
1885- y['s'] = -b;
1886-
1887- return x['plus'](y);
1888- }
1889-
1890- var xc = x['c'],
1891- yc = y['c'],
1892- e = mathfloor( y['e'] / LOGBASE ),
1893- k = mathfloor( x['e'] / LOGBASE ),
1894- pr = Decimal['precision'],
1895- rm = Decimal['rounding'];
1896-
1897- if ( !k || !e ) {
1898-
1899- // Either Infinity?
1900- if ( !xc || !yc ) {
1901-
1902- return xc ? ( y['s'] = -b, y ) : new Decimal( yc ? x : NaN );
1903- }
1904-
1905- // Either zero?
1906- if ( !xc[0] || !yc[0] ) {
1907-
1908- // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
1909- x = yc[0] ? ( y['s'] = -b, y ) : new Decimal( xc[0] ? x :
1910-
1911- // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity
1912- rm == 3 ? -0 : 0 );
1913-
1914- return external ? rnd( x, pr, rm ) : x;
1915- }
1916- }
1917-
1918- xc = xc.slice();
1919- i = xc.length;
1920-
1921- // Determine which is the bigger number. Prepend zeros to equalise exponents.
1922- if ( a = k - e ) {
1923-
1924- if ( xLTy = a < 0 ) {
1925- a = -a;
1926- t = xc;
1927- i = yc.length;
1928- } else {
1929- e = k;
1930- t = yc;
1931- }
1932-
1933- if ( ( k = Math.ceil( pr / LOGBASE ) ) > i ) {
1934- i = k;
1935- }
1936-
1937- /*
1938- Numbers with massively different exponents would result in a massive number of
1939- zeros needing to be prepended, but this can be avoided while still ensuring correct
1940- rounding by limiting the number of zeros to max( precision, i ) + 2, where pr is
1941- precision and i is the length of the coefficient of whichever is greater x or y.
1942- */
1943- if ( a > ( i += 2 ) ) {
1944- a = i;
1945- t.length = 1;
1946- }
1947-
1948- for ( t.reverse(), b = a; b--; t.push(0) );
1949- t.reverse();
1950- } else {
1951- // Exponents equal. Check digits.
1952-
1953- if ( xLTy = i < ( j = yc.length ) ) {
1954- j = i;
1955- }
1956-
1957- for ( a = b = 0; b < j; b++ ) {
1958-
1959- if ( xc[b] != yc[b] ) {
1960- xLTy = xc[b] < yc[b];
1961-
1962- break;
1963- }
1964- }
1965- }
1966-
1967- // x < y? Point xc to the array of the bigger number.
1968- if ( xLTy ) {
1969- t = xc, xc = yc, yc = t;
1970- y['s'] = -y['s'];
1971- }
1972-
1973- /*
1974- Append zeros to xc if shorter. No need to add zeros to yc if shorter as subtraction only
1975- needs to start at yc length.
1976- */
1977- if ( ( b = -( ( j = xc.length ) - yc.length ) ) > 0 ) {
1978-
1979- for ( ; b--; xc[j++] = 0 );
1980- }
1981-
1982- // Subtract yc from xc.
1983- for ( k = BASE - 1, b = yc.length; b > a; ) {
1984-
1985- if ( xc[--b] < yc[b] ) {
1986-
1987- for ( i = b; i && !xc[--i]; xc[i] = k );
1988- --xc[i];
1989- xc[b] += BASE;
1990- }
1991- xc[b] -= yc[b];
1992- }
1993-
1994- // Remove trailing zeros.
1995- for ( ; xc[--j] == 0; xc.pop() );
1996-
1997- // Remove leading zeros and adjust exponent accordingly.
1998- for ( ; xc[0] == 0; xc.shift(), --e );
1999-
2000- if ( !xc[0] ) {
2001-
2002- // Zero.
2003- xc = [ e = 0 ];
2004-
2005- // Following IEEE 754 (2008) 6.3, n - n = -0 when rounding towards -Infinity.
2006- y['s'] = rm == 3 ? -1 : 1;
2007- }
2008-
2009- y['c'] = xc;
2010-
2011- // Get the number of digits of xc[0].
2012- for ( a = 1, b = xc[0]; b >= 10; b /= 10, a++ );
2013- y['e'] = a + e * LOGBASE - 1;
2014-
2015- return external ? rnd( y, pr, rm ) : y;
2016- };
2017-
2018-
2019- /*
2020- * n % 0 = N
2021- * n % N = N
2022- * n % I = n
2023- * 0 % n = 0
2024- * -0 % n = -0
2025- * 0 % 0 = N
2026- * 0 % N = N
2027- * 0 % I = 0
2028- * N % n = N
2029- * N % 0 = N
2030- * N % N = N
2031- * N % I = N
2032- * I % n = N
2033- * I % 0 = N
2034- * I % N = N
2035- * I % I = N
2036- *
2037- * Return a new Decimal whose value is the value of this Decimal modulo Decimal(y, b), rounded
2038- * to precision significant digits using rounding mode rounding.
2039- *
2040- * The result depends on the modulo mode.
2041- *
2042- */
2043- P['modulo'] = P['mod'] = function ( y, b ) {
2044- var n, q,
2045- x = this,
2046- Decimal = x['constructor'],
2047- m = Decimal['modulo'];
2048-
2049- id = 9;
2050- y = new Decimal( y, b );
2051- b = y['s'];
2052- n = !x['c'] || !b || y['c'] && !y['c'][0];
2053-
2054- /*
2055- Return NaN if x is Infinity or NaN, or y is NaN or zero, else return x if y is Infinity
2056- or x is zero.
2057- */
2058- if ( n || !y['c'] || x['c'] && !x['c'][0] ) {
2059-
2060- return n
2061- ? new Decimal(NaN)
2062- : rnd( new Decimal(x), Decimal['precision'], Decimal['rounding'] );
2063- }
2064-
2065- external = false;
2066-
2067- if ( m == 9 ) {
2068-
2069- // Euclidian division: q = sign(y) * floor(x / abs(y))
2070- // r = x - qy where 0 <= r < abs(y)
2071- y['s'] = 1;
2072- q = div( x, y, 0, 3, 1 );
2073- y['s'] = b;
2074- q['s'] *= b;
2075- } else {
2076- q = div( x, y, 0, m, 1 );
2077- }
2078-
2079- q = q['times'](y);
2080- external = true;
2081-
2082- return x['minus'](q);
2083- };
2084-
2085-
2086- /*
2087- * Return a new Decimal whose value is the natural logarithm of the value of this Decimal,
2088- * rounded to precision significant digits using rounding mode rounding.
2089- *
2090- */
2091- P['naturalLogarithm'] = P['ln'] = function () {
2092-
2093- return ln(this);
2094- };
2095-
2096-
2097- /*
2098- * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if
2099- * multiplied by -1.
2100- *
2101- */
2102- P['negated'] = P['neg'] = function () {
2103- var x = new this['constructor'](this);
2104- x['s'] = -x['s'] || null;
2105-
2106- return rnd(x);
2107- };
2108-
2109-
2110- /*
2111- * n + 0 = n
2112- * n + N = N
2113- * n + I = I
2114- * 0 + n = n
2115- * 0 + 0 = 0
2116- * 0 + N = N
2117- * 0 + I = I
2118- * N + n = N
2119- * N + 0 = N
2120- * N + N = N
2121- * N + I = N
2122- * I + n = I
2123- * I + 0 = I
2124- * I + N = N
2125- * I + I = I
2126- *
2127- * Return a new Decimal whose value is the value of this Decimal plus Decimal(y, b), rounded
2128- * to precision significant digits using rounding mode rounding.
2129- *
2130- */
2131- P['plus'] = function ( y, b ) {
2132- var t,
2133- x = this,
2134- Decimal = x['constructor'],
2135- a = x['s'];
2136-
2137- id = 10;
2138- y = new Decimal( y, b );
2139- b = y['s'];
2140-
2141- // Either NaN?
2142- if ( !a || !b ) {
2143-
2144- return new Decimal(NaN);
2145- }
2146-
2147- // Signs differ?
2148- if ( a != b ) {
2149- y['s'] = -b;
2150-
2151- return x['minus'](y);
2152- }
2153-
2154- var xc = x['c'],
2155- yc = y['c'],
2156- e = mathfloor( y['e'] / LOGBASE ),
2157- k = mathfloor( x['e'] / LOGBASE ),
2158- pr = Decimal['precision'],
2159- rm = Decimal['rounding'];
2160-
2161- if ( !k || !e ) {
2162-
2163- // Either Infinity?
2164- if ( !xc || !yc ) {
2165-
2166- // Return +-Infinity.
2167- return new Decimal( a / 0 );
2168- }
2169-
2170- // Either zero?
2171- if ( !xc[0] || !yc[0] ) {
2172-
2173- // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
2174- x = yc[0] ? y: new Decimal( xc[0] ? x : a * 0 );
2175-
2176- return external ? rnd( x, pr, rm ) : x;
2177- }
2178- }
2179-
2180- xc = xc.slice();
2181-
2182- // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts.
2183- if ( a = k - e ) {
2184-
2185- if ( a < 0 ) {
2186- a = -a;
2187- t = xc;
2188- b = yc.length;
2189- } else {
2190- e = k;
2191- t = yc;
2192- b = xc.length;
2193- }
2194-
2195- if ( ( k = Math.ceil( pr / LOGBASE ) ) > b ) {
2196- b = k;
2197- }
2198-
2199- // Limit number of zeros prepended to max( pr, b ) + 1.
2200- if ( a > ++b ) {
2201- a = b;
2202- t.length = 1;
2203- }
2204-
2205- for ( t.reverse(); a--; t.push(0) );
2206- t.reverse();
2207- }
2208-
2209- // Point xc to the longer array.
2210- if ( xc.length - yc.length < 0 ) {
2211- t = yc, yc = xc, xc = t;
2212- }
2213-
2214- // Only start adding at yc.length - 1 as the further digits of xc can be left as they are.
2215- for ( a = yc.length, b = 0, k = BASE; a; xc[a] %= k ) {
2216- b = ( xc[--a] = xc[a] + yc[a] + b ) / k | 0;
2217- }
2218-
2219- if (b) {
2220- xc.unshift(b);
2221- ++e;
2222- }
2223-
2224- // Remove trailing zeros.
2225- for ( a = xc.length; xc[--a] == 0; xc.pop() );
2226-
2227- // No need to check for zero, as +x + +y != 0 && -x + -y != 0
2228-
2229- y['c'] = xc;
2230-
2231- // Get the number of digits of xc[0].
2232- for ( a = 1, b = xc[0]; b >= 10; b /= 10, a++ );
2233- y['e'] = a + e * LOGBASE - 1;
2234-
2235- return external ? rnd( y, pr, rm ) : y;
2236- };
2237-
2238-
2239- /*
2240- * Return the number of significant digits of this Decimal.
2241- *
2242- * z {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
2243- *
2244- */
2245- P['precision'] = P['sd'] = function (z) {
2246- var n = null,
2247- x = this;
2248-
2249- if ( z != n ) {
2250-
2251- if ( z !== !!z && z !== 1 && z !== 0 ) {
2252-
2253- // 'precision() argument not a boolean or binary digit: {z}'
2254- ifExceptionsThrow( x['constructor'], 'argument', z, 'precision', 1 );
2255- }
2256- }
2257-
2258- if ( x['c'] ) {
2259- n = getCoeffLength( x['c'] );
2260-
2261- if ( z && x['e'] + 1 > n ) {
2262- n = x['e'] + 1;
2263- }
2264- }
2265-
2266- return n;
2267- };
2268-
2269-
2270- /*
2271- * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using
2272- * rounding mode rounding.
2273- *
2274- */
2275- P['round'] = function () {
2276- var x = this,
2277- Decimal = x['constructor'];
2278-
2279- return rnd( new Decimal(x), x['e'] + 1, Decimal['rounding'] );
2280- };
2281-
2282-
2283- /*
2284- * sqrt(-n) = N
2285- * sqrt( N) = N
2286- * sqrt(-I) = N
2287- * sqrt( I) = I
2288- * sqrt( 0) = 0
2289- * sqrt(-0) = -0
2290- *
2291- * Return a new Decimal whose value is the square root of this Decimal, rounded to precision
2292- * significant digits using rounding mode rounding.
2293- *
2294- */
2295- P['squareRoot'] = P['sqrt'] = function () {
2296- var m, n, sd, r, rep, t,
2297- x = this,
2298- c = x['c'],
2299- s = x['s'],
2300- e = x['e'],
2301- Decimal = x['constructor'],
2302- half = new Decimal(0.5);
2303-
2304- // Negative/NaN/Infinity/zero?
2305- if ( s !== 1 || !c || !c[0] ) {
2306-
2307- return new Decimal( !s || s < 0 && ( !c || c[0] ) ? NaN : c ? x : 1 / 0 );
2308- }
2309-
2310- external = false;
2311-
2312- // Initial estimate.
2313- s = Math.sqrt( +x );
2314-
2315- /*
2316- Math.sqrt underflow/overflow?
2317- Pass x to Math.sqrt as integer, then adjust the exponent of the result.
2318- */
2319- if ( s == 0 || s == 1 / 0 ) {
2320- n = coefficientToString(c);
2321-
2322- if ( ( n.length + e ) % 2 == 0 ) {
2323- n += '0';
2324- }
2325-
2326- s = Math.sqrt(n);
2327- e = mathfloor( ( e + 1 ) / 2 ) - ( e < 0 || e % 2 );
2328-
2329- if ( s == 1 / 0 ) {
2330- n = '1e' + e;
2331- } else {
2332- n = s.toExponential();
2333- n = n.slice( 0, n.indexOf('e') + 1 ) + e;
2334- }
2335-
2336- r = new Decimal(n);
2337- } else {
2338- r = new Decimal( s.toString() );
2339- }
2340-
2341- sd = ( e = Decimal['precision'] ) + 3;
2342-
2343- // Newton-Raphson iteration.
2344- for ( ; ; ) {
2345- t = r;
2346- r = half['times']( t['plus']( div( x, t, sd + 2, 1 ) ) );
2347-
2348- if ( coefficientToString( t['c'] ).slice( 0, sd ) ===
2349- ( n = coefficientToString( r['c'] ) ).slice( 0, sd ) ) {
2350- n = n.slice( sd - 3, sd + 1 );
2351-
2352- /*
2353- The 4th rounding digit may be in error by -1 so if the 4 rounding digits are
2354- 9999 or 4999 (i.e. approaching a rounding boundary) continue the iteration.
2355- */
2356- if ( n == '9999' || !rep && n == '4999' ) {
2357-
2358- /*
2359- On the first iteration only, check to see if rounding up gives the exact result
2360- as the nines may infinitely repeat.
2361- */
2362- if ( !rep ) {
2363- rnd( t, e + 1, 0 );
2364-
2365- if ( t['times'](t)['eq'](x) ) {
2366- r = t;
2367-
2368- break;
2369- }
2370- }
2371- sd += 4;
2372- rep = 1;
2373- } else {
2374-
2375- /*
2376- If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.
2377- If not, then there are further digits and m will be truthy.
2378- */
2379- if ( !+n || !+n.slice(1) && n.charAt(0) == '5' ) {
2380-
2381- // Truncate to the first rounding digit.
2382- rnd( r, e + 1, 1 );
2383- m = !r['times'](r)['eq'](x);
2384- }
2385-
2386- break;
2387- }
2388- }
2389- }
2390- external = true;
2391-
2392- return rnd( r, e, Decimal['rounding'], m );
2393- };
2394-
2395-
2396- /*
2397- * n * 0 = 0
2398- * n * N = N
2399- * n * I = I
2400- * 0 * n = 0
2401- * 0 * 0 = 0
2402- * 0 * N = N
2403- * 0 * I = N
2404- * N * n = N
2405- * N * 0 = N
2406- * N * N = N
2407- * N * I = N
2408- * I * n = I
2409- * I * 0 = N
2410- * I * N = N
2411- * I * I = I
2412- *
2413- * Return a new Decimal whose value is this Decimal times Decimal(y), rounded to precision
2414- * significant digits using rounding mode rounding.
2415- *
2416- */
2417- P['times'] = function ( y, b ) {
2418- var c, e,
2419- x = this,
2420- Decimal = x['constructor'],
2421- xc = x['c'],
2422- yc = ( id = 11, y = new Decimal( y, b ), y['c'] ),
2423- i = mathfloor( x['e'] / LOGBASE ),
2424- j = mathfloor( y['e'] / LOGBASE ),
2425- a = x['s'];
2426-
2427- b = y['s'];
2428-
2429- y['s'] = a == b ? 1 : -1;
2430-
2431- // Either NaN/Infinity/0?
2432- if ( !i && ( !xc || !xc[0] ) || !j && ( !yc || !yc[0] ) ) {
2433-
2434- // Either NaN?
2435- return new Decimal( !a || !b ||
2436-
2437- // x is 0 and y is Infinity or y is 0 and x is Infinity?
2438- xc && !xc[0] && !yc || yc && !yc[0] && !xc
2439-
2440- // Return NaN.
2441- ? NaN
2442-
2443- // Either Infinity?
2444- : !xc || !yc
2445-
2446- // Return +-Infinity.
2447- ? y['s'] / 0
2448-
2449- // x or y is 0. Return +-0.
2450- : y['s'] * 0 );
2451- }
2452-
2453- e = i + j;
2454- a = xc.length;
2455- b = yc.length;
2456-
2457- if ( a < b ) {
2458-
2459- // Swap.
2460- c = xc, xc = yc, yc = c;
2461- j = a, a = b, b = j;
2462- }
2463-
2464- for ( j = a + b, c = []; j--; c.push(0) );
2465-
2466- // Multiply!
2467- for ( i = b - 1; i > -1; i-- ) {
2468-
2469- for ( b = 0, j = a + i; j > i; b = b / BASE | 0 ) {
2470- b = c[j] + yc[i] * xc[j - i - 1] + b;
2471- c[j--] = b % BASE | 0;
2472- }
2473-
2474- if (b) {
2475- c[j] = ( c[j] + b ) % BASE;
2476- }
2477- }
2478-
2479- if (b) {
2480- ++e;
2481- }
2482-
2483- // Remove any leading zero.
2484- if ( !c[0] ) {
2485- c.shift();
2486- }
2487-
2488- // Remove trailing zeros.
2489- for ( j = c.length; !c[--j]; c.pop() );
2490-
2491- y['c'] = c;
2492-
2493- // Get the number of digits of c[0].
2494- for ( a = 1, b = c[0]; b >= 10; b /= 10, a++ );
2495- y['e'] = a + e * LOGBASE - 1;
2496-
2497- return external ? rnd( y, Decimal['precision'], Decimal['rounding'] ) : y;
2498- };
2499-
2500-
2501- /*
2502- * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of dp
2503- * decimal places using rounding mode rm or rounding if rm is omitted.
2504- *
2505- * If dp is omitted, return a new Decimal whose value is the value of this Decimal.
2506- *
2507- * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
2508- * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
2509- *
2510- * 'toDP() dp out of range: {dp}'
2511- * 'toDP() dp not an integer: {dp}'
2512- * 'toDP() rounding mode not an integer: {rm}'
2513- * 'toDP() rounding mode out of range: {rm}'
2514- *
2515- */
2516- P['toDecimalPlaces'] = P['toDP'] = function ( dp, rm ) {
2517- var x = this;
2518- x = new x['constructor'](x);
2519-
2520- return dp == null || !checkArg( x, dp, 'toDP' )
2521- ? x
2522- : rnd( x, ( dp | 0 ) + x['e'] + 1, checkRM( x, rm, 'toDP' ) );
2523- };
2524-
2525-
2526- /*
2527- * Return a string representing the value of this Decimal in exponential notation rounded to dp
2528- * fixed decimal places using rounding mode rounding.
2529- *
2530- * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
2531- * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
2532- *
2533- * errors true: Throw if dp and rm are not undefined, null or integers in range.
2534- * errors false: Ignore dp and rm if not numbers or not in range, and truncate non-integers.
2535- *
2536- * 'toExponential() dp not an integer: {dp}'
2537- * 'toExponential() dp out of range: {dp}'
2538- * 'toExponential() rounding mode not an integer: {rm}'
2539- * 'toExponential() rounding mode out of range: {rm}'
2540- *
2541- */
2542- P['toExponential'] = function ( dp, rm ) {
2543- var x = this;
2544-
2545- return x['c']
2546- ? format( x, dp != null && checkArg( x, dp, 'toExponential' ) ? dp | 0 : null,
2547- dp != null && checkRM( x, rm, 'toExponential' ), 1 )
2548- : x.toString();
2549- };
2550-
2551-
2552- /*
2553- * Return a string representing the value of this Decimal in normal (fixed-point) notation to
2554- * dp fixed decimal places and rounded using rounding mode rm or rounding if rm is omitted.
2555- *
2556- * Note: as with JS numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'.
2557- *
2558- * [dp] {number} Decimal places. Integer, -MAX_DIGITS to MAX_DIGITS inclusive.
2559- * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
2560- *
2561- * errors true: Throw if dp and rm are not undefined, null or integers in range.
2562- * errors false: Ignore dp and rm if not numbers or not in range, and truncate non-integers.
2563- *
2564- * 'toFixed() dp not an integer: {dp}'
2565- * 'toFixed() dp out of range: {dp}'
2566- * 'toFixed() rounding mode not an integer: {rm}'
2567- * 'toFixed() rounding mode out of range: {rm}'
2568- *
2569- */
2570- P['toFixed'] = function ( dp, rm ) {
2571- var str,
2572- x = this,
2573- Decimal = x['constructor'],
2574- neg = Decimal['toExpNeg'],
2575- pos = Decimal['toExpPos'];
2576-
2577- if ( dp != null ) {
2578- dp = checkArg( x, dp, str = 'toFixed' ) ? x['e'] + ( dp | 0 ) : null;
2579- rm = checkRM( x, rm, str );
2580- }
2581-
2582- // Prevent toString returning exponential notation;
2583- Decimal['toExpNeg'] = -( Decimal['toExpPos'] = 1 / 0 );
2584-
2585- if ( dp == null || !x['c'] ) {
2586- str = x.toString();
2587- } else {
2588- str = format( x, dp, rm );
2589-
2590- // (-0).toFixed() is '0', but (-0.1).toFixed() is '-0'.
2591- // (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'.
2592- if ( x['s'] < 0 && x['c'] ) {
2593-
2594- // As e.g. (-0).toFixed(3), will wrongly be returned as -0.000 from toString.
2595- if ( !x['c'][0] ) {
2596- str = str.replace( '-', '' );
2597-
2598- // As e.g. -0.5 if rounded to -0 will cause toString to omit the minus sign.
2599- } else if ( str.indexOf('-') < 0 ) {
2600- str = '-' + str;
2601- }
2602- }
2603- }
2604- Decimal['toExpNeg'] = neg;
2605- Decimal['toExpPos'] = pos;
2606-
2607- return str;
2608- };
2609-
2610-
2611- /*
2612- * Return a string representing the value of this Decimal in normal notation rounded using
2613- * rounding mode rounding to dp fixed decimal places, with the integer part of the number
2614- * separated into thousands by string sep1 or ',' if sep1 is null or undefined, and the
2615- * fraction part separated into groups of five digits by string sep2.
2616- *
2617- * [sep1] {string} The grouping separator of the integer part of the number.
2618- * [sep2] {string} The grouping separator of the fraction part of the number.
2619- * [dp] {number} Decimal places. Integer, -MAX_DIGITS to MAX_DIGITS inclusive.
2620- *
2621- * Non-breaking thin-space: \u202f
2622- *
2623- * If dp is invalid the error message will incorrectly give the method as toFixed.
2624- *
2625- */
2626- P['toFormat'] = function ( sep1, dp, sep2 ) {
2627- var arr = this.toFixed(dp).split('.');
2628-
2629- return arr[0].replace( /\B(?=(\d{3})+$)/g, sep1 == null ? ',' : sep1 + '' ) +
2630- ( arr[1] ? '.' + ( sep2 ? arr[1].replace( /\d{5}\B/g, '$&' + sep2 ) : arr[1] ) : '' );
2631- };
2632-
2633-
2634- /*
2635- * Return a string array representing the value of this Decimal as a simple fraction with an
2636- * integer numerator and an integer denominator.
2637- *
2638- * The denominator will be a positive non-zero value less than or equal to the specified
2639- * maximum denominator. If a maximum denominator is not specified, the denominator will be
2640- * the lowest value necessary to represent the number exactly.
2641- *
2642- * [maxD] {number|string|Decimal} Maximum denominator. Integer >= 1 and < Infinity.
2643- *
2644- */
2645- P['toFraction'] = function (maxD) {
2646- var d0, d2, e, frac, n, n0, p, q,
2647- x = this,
2648- Decimal = x['constructor'],
2649- n1 = d0 = new Decimal( Decimal['ONE'] ),
2650- d1 = n0 = new Decimal(0),
2651- xc = x['c'],
2652- d = new Decimal(d1);
2653-
2654- // NaN, Infinity.
2655- if ( !xc ) {
2656-
2657- return x.toString();
2658- }
2659-
2660- e = d['e'] = getCoeffLength(xc) - x['e'] - 1;
2661- d['c'][0] = mathpow( 10, ( p = e % LOGBASE ) < 0 ? LOGBASE + p : p );
2662-
2663- // If maxD is undefined or null...
2664- if ( maxD == null ||
2665-
2666- // or NaN...
2667- ( !( id = 12, n = new Decimal(maxD) )['s'] ||
2668-
2669- // or less than 1, or Infinity...
2670- ( outOfRange = n['cmp'](n1) < 0 || !n['c'] ) ||
2671-
2672- // or not an integer...
2673- ( Decimal['errors'] && mathfloor( n['e'] / LOGBASE ) < n['c'].length - 1 ) ) &&
2674-
2675- // 'toFraction() max denominator not an integer: {maxD}'
2676- // 'toFraction() max denominator out of range: {maxD}'
2677- !ifExceptionsThrow( Decimal, 'max denominator', maxD, 'toFraction', 0 ) ||
2678-
2679- // or greater than the maximum denominator needed to specify the value exactly.
2680- ( maxD = n )['cmp'](d) > 0 ) {
2681-
2682- // d is 10**e, n1 is 1.
2683- maxD = e > 0 ? d : n1;
2684- }
2685-
2686- external = false;
2687- n = new Decimal( coefficientToString(xc) );
2688- p = Decimal['precision'];
2689- Decimal['precision'] = e = xc.length * LOGBASE * 2;
2690-
2691- for ( ; ; ) {
2692- q = div( n, d, 0, 1, 1 );
2693- d2 = d0['plus']( q['times'](d1) );
2694-
2695- if ( d2['cmp'](maxD) == 1 ) {
2696-
2697- break;
2698- }
2699- d0 = d1, d1 = d2;
2700-
2701- n1 = n0['plus']( q['times']( d2 = n1 ) );
2702- n0 = d2;
2703-
2704- d = n['minus']( q['times']( d2 = d ) );
2705- n = d2;
2706- }
2707-
2708- d2 = div( maxD['minus'](d0), d1, 0, 1, 1 );
2709- n0 = n0['plus']( d2['times'](n1) );
2710- d0 = d0['plus']( d2['times'](d1) );
2711- n0['s'] = n1['s'] = x['s'];
2712-
2713- // Determine which fraction is closer to x, n0/d0 or n1/d1?
2714- frac = div( n1, d1, e, 1 )['minus'](x)['abs']()['cmp'](
2715- div( n0, d0, e, 1 )['minus'](x)['abs']() ) < 1
2716- ? [ n1 + '', d1 + '' ]
2717- : [ n0 + '', d0 + '' ];
2718-
2719- external = true;
2720- Decimal['precision'] = p;
2721-
2722- return frac;
2723- };
2724-
2725-
2726- /*
2727- * Returns a new Decimal whose value is the nearest multiple of the magnitude of n to the value
2728- * of this Decimal.
2729- *
2730- * If the value of this Decimal is equidistant from two multiples of n, the rounding mode rm,
2731- * or rounding if rm is omitted or is null or undefined, determines the direction of the
2732- * nearest multiple.
2733- *
2734- * In the context of this method, rounding mode 4 (ROUND_HALF_UP) is the same as rounding mode 0
2735- * (ROUND_UP), and so on.
2736- *
2737- * The return value will always have the same sign as this Decimal, unless either this Decimal
2738- * or n is NaN, in which case the return value will be also be NaN.
2739- *
2740- * The return value is not rounded to precision significant digits.
2741- *
2742- * n {number|string|Decimal} The magnitude to round to a multiple of.
2743- * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
2744- *
2745- * 'toNearest() rounding mode not an integer: {rm}'
2746- * 'toNearest() rounding mode out of range: {rm}'
2747- *
2748- */
2749- P['toNearest'] = function ( n, rm ) {
2750- var x = this,
2751- Decimal = x['constructor'];
2752-
2753- x = new Decimal(x);
2754-
2755- if ( n == null ) {
2756- n = new Decimal( Decimal['ONE'] );
2757- rm = Decimal['rounding'];
2758- } else {
2759- id = 17;
2760- n = new Decimal(n);
2761- rm = checkRM( x, rm, 'toNearest' );
2762- }
2763-
2764- // If n is finite...
2765- if ( n['c'] ) {
2766-
2767- // If x is finite...
2768- if ( x['c'] ) {
2769-
2770- if ( n['c'][0] ) {
2771- external = false;
2772- x = div( x, n, 0, rm < 4 ? [4, 5, 7, 8][rm] : rm, 1 )['times'](n);
2773- external = true;
2774- rnd(x);
2775- } else {
2776- x['c'] = [ x['e'] = 0 ];
2777- }
2778- }
2779-
2780- // n is NaN or +-Infinity. If x is not NaN...
2781- } else if ( x['s'] ) {
2782-
2783- // If n is +-Infinity...
2784- if ( n['s'] ) {
2785- n['s'] = x['s'];
2786- }
2787- x = n;
2788- }
2789-
2790- return x;
2791- };
2792-
2793-
2794- /*
2795- * Return the value of this Decimal converted to a number primitive.
2796- *
2797- */
2798- P['toNumber'] = function () {
2799- var x = this;
2800-
2801- // Ensure zero has correct sign.
2802- return +x || ( x['s'] ? 0 * x['s'] : NaN );
2803- };
2804-
2805-
2806- /*
2807- * Return a new Decimal whose value is the value of this Decimal raised to the power
2808- * Decimal(y, b), rounded to precision significant digits using rounding mode rounding.
2809- *
2810- * ECMAScript compliant.
2811- *
2812- * x is any value, including NaN.
2813- * n is any number, including �Infinity unless stated.
2814- *
2815- * pow( x, NaN ) = NaN
2816- * pow( x, �0 ) = 1
2817-
2818- * pow( NaN, nonzero ) = NaN
2819- * pow( abs(n) > 1, +Infinity ) = +Infinity
2820- * pow( abs(n) > 1, -Infinity ) = +0
2821- * pow( abs(n) == 1, �Infinity ) = NaN
2822- * pow( abs(n) < 1, +Infinity ) = +0
2823- * pow( abs(n) < 1, -Infinity ) = +Infinity
2824- * pow( +Infinity, n > 0 ) = +Infinity
2825- * pow( +Infinity, n < 0 ) = +0
2826- * pow( -Infinity, odd integer > 0 ) = -Infinity
2827- * pow( -Infinity, even integer > 0 ) = +Infinity
2828- * pow( -Infinity, odd integer < 0 ) = -0
2829- * pow( -Infinity, even integer < 0 ) = +0
2830- * pow( +0, n > 0 ) = +0
2831- * pow( +0, n < 0 ) = +Infinity
2832- * pow( -0, odd integer > 0 ) = -0
2833- * pow( -0, even integer > 0 ) = +0
2834- * pow( -0, odd integer < 0 ) = -Infinity
2835- * pow( -0, even integer < 0 ) = +Infinity
2836- * pow( finite n < 0, finite non-integer ) = NaN
2837- *
2838- * For non-integer and larger exponents pow(x, y) is calculated using
2839- *
2840- * x^y = exp(y*ln(x))
2841- *
2842- * Assuming the first 15 rounding digits are each equally likely to be any digit 0-9, the
2843- * probability of an incorrectly rounded result
2844- * P( [49]9{14} | [50]0{14} ) = 2 * 0.2 * 10^-14 = 4e-15 = 1/2.5e+14
2845- * i.e. 1 in 250,000,000,000,000
2846- *
2847- * If a result is incorrectly rounded the maximum error will be 1 ulp (unit in last place).
2848- *
2849- * y {number|string|Decimal} The power to which to raise this Decimal.
2850- * [b] {number} The base of y.
2851- *
2852- */
2853- P['toPower'] = P['pow'] = function ( y, b ) {
2854- var a, e, n, r,
2855- x = this,
2856- Decimal = x['constructor'],
2857- s = x['s'],
2858- yN = +( id = 13, y = new Decimal( y, b ) ),
2859- i = yN < 0 ? -yN : yN,
2860- pr = Decimal['precision'],
2861- rm = Decimal['rounding'];
2862-
2863- // Handle +-Infinity, NaN and +-0.
2864- if ( !x['c'] || !y['c'] || ( n = !x['c'][0] ) || !y['c'][0] ) {
2865-
2866- // valueOf -0 is 0, so check for 0 then multiply it by the sign.
2867- return new Decimal( mathpow( n ? s * 0 : +x, yN ) );
2868- }
2869-
2870- x = new Decimal(x);
2871- a = x['c'].length;
2872-
2873- // if x == 1
2874- if ( !x['e'] && x['c'][0] == x['s'] && a == 1 ) {
2875-
2876- return x;
2877- }
2878-
2879- b = y['c'].length - 1;
2880-
2881- // if y == 1
2882- if ( !y['e'] && y['c'][0] == y['s'] && !b ) {
2883- r = rnd( x, pr, rm );
2884- } else {
2885- e = mathfloor( y['e'] / LOGBASE );
2886- n = e >= b;
2887-
2888- // If y is not an integer and x is negative, return NaN.
2889- if ( !n && s < 0 ) {
2890- r = new Decimal(NaN);
2891- } else {
2892-
2893- /*
2894- If the approximate number of significant digits of x multiplied by abs(y) is less
2895- than INT_POW_LIMIT use the 'exponentiation by squaring' algorithm.
2896- */
2897- if ( n && a * LOGBASE * i < INT_POW_LIMIT ) {
2898- r = intPow( Decimal, x, i );
2899-
2900- if ( y['s'] < 0 ) {
2901-
2902- return Decimal['ONE']['div'](r);
2903- }
2904- } else {
2905-
2906- // Result is negative if x is negative and the last digit of integer y is odd.
2907- s = s < 0 && y['c'][ Math.max( e, b ) ] & 1 ? -1 : 1;
2908-
2909- b = mathpow( +x, yN );
2910-
2911- /*
2912- Estimate result exponent.
2913- x^y = 10^e, where e = y * log10(x)
2914- log10(x) = log10(x_significand) + x_exponent
2915- log10(x_significand) = ln(x_significand) / ln(10)
2916- */
2917- e = b == 0 || !isFinite(b)
2918- ? mathfloor( yN * (
2919- Math.log( '0.' + coefficientToString( x['c'] ) ) / Math.LN10 + x['e'] + 1 ) )
2920- : new Decimal( b + '' )['e'];
2921-
2922- // Estimate may be incorrect e.g.: x: 0.999999999999999999, y: 2.29, e: 0, r.e:-1
2923-
2924- // Overflow/underflow?
2925- if ( e > Decimal['maxE'] + 1 || e < Decimal['minE'] - 1 ) {
2926-
2927- return new Decimal( e > 0 ? s / 0 : 0 );
2928- }
2929-
2930- external = false;
2931- Decimal['rounding'] = x['s'] = 1;
2932-
2933- /*
2934- Estimate extra digits needed from ln(x) to ensure five correct rounding digits
2935- in result (i was unnecessary before max exponent was extended?).
2936- Example of failure before i was introduced: (precision: 10),
2937- new Decimal(2.32456).pow('2087987436534566.46411')
2938- should be 1.162377823e+764914905173815, but is 1.162355823e+764914905173815
2939- */
2940- i = Math.min( 12, ( e + '' ).length );
2941-
2942- // r = x^y = exp(y*ln(x))
2943- r = exp( y['times']( ln( x, pr + i ) ), pr );
2944-
2945- // Truncate to the required precision plus five rounding digits.
2946- r = rnd( r, pr + 5, 1 );
2947-
2948- /*
2949- If the rounding digits are [49]9999 or [50]0000 increase the precision by 10
2950- and recalculate the result.
2951- */
2952- if ( checkRoundingDigits( r['c'], pr, rm ) ) {
2953- e = pr + 10;
2954-
2955- // Truncate to the increased precision plus five rounding digits.
2956- r = rnd( exp( y['times']( ln( x, e + i ) ), e ), e + 5, 1 );
2957-
2958- /*
2959- Check for 14 nines from the 2nd rounding digit (the first rounding digit
2960- may be 4 or 9).
2961- */
2962- if ( +coefficientToString( r['c'] ).slice( pr + 1, pr + 15 ) + 1 == 1e14 ) {
2963- r = rnd( r, pr + 1, 0 );
2964- }
2965- }
2966-
2967- r['s'] = s;
2968- external = true;
2969- Decimal['rounding'] = rm;
2970- }
2971-
2972- r = rnd( r, pr, rm );
2973- }
2974- }
2975-
2976- return r;
2977- };
2978-
2979-
2980- /*
2981- * Return a string representing the value of this Decimal rounded to sd significant digits
2982- * using rounding mode rounding.
2983- *
2984- * Return exponential notation if sd is less than the number of digits necessary to represent
2985- * the integer part of the value in normal notation.
2986- *
2987- * sd {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
2988- * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
2989- *
2990- * errors true: Throw if sd and rm are not undefined, null or integers in range.
2991- * errors false: Ignore sd and rm if not numbers or not in range, and truncate non-integers.
2992- *
2993- * 'toPrecision() sd not an integer: {sd}'
2994- * 'toPrecision() sd out of range: {sd}'
2995- * 'toPrecision() rounding mode not an integer: {rm}'
2996- * 'toPrecision() rounding mode out of range: {rm}'
2997- *
2998- */
2999- P['toPrecision'] = function ( sd, rm ) {
3000- var x = this;
3001-
3002- return sd != null && checkArg( x, sd, 'toPrecision', 1 ) && x['c']
3003- ? format( x, --sd | 0, checkRM( x, rm, 'toPrecision' ), 2 )
3004- : x.toString();
3005- };
3006-
3007-
3008- /*
3009- * Return a new Decimal whose value is this Decimal rounded to a maximum of d significant
3010- * digits using rounding mode rm, or to precision and rounding respectively if omitted.
3011- *
3012- * [d] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
3013- * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
3014- *
3015- * 'toSD() digits out of range: {d}'
3016- * 'toSD() digits not an integer: {d}'
3017- * 'toSD() rounding mode not an integer: {rm}'
3018- * 'toSD() rounding mode out of range: {rm}'
3019- *
3020- */
3021- P['toSignificantDigits'] = P['toSD'] = function ( d, rm ) {
3022- var x = this,
3023- Decimal = x['constructor'];
3024-
3025- x = new Decimal(x);
3026-
3027- return d == null || !checkArg( x, d, 'toSD', 1 )
3028- ? rnd( x, Decimal['precision'], Decimal['rounding'] )
3029- : rnd( x, d | 0, checkRM( x, rm, 'toSD' ) );
3030- };
3031-
3032-
3033- /*
3034- * Return a string representing the value of this Decimal in base b, or base 10 if b is
3035- * omitted. If a base is specified, including base 10, round to precision significant digits
3036- * using rounding mode rounding.
3037- *
3038- * Return exponential notation if a base is not specified, and this Decimal has a positive
3039- * exponent equal to or greater than toExpPos, or a negative exponent equal to or less than
3040- * toExpNeg.
3041- *
3042- * [b] {number} Base. Integer, 2 to 64 inclusive.
3043- *
3044- */
3045- P['toString'] = function (b) {
3046- var u, str, strL,
3047- x = this,
3048- Decimal = x['constructor'],
3049- xe = x['e'];
3050-
3051- // Infinity or NaN?
3052- if ( xe === null ) {
3053- str = x['s'] ? 'Infinity' : 'NaN';
3054-
3055- // Exponential format?
3056- } else if ( b === u && ( xe <= Decimal['toExpNeg'] || xe >= Decimal['toExpPos'] ) ) {
3057-
3058- return format( x, null, Decimal['rounding'], 1 );
3059- } else {
3060- str = coefficientToString( x['c'] );
3061-
3062- // Negative exponent?
3063- if ( xe < 0 ) {
3064-
3065- // Prepend zeros.
3066- for ( ; ++xe; str = '0' + str );
3067- str = '0.' + str;
3068-
3069- // Positive exponent?
3070- } else if ( strL = str.length, xe > 0 ) {
3071-
3072- if ( ++xe > strL ) {
3073-
3074- // Append zeros.
3075- for ( xe -= strL; xe-- ; str += '0' );
3076-
3077- } else if ( xe < strL ) {
3078- str = str.slice( 0, xe ) + '.' + str.slice(xe);
3079- }
3080-
3081- // Exponent zero.
3082- } else {
3083- u = str.charAt(0);
3084-
3085- if ( strL > 1 ) {
3086- str = u + '.' + str.slice(1);
3087-
3088- // Avoid '-0'
3089- } else if ( u == '0' ) {
3090-
3091- return u;
3092- }
3093- }
3094-
3095- if ( b != null ) {
3096-
3097- if ( !( outOfRange = !( b >= 2 && b < 65 ) ) &&
3098- ( b == (b | 0) || !Decimal['errors'] ) ) {
3099- str = convertBase( Decimal, str, b | 0, 10, x['s'] );
3100-
3101- // Avoid '-0'
3102- if ( str == '0' ) {
3103-
3104- return str;
3105- }
3106- } else {
3107-
3108- // 'toString() base not an integer: {b}'
3109- // 'toString() base out of range: {b}'
3110- ifExceptionsThrow( Decimal, 'base', b, 'toString', 0 );
3111- }
3112- }
3113- }
3114-
3115- return x['s'] < 0 ? '-' + str : str;
3116- };
3117-
3118-
3119- /*
3120- * Return a new Decimal whose value is the value of this Decimal truncated to a whole number.
3121- *
3122- */
3123- P['truncated'] = P['trunc'] = function () {
3124-
3125- return rnd( new this['constructor'](this), this['e'] + 1, 1 );
3126- };
3127-
3128-
3129- /*
3130- * Return as toString, but do not accept a base argument.
3131- *
3132- * Ensures that JSON.stringify() uses toString for serialization.
3133- *
3134- */
3135- P['valueOf'] = P['toJSON'] = function () {
3136-
3137- return this.toString();
3138- };
3139-
3140-
3141- /*
3142- // Add aliases to match BigDecimal method names.
3143- P['add'] = P['plus'];
3144- P['subtract'] = P['minus'];
3145- P['multiply'] = P['times'];
3146- P['divide'] = P['div'];
3147- P['remainder'] = P['mod'];
3148- P['compareTo'] = P['cmp'];
3149- P['negate'] = P['neg'];
3150- */
3151-
3152-
3153- // Private functions for Decimal.prototype methods.
3154-
3155-
3156- /*
3157- * coefficientToString
3158- * checkRoundingDigits
3159- * checkRM
3160- * checkArg
3161- * convertBase
3162- * div
3163- * exp
3164- * format
3165- * getCoeffLength
3166- * ifExceptionsThrow
3167- * intPow
3168- * ln
3169- * rnd
3170- */
3171-
3172-
3173- function coefficientToString(a) {
3174- var s, z,
3175- i = 1,
3176- j = a.length,
3177- r = a[0] + '';
3178-
3179- for ( ; i < j; i++ ) {
3180- s = a[i] + '';
3181-
3182- for ( z = LOGBASE - s.length; z--; ) {
3183- s = '0' + s;
3184- }
3185-
3186- r += s;
3187- }
3188-
3189- for ( j = r.length; r.charAt(--j) == '0'; );
3190-
3191- return r.slice( 0, j + 1 || 1 );
3192- }
3193-
3194-
3195- /*
3196- * Check 5 rounding digits if repeating is null, 4 otherwise.
3197- * repeating == null if caller is log or pow,
3198- * repeating != null if caller is ln or exp.
3199- *
3200- *
3201- // Previous, much simpler implementation when coefficient was base 10.
3202- function checkRoundingDigits( c, i, rm, repeating ) {
3203- return ( !repeating && rm > 3 && c[i] == 4 ||
3204- ( repeating || rm < 4 ) && c[i] == 9 ) && c[i + 1] == 9 && c[i + 2] == 9 &&
3205- c[i + 3] == 9 && ( repeating != null || c[i + 4] == 9 ) ||
3206- repeating == null && ( c[i] == 5 || !c[i] ) && !c[i + 1] && !c[i + 2] &&
3207- !c[i + 3] && !c[i + 4];
3208- }
3209- */
3210- function checkRoundingDigits( c, i, rm, repeating ) {
3211- var ci, k, n, r, rd;
3212-
3213- // Get the length of the first element of the array c.
3214- for ( k = 1, n = c[0]; n >= 10; n /= 10, k++ );
3215-
3216- n = i - k;
3217-
3218- // Is the rounding digit in the first element of c?
3219- if ( n < 0 ) {
3220- n += LOGBASE;
3221- ci = 0;
3222- } else {
3223- ci = Math.ceil( ( n + 1 ) / LOGBASE );
3224- n %= LOGBASE;
3225- }
3226-
3227- k =mathpow( 10, LOGBASE - n );
3228- rd = c[ci] % k | 0;
3229-
3230- if ( repeating == null ) {
3231-
3232- if ( n < 3 ) {
3233-
3234- if ( n == 0 ) {
3235- rd = rd / 100 | 0;
3236- } else if ( n == 1 ) {
3237- rd = rd / 10 | 0;
3238- }
3239-
3240- r = rm < 4 && rd == 99999 || rm > 3 && rd == 49999 || rd == 50000 || rd == 0;
3241- } else {
3242- r = ( rm < 4 && rd + 1 == k || rm > 3 && rd + 1 == k / 2 ) &&
3243- ( c[ci + 1] / k / 100 | 0 ) == mathpow( 10, n - 2 ) - 1 ||
3244- ( rd == k / 2 || rd == 0 ) && ( c[ci + 1] / k / 100 | 0 ) == 0;
3245- }
3246- } else {
3247-
3248- if ( n < 4 ) {
3249-
3250- if ( n == 0 ) {
3251- rd = rd / 1000 | 0;
3252- } else if ( n == 1 ) {
3253- rd = rd / 100 | 0;
3254- } else if ( n == 2 ) {
3255- rd = rd / 10 | 0;
3256- }
3257-
3258- r = ( repeating || rm < 4 ) && rd == 9999 || !repeating && rm > 3 && rd == 4999;
3259- } else {
3260- r = ( ( repeating || rm < 4 ) && rd + 1 == k ||
3261- ( !repeating && rm > 3 ) && rd + 1 == k / 2 ) &&
3262- ( c[ci + 1] / k / 1000 | 0 ) == mathpow( 10, n - 3 ) - 1;
3263- }
3264- }
3265-
3266- return r;
3267- }
3268-
3269-
3270- /*
3271- * Check and return rounding mode. If rm is invalid, return rounding mode rounding.
3272- */
3273- function checkRM( x, rm, method ) {
3274- var Decimal = x['constructor'];
3275-
3276- return rm == null || ( ( outOfRange = rm < 0 || rm > 8 ) ||
3277- rm !== 0 && ( Decimal['errors'] ? parseInt : parseFloat )(rm) != rm ) &&
3278- !ifExceptionsThrow( Decimal, 'rounding mode', rm, method, 0 )
3279- ? Decimal['rounding'] : rm | 0;
3280- }
3281-
3282-
3283- /*
3284- * Check that argument n is in range, return true or false.
3285- */
3286- function checkArg( x, n, method, min ) {
3287- var Decimal = x['constructor'];
3288-
3289- return !( outOfRange = n < ( min || 0 ) || n >= MAX_DIGITS + 1 ) &&
3290-
3291- /*
3292- * Include 'n === 0' because Opera has 'parseFloat(-0) == -0' as false
3293- * despite having 'parseFloat(-0) === -0 && parseFloat('-0') === -0 && 0 == -0' as true.
3294- */
3295- ( n === 0 || ( Decimal['errors'] ? parseInt : parseFloat )(n) == n ) ||
3296- ifExceptionsThrow( Decimal, 'argument', n, method, 0 );
3297- }
3298-
3299-
3300- /*
3301- * Convert a numeric string of baseIn to a numeric string of baseOut.
3302- */
3303- convertBase = (function () {
3304-
3305- /*
3306- * Convert string of baseIn to an array of numbers of baseOut.
3307- * Eg. convertBase('255', 10, 16) returns [15, 15].
3308- * Eg. convertBase('ff', 16, 10) returns [2, 5, 5].
3309- */
3310- function toBaseOut( str, baseIn, baseOut ) {
3311- var j,
3312- arr = [0],
3313- arrL,
3314- i = 0,
3315- strL = str.length;
3316-
3317- for ( ; i < strL; ) {
3318-
3319- for ( arrL = arr.length; arrL--; arr[arrL] *= baseIn );
3320-
3321- arr[ j = 0 ] += NUMERALS.indexOf( str.charAt( i++ ) );
3322-
3323- for ( ; j < arr.length; j++ ) {
3324-
3325- if ( arr[j] > baseOut - 1 ) {
3326-
3327- if ( arr[j + 1] == null ) {
3328- arr[j + 1] = 0;
3329- }
3330- arr[j + 1] += arr[j] / baseOut | 0;
3331- arr[j] %= baseOut;
3332- }
3333- }
3334- }
3335-
3336- return arr.reverse();
3337- }
3338-
3339- return function ( Decimal, str, baseOut, baseIn, sign ) {
3340- var e, j, r, x, xc, y,
3341- i = str.indexOf( '.' ),
3342- pr = Decimal['precision'],
3343- rm = Decimal['rounding'];
3344-
3345- if ( baseIn < 37 ) {
3346- str = str.toLowerCase();
3347- }
3348-
3349- // Non-integer.
3350- if ( i >= 0 ) {
3351- str = str.replace( '.', '' );
3352- y = new Decimal(baseIn);
3353- x = intPow( Decimal, y, str.length - i );
3354-
3355- /*
3356- Convert str as if an integer, then divide the result by its base raised to a power
3357- such that the fraction part will be restored.
3358- Use toFixed to avoid possible exponential notation.
3359- */
3360- y['c'] = toBaseOut( x.toFixed(), 10, baseOut );
3361- y['e'] = y['c'].length;
3362- }
3363-
3364- // Convert the number as integer.
3365- xc = toBaseOut( str, baseIn, baseOut );
3366- e = j = xc.length;
3367-
3368- // Remove trailing zeros.
3369- for ( ; xc[--j] == 0; xc.pop() );
3370-
3371- if ( !xc[0] ) {
3372-
3373- return '0';
3374- }
3375-
3376- if ( i < 0 ) {
3377- e--;
3378- } else {
3379- x['c'] = xc;
3380- x['e'] = e;
3381-
3382- // sign is needed for correct rounding.
3383- x['s'] = sign;
3384- x = div( x, y, pr, rm, 0, baseOut );
3385- xc = x['c'];
3386- r = x['r'];
3387- e = x['e'];
3388- }
3389-
3390- // The rounding digit, i.e. the digit after the digit that may be rounded up.
3391- i = xc[pr];
3392- j = baseOut / 2;
3393- r = r || xc[pr + 1] != null;
3394-
3395- if ( rm < 4
3396- ? ( i != null || r ) && ( rm == 0 || rm == ( x['s'] < 0 ? 3 : 2 ) )
3397- : i > j || i == j && ( rm == 4 || r || rm == 6 && xc[pr - 1] & 1 ||
3398- rm == ( x['s'] < 0 ? 8 : 7 ) ) ) {
3399-
3400- xc.length = pr;
3401-
3402- // Rounding up may mean the previous digit has to be rounded up and so on.
3403- for ( --baseOut; ++xc[--pr] > baseOut; ) {
3404- xc[pr] = 0;
3405-
3406- if ( !pr ) {
3407- ++e;
3408- xc.unshift(1);
3409- }
3410- }
3411- } else {
3412- xc.length = pr;
3413- }
3414-
3415- // Determine trailing zeros.
3416- for ( j = xc.length; !xc[--j]; );
3417-
3418- // E.g. [4, 11, 15] becomes 4bf.
3419- for ( i = 0, str = ''; i <= j; str += NUMERALS.charAt( xc[i++] ) );
3420-
3421- // Negative exponent?
3422- if ( e < 0 ) {
3423-
3424- // Prepend zeros.
3425- for ( ; ++e; str = '0' + str );
3426-
3427- str = '0.' + str;
3428-
3429- // Positive exponent?
3430- } else {
3431- i = str.length;
3432-
3433- if ( ++e > i ) {
3434-
3435- // Append zeros.
3436- for ( e -= i; e-- ; str += '0' );
3437-
3438- } else if ( e < i ) {
3439- str = str.slice( 0, e ) + '.' + str.slice(e);
3440- }
3441- }
3442-
3443- // No negative numbers: the caller will add the sign.
3444- return str;
3445- }
3446- })();
3447-
3448-
3449- /*
3450- * Perform division in the specified base. Called by div and convertBase.
3451- */
3452- var div = ( function () {
3453-
3454- // Assumes non-zero x and k, and hence non-zero result.
3455- function multiplyInteger( x, k, base ) {
3456- var temp,
3457- carry = 0,
3458- i = x.length;
3459-
3460- for ( x = x.slice(); i--; ) {
3461- temp = x[i] * k + carry;
3462- x[i] = temp % base | 0;
3463- carry = temp / base | 0;
3464- }
3465-
3466- if (carry) {
3467- x.unshift(carry);
3468- }
3469-
3470- return x;
3471- }
3472-
3473- function compare( a, b, aL, bL ) {
3474- var i, cmp;
3475-
3476- if ( aL != bL ) {
3477- cmp = aL > bL ? 1 : -1;
3478- } else {
3479-
3480- for ( i = cmp = 0; i < aL; i++ ) {
3481-
3482- if ( a[i] != b[i] ) {
3483- cmp = a[i] > b[i] ? 1 : -1;
3484-
3485- break;
3486- }
3487- }
3488- }
3489-
3490- return cmp;
3491- }
3492-
3493- function subtract( a, b, aL, base ) {
3494- var i = 0;
3495-
3496- // Subtract b from a.
3497- for ( ; aL--; ) {
3498- a[aL] -= i;
3499- i = a[aL] < b[aL] ? 1 : 0;
3500- a[aL] = i * base + a[aL] - b[aL];
3501- }
3502-
3503- // Remove leading zeros.
3504- for ( ; !a[0] && a.length > 1; a.shift() );
3505- }
3506-
3507- // x: dividend, y: divisor.
3508- return function ( x, y, pr, rm, dp, base ) {
3509- var cmp, e, i, logbase, more, n, prod, prodL, q, qc, rem, remL, rem0, t, xi, xL, yc0,
3510- yL, yz,
3511- Decimal = x['constructor'],
3512- s = x['s'] == y['s'] ? 1 : -1,
3513- xc = x['c'],
3514- yc = y['c'];
3515-
3516- // Either NaN, Infinity or 0?
3517- if ( !xc || !xc[0] || !yc || !yc[0] ) {
3518-
3519- return new Decimal(
3520-
3521- // Return NaN if either NaN, or both Infinity or 0.
3522- !x['s'] || !y['s'] || ( xc ? yc && xc[0] == yc[0] : !yc ) ? NaN :
3523-
3524- // Return +-0 if x is 0 or y is +-Infinity, or return +-Infinity as y is 0.
3525- xc && xc[0] == 0 || !yc ? s * 0 : s / 0
3526- );
3527- }
3528-
3529- if (base) {
3530- logbase = 1;
3531- e = x['e'] - y['e'];
3532- } else {
3533- base = BASE;
3534- logbase = LOGBASE;
3535- e = mathfloor( x['e'] / logbase ) - mathfloor( y['e'] / logbase );
3536- }
3537-
3538- yL = yc.length;
3539- xL = xc.length;
3540- q = new Decimal(s);
3541- qc = q['c'] = [];
3542-
3543- // Result exponent may be one less then the current value of e.
3544- // The coefficients of the Decimals from convertBase may have trailing zeros.
3545- for ( i = 0; yc[i] == ( xc[i] || 0 ); i++ );
3546-
3547- if ( yc[i] > ( xc[i] || 0 ) ) {
3548- e--;
3549- }
3550-
3551- if ( pr == null ) {
3552- s = pr = Decimal['precision'];
3553- rm = Decimal['rounding'];
3554- } else if (dp) {
3555- s = pr + ( x['e'] - y['e'] ) + 1;
3556- } else {
3557- s = pr;
3558- }
3559-
3560- if ( s < 0 ) {
3561- qc.push(1);
3562- more = true;
3563- } else {
3564-
3565- // Convert base 10 decimal places to base 1e7 decimal places.
3566- s = s / logbase + 2 | 0;
3567- i = 0;
3568-
3569- // divisor < 1e7
3570- if ( yL == 1 ) {
3571- n = 0;
3572- yc = yc[0];
3573- s++;
3574-
3575- // 'n' is the carry.
3576- for ( ; ( i < xL || n ) && s--; i++ ) {
3577- t = n * base + ( xc[i] || 0 );
3578- qc[i] = t / yc | 0;
3579- n = t % yc | 0;
3580- }
3581-
3582- more = n || i < xL;
3583-
3584- // divisor >= 1e7
3585- } else {
3586-
3587- // Normalise xc and yc so highest order digit of yc is >= base/2
3588- n = base / ( yc[0] + 1 ) | 0;
3589-
3590- if ( n > 1 ) {
3591- yc = multiplyInteger( yc, n, base );
3592- xc = multiplyInteger( xc, n, base );
3593- yL = yc.length;
3594- xL = xc.length;
3595- }
3596-
3597- xi = yL;
3598- rem = xc.slice( 0, yL );
3599- remL = rem.length;
3600-
3601- // Add zeros to make remainder as long as divisor.
3602- for ( ; remL < yL; rem[remL++] = 0 );
3603-
3604- yz = yc.slice();
3605- yz.unshift(0);
3606- yc0 = yc[0];
3607-
3608- if ( yc[1] >= base / 2 ) {
3609- yc0++;
3610- }
3611-
3612- do {
3613- n = 0;
3614-
3615- // Compare divisor and remainder.
3616- cmp = compare( yc, rem, yL, remL );
3617-
3618- // If divisor < remainder.
3619- if ( cmp < 0 ) {
3620-
3621- // Calculate trial digit, n.
3622- rem0 = rem[0];
3623-
3624- if ( yL != remL ) {
3625- rem0 = rem0 * base + ( rem[1] || 0 );
3626- }
3627-
3628- // n will be how many times the divisor goes into the current remainder.
3629- n = rem0 / yc0 | 0;
3630-
3631- /*
3632- Algorithm:
3633- 1. product = divisor * trial digit (n)
3634- 2. if product > remainder: product -= divisor, n--
3635- 3. remainder -= product
3636- 4. if product was < remainder at 2:
3637- 5. compare new remainder and divisor
3638- 6. If remainder > divisor: remainder -= divisor, n++
3639- */
3640-
3641- if ( n > 1 ) {
3642-
3643- if ( n >= base ) {
3644- n = base - 1;
3645- }
3646-
3647- // product = divisor * trial digit.
3648- prod = multiplyInteger( yc, n, base );
3649- prodL = prod.length;
3650- remL = rem.length;
3651-
3652- // Compare product and remainder.
3653- cmp = compare( prod, rem, prodL, remL );
3654-
3655- // product > remainder.
3656- if ( cmp == 1 ) {
3657- n--;
3658-
3659- // Subtract divisor from product.
3660- subtract( prod, yL < prodL ? yz : yc, prodL, base );
3661- }
3662- } else {
3663-
3664- // cmp is -1.
3665- // If n is 0, there is no need to compare yc and rem again below, so change cmp to 1 to avoid it.
3666- // If n is 1 there IS a need to compare yc and rem again below.
3667- if ( n == 0 ) {
3668- cmp = n = 1;
3669- }
3670- prod = yc.slice();
3671- }
3672- prodL = prod.length;
3673-
3674- if ( prodL < remL ) {
3675- prod.unshift(0);
3676- }
3677-
3678- // Subtract product from remainder.
3679- subtract( rem, prod, remL, base );
3680-
3681- // If product was < previous remainder.
3682- if ( cmp == -1 ) {
3683- remL = rem.length;
3684-
3685- // Compare divisor and new remainder.
3686- cmp = compare( yc, rem, yL, remL );
3687-
3688- // If divisor < new remainder, subtract divisor from remainder.
3689- if ( cmp < 1 ) {
3690- n++;
3691-
3692- // Subtract divisor from remainder.
3693- subtract( rem, yL < remL ? yz : yc, remL, base );
3694- }
3695- }
3696-
3697- remL = rem.length;
3698-
3699- } else if ( cmp === 0 ) {
3700- n++;
3701- rem = [0];
3702- } // if cmp === 1, n will be 0
3703-
3704- // Add the next digit, n, to the result array.
3705- qc[i++] = n;
3706-
3707- // Update the remainder.
3708- if ( cmp && rem[0] ) {
3709- rem[remL++] = xc[xi] || 0;
3710- } else {
3711- rem = [ xc[xi] ];
3712- remL = 1;
3713- }
3714-
3715- } while ( ( xi++ < xL || rem[0] != null ) && s-- );
3716-
3717- more = rem[0] != null;
3718- }
3719-
3720- // Leading zero?
3721- if ( !qc[0] ) {
3722- qc.shift();
3723- }
3724- }
3725-
3726- // If div is being used for base conversion.
3727- if ( logbase == 1 ) {
3728- q['e'] = e;
3729- q['r'] = +more;
3730- } else {
3731-
3732- // To calculate q.e, first get the number of digits of qc[0].
3733- for ( i = 1, s = qc[0]; s >= 10; s /= 10, i++ );
3734- q['e'] = i + e * logbase - 1;
3735-
3736- rnd( q, dp ? pr + q['e'] + 1 : pr, rm, more );
3737- }
3738-
3739- return q;
3740- }
3741- })();
3742-
3743-
3744- /*
3745- * Taylor/Maclaurin series.
3746- *
3747- * exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ...
3748- *
3749- * Argument reduction:
3750- * Repeat x = x / 32, k += 5, until |x| < 0.1
3751- * exp(x) = exp(x / 2^k)^(2^k)
3752- *
3753- * Previously, the argument was initially reduced by
3754- * exp(x) = exp(r) * 10^k where r = x - k * ln10, k = floor(x / ln10)
3755- * to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was
3756- * found to be slower than just dividing repeatedly by 32 as above.
3757- *
3758- * Max integer argument: exp('20723265836946413') = 6.3e+9000000000000000
3759- * Min integer argument: exp('-20723265836946411') = 1.2e-9000000000000000
3760- * ( Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324 )
3761- *
3762- * exp(Infinity) = Infinity
3763- * exp(-Infinity) = 0
3764- * exp(NaN) = NaN
3765- * exp(+-0) = 1
3766- *
3767- * exp(x) is non-terminating for any finite, non-zero x.
3768- *
3769- * The result will always be correctly rounded.
3770- *
3771- */
3772- function exp( x, pr ) {
3773- var denom, guard, j, pow, sd, sum, t,
3774- rep = 0,
3775- i = 0,
3776- k = 0,
3777- Decimal = x['constructor'],
3778- one = Decimal['ONE'],
3779- rm = Decimal['rounding'],
3780- precision = Decimal['precision'];
3781-
3782- // 0/NaN/Infinity?
3783- if ( !x['c'] || !x['c'][0] || x['e'] > 17 ) {
3784-
3785- return new Decimal( x['c']
3786- ? !x['c'][0] ? one : x['s'] < 0 ? 0 : 1 / 0
3787- : x['s'] ? x['s'] < 0 ? 0 : x : NaN );
3788- }
3789-
3790- if ( pr == null ) {
3791-
3792- /*
3793- Estimate result exponent.
3794- e^x = 10^j, where j = x * log10(e) and
3795- log10(e) = ln(e) / ln(10) = 1 / ln(10),
3796- so j = x / ln(10)
3797- j = mathfloor( x / Math.LN10 );
3798-
3799- // Overflow/underflow? Estimate may be +-1 of true value.
3800- if ( j > Decimal['maxE'] + 1 || j < Decimal['minE'] - 1 ) {
3801-
3802- return new Decimal( j > 0 ? 1 / 0 : 0 );
3803- }
3804- */
3805-
3806- external = false;
3807- sd = precision;
3808- } else {
3809- sd = pr;
3810- }
3811-
3812- t = new Decimal(0.03125);
3813-
3814- // while abs(x) >= 0.1
3815- while ( x['e'] > -2 ) {
3816-
3817- // x = x / 2^5
3818- x = x['times'](t);
3819- k += 5;
3820- }
3821-
3822- /*
3823- Use 2 * log10(2^k) + 5 to estimate the increase in precision necessary to ensure the first
3824- 4 rounding digits are correct.
3825- */
3826- guard = Math.log( mathpow( 2, k ) ) / Math.LN10 * 2 + 5 | 0;
3827- sd += guard;
3828-
3829- denom = pow = sum = new Decimal(one);
3830- Decimal['precision'] = sd;
3831-
3832- for ( ; ; ) {
3833- pow = rnd( pow['times'](x), sd, 1 );
3834- denom = denom['times'](++i);
3835- t = sum['plus']( div( pow, denom, sd, 1 ) );
3836-
3837- if ( coefficientToString( t['c'] ).slice( 0, sd ) ===
3838- coefficientToString( sum['c'] ).slice( 0, sd ) ) {
3839- j = k;
3840-
3841- while ( j-- ) {
3842- sum = rnd( sum['times'](sum), sd, 1 );
3843- }
3844-
3845- /*
3846- Check to see if the first 4 rounding digits are [49]999.
3847- If so, repeat the summation with a higher precision, otherwise
3848- E.g. with precision: 18, rounding: 1
3849- exp(18.404272462595034083567793919843761) = 98372560.1229999999
3850- when it should be 98372560.123
3851-
3852- sd - guard is the index of first rounding digit.
3853- */
3854- if ( pr == null ) {
3855-
3856- if ( rep < 3 && checkRoundingDigits( sum['c'], sd - guard, rm, rep ) ) {
3857- Decimal['precision'] = sd += 10;
3858- denom = pow = t = new Decimal(one);
3859- i = 0;
3860- rep++;
3861- } else {
3862-
3863- return rnd( sum, Decimal['precision'] = precision, rm, external = true );
3864- }
3865- } else {
3866- Decimal['precision'] = precision;
3867-
3868- return sum;
3869- }
3870- }
3871- sum = t;
3872- }
3873- }
3874-
3875-
3876- /*
3877- * Return a string representing the value of Decimal n in normal or exponential notation
3878- * rounded to the specified decimal places or significant digits.
3879- * Called by toString, toExponential (k is 1), toFixed, and toPrecision (k is 2).
3880- * i is the index (with the value in normal notation) of the digit that may be rounded up.
3881- * j is the rounding mode, then the number of digits required including fraction-part trailing
3882- * zeros.
3883- */
3884- function format( n, i, j, k ) {
3885- var s, z,
3886- Decimal = n['constructor'],
3887- e = ( n = new Decimal(n) )['e'];
3888-
3889- // i == null when toExponential(no arg), or toString() when x >= toExpPos etc.
3890- if ( i == null ) {
3891- j = 0;
3892- } else {
3893- rnd( n, ++i, j );
3894-
3895- // If toFixed, n['e'] may have changed if the value was rounded up.
3896- j = k ? i : i + n['e'] - e;
3897- }
3898-
3899- e = n['e'];
3900- s = coefficientToString( n['c'] );
3901-
3902- /*
3903- toPrecision returns exponential notation if the number of significant digits specified
3904- is less than the number of digits necessary to represent the integer part of the value
3905- in normal notation.
3906- */
3907-
3908- // Exponential notation.
3909- if ( k == 1 || k == 2 && ( i <= e || e <= Decimal['toExpNeg'] ) ) {
3910-
3911- // Append zeros?
3912- for ( ; s.length < j; s += '0' );
3913-
3914- if ( s.length > 1 ) {
3915- s = s.charAt(0) + '.' + s.slice(1);
3916- }
3917-
3918- s += ( e < 0 ? 'e' : 'e+' ) + e;
3919-
3920- // Normal notation.
3921- } else {
3922- k = s.length;
3923-
3924- // Negative exponent?
3925- if ( e < 0 ) {
3926- z = j - k;
3927-
3928- // Prepend zeros.
3929- for ( ; ++e; s = '0' + s );
3930- s = '0.' + s;
3931-
3932- // Positive exponent?
3933- } else {
3934-
3935- if ( ++e > k ) {
3936- z = j - e;
3937-
3938- // Append zeros.
3939- for ( e -= k; e-- ; s += '0' );
3940-
3941- if ( z > 0 ) {
3942- s += '.';
3943- }
3944-
3945- } else {
3946- z = j - k;
3947-
3948- if ( e < k ) {
3949- s = s.slice( 0, e ) + '.' + s.slice(e);
3950- } else if ( z > 0 ) {
3951- s += '.';
3952- }
3953- }
3954- }
3955-
3956- // Append more zeros?
3957- if ( z > 0 ) {
3958-
3959- for ( ; z--; s += '0' );
3960- }
3961- }
3962-
3963- return n['s'] < 0 && n['c'][0] ? '-' + s : s;
3964- }
3965-
3966-
3967- function getCoeffLength(c) {
3968- var v = c.length - 1,
3969- n = v * LOGBASE + 1;
3970-
3971- if ( v = c[v] ) {
3972-
3973- // Subtract the number of trailing zeros of the last number.
3974- for ( ; v % 10 == 0; v /= 10, n-- );
3975-
3976- // Add the number of digits of the first number.
3977- for ( v = c[0]; v >= 10; v /= 10, n++ );
3978- }
3979-
3980- return n;
3981- }
3982-
3983-
3984- /*
3985- * Assemble error messages. Throw Decimal Errors.
3986- */
3987- function ifExceptionsThrow( Decimal, message, arg, method, more ) {
3988-
3989- if ( Decimal['errors'] ) {
3990- var error = new Error( ( method || [
3991- 'new Decimal', 'cmp', 'div', 'eq', 'gt', 'gte', 'lt', 'lte', 'minus', 'mod',
3992- 'plus', 'times', 'toFraction', 'pow', 'random', 'log', 'sqrt', 'toNearest', 'divToInt'
3993- ][ id ? id < 0 ? -id : id : 1 / id < 0 ? 1 : 0 ] ) + '() ' + ( [
3994- 'number type has more than 15 significant digits', 'LN10 out of digits' ][message]
3995- || message + ( [ outOfRange ? ' out of range' : ' not an integer',
3996- ' not a boolean or binary digit' ][more] || '' ) ) + ': ' + arg
3997- );
3998- error['name'] = 'Decimal Error';
3999- outOfRange = id = 0;
4000-
4001- throw error;
4002- }
4003- }
4004-
4005-
4006- /*
4007- * Use 'exponentiation by squaring' for small integers. Called by convertBase and pow.
4008- */
4009- function intPow( Decimal, x, i ) {
4010- var r = new Decimal( Decimal['ONE'] );
4011-
4012- for ( external = false; ; ) {
4013-
4014- if ( i & 1 ) {
4015- r = r['times'](x);
4016- }
4017- i >>= 1;
4018-
4019- if ( !i ) {
4020-
4021- break;
4022- }
4023- x = x['times'](x);
4024- }
4025- external = true;
4026-
4027- return r;
4028- }
4029-
4030-
4031- /*
4032- * ln(-n) = NaN
4033- * ln(0) = -Infinity
4034- * ln(-0) = -Infinity
4035- * ln(1) = 0
4036- * ln(Infinity) = Infinity
4037- * ln(-Infinity) = NaN
4038- * ln(NaN) = NaN
4039- *
4040- * ln(n) (n != 1) is non-terminating.
4041- *
4042- */
4043- function ln( y, pr ) {
4044- var c, c0, denom, e, num, rep, sd, sum, t, x1, x2,
4045- n = 1,
4046- guard = 10,
4047- x = y,
4048- xc = x['c'],
4049- Decimal = x['constructor'],
4050- one = Decimal['ONE'],
4051- rm = Decimal['rounding'],
4052- precision = Decimal['precision'];
4053-
4054- // x < 0 or +-Infinity/NaN or 0 or 1.
4055- if ( x['s'] < 0 || !xc || !xc[0] || !x['e'] && xc[0] == 1 && xc.length == 1 ) {
4056-
4057- return new Decimal( xc && !xc[0] ? -1 / 0 : x['s'] != 1 ? NaN : xc ? 0 : x );
4058- }
4059-
4060- if ( pr == null ) {
4061- external = false;
4062- sd = precision;
4063- } else {
4064- sd = pr;
4065- }
4066-
4067- Decimal['precision'] = sd += guard;
4068-
4069- c = coefficientToString(xc);
4070- c0 = c.charAt(0);
4071-
4072- if ( Math.abs( e = x['e'] ) < 1.5e15 ) {
4073-
4074- /*
4075- Argument reduction.
4076- The series converges faster the closer the argument is to 1, so using
4077- ln(a^b) = b * ln(a), ln(a) = ln(a^b) / b
4078- multiply the argument by itself until the leading digits of the significand are 7, 8,
4079- 9, 10, 11, 12 or 13, recording the number of multiplications so the sum of the series
4080- can later be divided by this number, then separate out the power of 10 using
4081- ln(a*10^b) = ln(a) + b*ln(10).
4082- */
4083-
4084- // max n is 21 ( gives 0.9, 1.0 or 1.1 ) ( 9e15 / 21 = 4.2e14 ).
4085- //while ( c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1 ) {
4086- // max n is 6 ( gives 0.7 - 1.3 )
4087- while ( c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3 ) {
4088- x = x['times'](y);
4089- c = coefficientToString( x['c'] );
4090- c0 = c.charAt(0);
4091- n++;
4092- }
4093-
4094- e = x['e'];
4095-
4096- if ( c0 > 1 ) {
4097- x = new Decimal( '0.' + c );
4098- e++;
4099- } else {
4100- x = new Decimal( c0 + '.' + c.slice(1) );
4101- }
4102- } else {
4103-
4104- /*
4105- The argument reduction method above may result in overflow if the argument y is a
4106- massive number with exponent >= 1500000000000000 ( 9e15 / 6 = 1.5e15 ), so instead
4107- recall this function using ln(x*10^e) = ln(x) + e*ln(10).
4108- */
4109- x = new Decimal( c0 + '.' + c.slice(1) );
4110-
4111- if ( sd + 2 > LN10.length ) {
4112- ifExceptionsThrow( Decimal, 1, sd + 2, 'ln' );
4113- }
4114-
4115- x = ln( x, sd - guard )['plus'](
4116- new Decimal( LN10.slice( 0, sd + 2 ) )['times']( e + '' )
4117- );
4118-
4119- Decimal['precision'] = precision;
4120-
4121- return pr == null ? rnd( x, precision, rm, external = true ) : x;
4122- }
4123-
4124- // x1 is x reduced to a value near 1.
4125- x1 = x;
4126-
4127- /*
4128- Taylor series.
4129- ln(y) = ln( (1 + x)/(1 - x) ) = 2( x + x^3/3 + x^5/5 + x^7/7 + ... )
4130- where
4131- x = (y - 1)/(y + 1) ( |x| < 1 )
4132- */
4133- sum = num = x = div( x['minus'](one), x['plus'](one), sd, 1 );
4134- x2 = rnd( x['times'](x), sd, 1 );
4135- denom = 3;
4136-
4137- for ( ; ; ) {
4138- num = rnd( num['times'](x2), sd, 1 );
4139- t = sum['plus']( div( num, new Decimal(denom), sd, 1 ) );
4140-
4141- if ( coefficientToString( t['c'] ).slice( 0, sd ) ===
4142- coefficientToString( sum['c'] ).slice( 0, sd ) ) {
4143- sum = sum['times'](2);
4144-
4145- /*
4146- Reverse the argument reduction. Check that e is not 0 because, as well as
4147- preventing an unnecessary calculation, -0 + 0 = +0 and to ensure correct
4148- rounding later -0 needs to stay -0.
4149- */
4150- if ( e !== 0 ) {
4151-
4152- if ( sd + 2 > LN10.length ) {
4153- ifExceptionsThrow( Decimal, 1, sd + 2, 'ln' );
4154- }
4155-
4156- sum = sum['plus'](
4157- new Decimal( LN10.slice( 0, sd + 2 ) )['times']( e + '' )
4158- );
4159- }
4160-
4161- sum = div( sum, new Decimal(n), sd, 1 );
4162-
4163- /*
4164- Is rm > 3 and the first 4 rounding digits 4999, or rm < 4 (or the summation has
4165- been repeated previously) and the first 4 rounding digits 9999?
4166-
4167- If so, restart the summation with a higher precision, otherwise
4168- E.g. with precision: 12, rounding: 1
4169- ln(135520028.6126091714265381533) = 18.7246299999 when it should be 18.72463.
4170-
4171- sd - guard is the index of first rounding digit.
4172- */
4173- if ( pr == null ) {
4174-
4175- if ( checkRoundingDigits( sum['c'], sd - guard, rm, rep ) ) {
4176- Decimal['precision'] = sd += guard;
4177- t = num = x = div( x1['minus'](one), x1['plus'](one), sd, 1 );
4178- x2 = rnd( x['times'](x), sd, 1 );
4179- denom = rep = 1;
4180- } else {
4181-
4182- return rnd( sum, Decimal['precision'] = precision, rm, external = true );
4183- }
4184- } else {
4185- Decimal['precision'] = precision;
4186-
4187- return sum;
4188- }
4189- }
4190-
4191- sum = t;
4192- denom += 2;
4193- }
4194- }
4195-
4196-
4197- /*
4198- * Round x to sd significant digits using rounding mode rm. Check for over/under-flow.
4199- */
4200- function rnd( x, sd, rm, r ) {
4201- var digits, i, j, k, n, rd, xc, xci,
4202- Decimal = x['constructor'];
4203-
4204- // Don't round if sd is null or undefined.
4205- r: if ( sd != i ) {
4206-
4207- // Infinity/NaN.
4208- if ( !( xc = x['c'] ) ) {
4209-
4210- return x;
4211- }
4212-
4213- /*
4214- rd, the rounding digit, i.e. the digit after the digit that may be rounded up,
4215- n, a base 1e7 number, the element of xc containing rd,
4216- xci, the index of n within xc,
4217- digits, the number of digits of n,
4218- i, what would be the index of rd within n if all the numbers were 7 digits long (i.e. they had leading zeros)
4219- j, if > 0, the actual index of rd within n (if < 0, rd is a leading zero),
4220- nLeadingZeros, the number of leading zeros n would have if it were 7 digits long.
4221- */
4222-
4223- // Get the length of the first element of the coefficient array xc.
4224- for ( digits = 1, k = xc[0]; k >= 10; k /= 10, digits++ );
4225-
4226- i = sd - digits;
4227-
4228- // Is the rounding digit in the first element of xc?
4229- if ( i < 0 ) {
4230- i += LOGBASE;
4231- j = sd;
4232- n = xc[ xci = 0 ];
4233-
4234- // Get the rounding digit at index j of n.
4235- rd = n / mathpow( 10, digits - j - 1 ) % 10 | 0;
4236- } else {
4237- xci = Math.ceil( ( i + 1 ) / LOGBASE );
4238-
4239- if ( xci >= xc.length ) {
4240-
4241- if (r) {
4242-
4243- // Needed by exp, ln and sqrt.
4244- for ( ; xc.length <= xci; xc.push(0) );
4245-
4246- n = rd = 0;
4247- digits = 1;
4248- i %= LOGBASE;
4249- j = i - LOGBASE + 1;
4250- } else {
4251-
4252- break r;
4253- }
4254- } else {
4255- n = k = xc[xci];
4256-
4257- // Get the number of digits of n.
4258- for ( digits = 1; k >= 10; k /= 10, digits++ );
4259-
4260- // Get the index of rd within n.
4261- i %= LOGBASE;
4262-
4263- // Get the index of rd within n, adjusted for leading zeros.
4264- // The number of leading zeros of n is given by LOGBASE - digits.
4265- j = i - LOGBASE + digits;
4266-
4267- // Get the rounding digit at index j of n.
4268- // Floor using Math.floor instead of | 0 as rd may be outside int range.
4269- rd = j < 0 ? 0 : mathfloor( n / mathpow( 10, digits - j - 1 ) % 10 );
4270- }
4271- }
4272-
4273- r = r || sd < 0 ||
4274- // Are there any non-zero digits after the rounding digit?
4275- xc[xci + 1] != null || ( j < 0 ? n : n % mathpow( 10, digits - j - 1 ) );
4276-
4277- /*
4278- The expression n % mathpow( 10, digits - j - 1 ) returns all the digits of n to the
4279- right of the digit at (left-to-right) index j,
4280- e.g. if n is 908714 and j is 2, the expression will give 714.
4281- */
4282-
4283- r = rm < 4
4284- ? ( rd || r ) && ( rm == 0 || rm == ( x['s'] < 0 ? 3 : 2 ) )
4285- : rd > 5 || rd == 5 && ( rm == 4 || r ||
4286- // Check whether the digit to the left of the rounding digit is odd.
4287- rm == 6 && ( ( i > 0 ? j > 0 ? n / mathpow( 10, digits - j ) : 0 : xc[xci - 1] ) % 10 ) & 1 ||
4288- rm == ( x['s'] < 0 ? 8 : 7 ) );
4289-
4290- if ( sd < 1 || !xc[0] ) {
4291- xc.length = 0;
4292-
4293- if (r) {
4294-
4295- // Convert sd to decimal places.
4296- sd -= x['e'] + 1;
4297-
4298- // 1, 0.1, 0.01, 0.001, 0.0001 etc.
4299- xc[0] = mathpow( 10, sd % LOGBASE );
4300- x['e'] = -sd || 0;
4301- } else {
4302-
4303- // Zero.
4304- xc[0] = x['e'] = 0;
4305- }
4306-
4307- return x;
4308- }
4309-
4310- // Remove excess digits.
4311-
4312- if ( i == 0 ) {
4313- xc.length = xci;
4314- k = 1;
4315- xci--;
4316- } else {
4317- xc.length = xci + 1;
4318- k = mathpow( 10, LOGBASE - i );
4319-
4320- // E.g. 56700 becomes 56000 if 7 is the rounding digit.
4321- // j > 0 means i > number of leading zeros of n.
4322- xc[xci] = j > 0 ? ( n / mathpow( 10, digits - j ) % mathpow( 10, j ) | 0 ) * k : 0;
4323- }
4324-
4325- // Round up?
4326- if (r) {
4327-
4328- for ( ; ; ) {
4329-
4330- // Is the digit to be rounded up in the first element of xc.
4331- if ( xci == 0 ) {
4332-
4333- // i will be the length of xc[0] before k is added.
4334- for ( i = 1, j = xc[0]; j >= 10; j /= 10, i++ );
4335-
4336- j = xc[0] += k;
4337-
4338- for ( k = 1; j >= 10; j /= 10, k++ );
4339-
4340- // if i != k the length has increased.
4341- if ( i != k ) {
4342- x['e']++;
4343-
4344- if ( xc[0] == BASE ) {
4345- xc[0] = 1;
4346- }
4347- }
4348-
4349- break;
4350- } else {
4351- xc[xci] += k;
4352-
4353- if ( xc[xci] != BASE ) {
4354-
4355- break;
4356- }
4357-
4358- xc[xci--] = 0;
4359- k = 1;
4360- }
4361- }
4362- }
4363-
4364- // Remove trailing zeros.
4365- for ( i = xc.length; xc[--i] === 0; xc.pop() );
4366- }
4367-
4368- if (external) {
4369-
4370- // Overflow?
4371- if ( x['e'] > Decimal['maxE'] ) {
4372-
4373- // Infinity.
4374- x['c'] = x['e'] = null;
4375-
4376- // Underflow?
4377- } else if ( x['e'] < Decimal['minE'] ) {
4378-
4379- // Zero.
4380- x['c'] = [ x['e'] = 0 ];
4381- }
4382- }
4383-
4384- return x;
4385- }
4386-
4387-
4388- DecimalConstructor = (function () {
4389-
4390-
4391- // Private functions used by static Decimal methods.
4392-
4393-
4394- /*
4395- * The following emulations or wrappers of Math object functions are currently
4396- * commented-out and not in the public API.
4397- *
4398- * abs
4399- * acos
4400- * asin
4401- * atan
4402- * atan2
4403- * ceil
4404- * cos
4405- * floor
4406- * round
4407- * sin
4408- * tan
4409- * trunc
4410- */
4411-
4412-
4413- /*
4414- * Return a new Decimal whose value is the absolute value of n.
4415- *
4416- * n {number|string|Decimal}
4417- *
4418- function abs(n) { return new this(n)['abs']() }
4419- */
4420-
4421-
4422- /*
4423- * Return a new Decimal whose value is the arccosine in radians of n.
4424- *
4425- * n {number|string|Decimal}
4426- *
4427- function acos(n) { return new this( Math.acos(n) + '' ) }
4428- */
4429-
4430-
4431- /*
4432- * Return a new Decimal whose value is the arcsine in radians of n.
4433- *
4434- * n {number|string|Decimal}
4435- *
4436- function asin(n) { return new this( Math.asin(n) + '' ) }
4437- */
4438-
4439-
4440- /*
4441- * Return a new Decimal whose value is the arctangent in radians of n.
4442- *
4443- * n {number|string|Decimal}
4444- *
4445- function atan(n) { return new this( Math.atan(n) + '' ) }
4446- */
4447-
4448-
4449- /*
4450- * Return a new Decimal whose value is the arctangent in radians of y/x in the range
4451- * -PI to PI (inclusive).
4452- *
4453- * y {number|string|Decimal} The y-coordinate.
4454- * x {number|string|Decimal} The x-coordinate.
4455- *
4456- function atan2( y, x ) { return new this( Math.atan2( y, x ) + '' ) }
4457- */
4458-
4459-
4460- /*
4461- * Return a new Decimal whose value is n round to an integer using ROUND_CEIL.
4462- *
4463- * n {number|string|Decimal}
4464- *
4465- function ceil(n) { return new this(n)['ceil']() }
4466- */
4467-
4468-
4469- /*
4470- * Configure global settings for a Decimal constructor.
4471- *
4472- * obj is an object with any of the following properties,
4473- *
4474- * precision {number}
4475- * rounding {number}
4476- * toExpNeg {number}
4477- * toExpPos {number}
4478- * minE {number}
4479- * maxE {number}
4480- * errors {boolean|number}
4481- * crypto {boolean|number}
4482- * modulo {number}
4483- *
4484- * E.g.
4485- * Decimal.config({ precision: 20, rounding: 4 })
4486- *
4487- */
4488- function config(obj) {
4489- var p, u, v,
4490- Decimal = this,
4491- c = 'config',
4492- parse = Decimal['errors'] ? parseInt : parseFloat;
4493-
4494- if ( obj == u || typeof obj != 'object' &&
4495- !ifExceptionsThrow( Decimal, 'object expected', obj, c ) ) {
4496-
4497- return Decimal;
4498- }
4499-
4500- // precision {number|number[]} Integer, 1 to MAX_DIGITS inclusive.
4501- if ( ( v = obj[ p = 'precision' ] ) != u ) {
4502-
4503- if ( !( outOfRange = v < 1 || v > MAX_DIGITS ) && parse(v) == v ) {
4504- Decimal[p] = v | 0;
4505- } else {
4506-
4507- // 'config() precision not an integer: {v}'
4508- // 'config() precision out of range: {v}'
4509- ifExceptionsThrow( Decimal, p, v, c, 0 );
4510- }
4511- }
4512-
4513- // rounding {number} Integer, 0 to 8 inclusive.
4514- if ( ( v = obj[ p = 'rounding' ] ) != u ) {
4515-
4516- if ( !( outOfRange = v < 0 || v > 8 ) && parse(v) == v ) {
4517- Decimal[p] = v | 0;
4518- } else {
4519-
4520- // 'config() rounding not an integer: {v}'
4521- // 'config() rounding out of range: {v}'
4522- ifExceptionsThrow( Decimal, p, v, c, 0 );
4523- }
4524- }
4525-
4526- // toExpNeg {number} Integer, -EXP_LIMIT to 0 inclusive.
4527- if ( ( v = obj[ p = 'toExpNeg' ] ) != u ) {
4528-
4529- if ( !( outOfRange = v < -EXP_LIMIT || v > 0 ) && parse(v) == v ) {
4530- Decimal[p] = mathfloor(v);
4531- } else {
4532-
4533- // 'config() toExpNeg not an integer: {v}'
4534- // 'config() toExpNeg out of range: {v}'
4535- ifExceptionsThrow( Decimal, p, v, c, 0 );
4536- }
4537- }
4538-
4539- // toExpPos {number} Integer, 0 to EXP_LIMIT inclusive.
4540- if ( ( v = obj[ p = 'toExpPos' ] ) != u ) {
4541-
4542- if ( !( outOfRange = v < 0 || v > EXP_LIMIT ) && parse(v) == v ) {
4543- Decimal[p] = mathfloor(v);
4544- } else {
4545-
4546- // 'config() toExpPos not an integer: {v}'
4547- // 'config() toExpPos out of range: {v}'
4548- ifExceptionsThrow( Decimal, p, v, c, 0 );
4549- }
4550- }
4551-
4552- // minE {number} Integer, -EXP_LIMIT to 0 inclusive.
4553- if ( ( v = obj[ p = 'minE' ] ) != u ) {
4554-
4555- if ( !( outOfRange = v < -EXP_LIMIT || v > 0 ) && parse(v) == v ) {
4556- Decimal[p] = mathfloor(v);
4557- } else {
4558-
4559- // 'config() minE not an integer: {v}'
4560- // 'config() minE out of range: {v}'
4561- ifExceptionsThrow( Decimal, p, v, c, 0 );
4562- }
4563- }
4564-
4565- // maxE {number} Integer, 0 to EXP_LIMIT inclusive.
4566- if ( ( v = obj[ p = 'maxE' ] ) != u ) {
4567-
4568- if ( !( outOfRange = v < 0 || v > EXP_LIMIT ) && parse(v) == v ) {
4569- Decimal[p] = mathfloor(v);
4570- } else {
4571-
4572- // 'config() maxE not an integer: {v}'
4573- // 'config() maxE out of range: {v}'
4574- ifExceptionsThrow( Decimal, p, v, c, 0 );
4575- }
4576- }
4577-
4578- // errors {boolean|number} true, false, 1 or 0.
4579- if ( ( v = obj[ p = 'errors' ] ) != u ) {
4580-
4581- if ( v === !!v || v === 1 || v === 0 ) {
4582- outOfRange = id = 0;
4583- Decimal[p] = !!v;
4584- } else {
4585-
4586- // 'config() errors not a boolean or binary digit: {v}'
4587- ifExceptionsThrow( Decimal, p, v, c, 1 );
4588- }
4589- }
4590-
4591- // crypto {boolean|number} true, false, 1 or 0.
4592- if ( ( v = obj[ p = 'crypto' ] ) != u ) {
4593-
4594- if ( v === !!v || v === 1 || v === 0 ) {
4595- Decimal[p] = !!( v && crypto && typeof crypto == 'object' );
4596- } else {
4597-
4598- // 'config() crypto not a boolean or binary digit: {v}'
4599- ifExceptionsThrow( Decimal, p, v, c, 1 );
4600- }
4601- }
4602-
4603- // modulo {number} Integer, 0 to 9 inclusive.
4604- if ( ( v = obj[ p = 'modulo' ] ) != u ) {
4605-
4606- if ( !( outOfRange = v < 0 || v > 9 ) && parse(v) == v ) {
4607- Decimal[p] = v | 0;
4608- } else {
4609-
4610- // 'config() modulo not an integer: {v}'
4611- // 'config() modulo out of range: {v}'
4612- ifExceptionsThrow( Decimal, p, v, c, 0 );
4613- }
4614- }
4615-
4616- return Decimal;
4617- }
4618-
4619-
4620- /*
4621- * Return a new Decimal whose value is the cosine of n.
4622- *
4623- * n {number|string|Decimal} A number given in radians.
4624- *
4625- function cos(n) { return new this( Math.cos(n) + '' ) }
4626- */
4627-
4628-
4629- /*
4630- * Return a new Decimal whose value is the exponential of n,
4631- *
4632- * n {number|string|Decimal} The power to which to raise the base of the natural log.
4633- *
4634- */
4635- function exp(n) { return new this(n)['exp']() }
4636-
4637-
4638- /*
4639- * Return a new Decimal whose value is n round to an integer using ROUND_FLOOR.
4640- *
4641- * n {number|string|Decimal}
4642- *
4643- function floor(n) { return new this(n)['floor']() }
4644- */
4645-
4646-
4647- /*
4648- * Return a new Decimal whose value is the natural logarithm of n.
4649- *
4650- * n {number|string|Decimal}
4651- *
4652- */
4653- function ln(n) { return new this(n)['ln']() }
4654-
4655-
4656- /*
4657- * Return a new Decimal whose value is the log of x to the base y, or to base 10 if no
4658- * base is specified.
4659- *
4660- * log[y](x)
4661- *
4662- * x {number|string|Decimal} The argument of the logarithm.
4663- * y {number|string|Decimal} The base of the logarithm.
4664- *
4665- */
4666- function log( x, y ) { return new this(x)['log'](y) }
4667-
4668-
4669- /*
4670- * Handle max and min. ltgt is 'lt' or 'gt'.
4671- */
4672- function maxOrMin( Decimal, args, ltgt ) {
4673- var m, n,
4674- i = 0;
4675-
4676- if ( toString.call( args[0] ) == '[object Array]' ) {
4677- args = args[0];
4678- }
4679-
4680- m = new Decimal( args[0] );
4681-
4682- for ( ; ++i < args.length; ) {
4683- n = new Decimal( args[i] );
4684-
4685- if ( !n['s'] ) {
4686- m = n;
4687-
4688- break;
4689- } else if ( m[ltgt](n) ) {
4690- m = n;
4691- }
4692- }
4693-
4694- return m;
4695- }
4696-
4697-
4698- /*
4699- * Return a new Decimal whose value is the maximum of the arguments.
4700- *
4701- * arguments {number|string|Decimal}
4702- *
4703- */
4704- function max() { return maxOrMin( this, arguments, 'lt' ) }
4705-
4706-
4707- /*
4708- * Return a new Decimal whose value is the minimum of the arguments.
4709- *
4710- * arguments {number|string|Decimal}
4711- *
4712- */
4713- function min() { return maxOrMin( this, arguments, 'gt' ) }
4714-
4715-
4716- /*
4717- * Parse the value of a new Decimal from a number or string.
4718- */
4719- var parseDecimal = (function () {
4720- var isValid = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
4721- trim = String.prototype.trim || function () {return this.replace(/^\s+|\s+$/g, '')};
4722-
4723- return function ( Decimal, x, n, b ) {
4724- var d, e, i, isNum, orig, valid;
4725-
4726- if ( typeof n != 'string' ) {
4727-
4728- // TODO: modify so regex test below is avoided if type is number.
4729- // If n is a number, check if minus zero.
4730- n = ( isNum = typeof n == 'number' || toString.call(n) == '[object Number]' ) &&
4731- n === 0 && 1 / n < 0 ? '-0' : n + '';
4732- }
4733- orig = n;
4734-
4735- if ( b == e && isValid.test(n) ) {
4736-
4737- // Determine sign.
4738- x['s'] = n.charAt(0) == '-' ? ( n = n.slice(1), -1 ) : 1;
4739-
4740- // Either n is not a valid Decimal or a base has been specified.
4741- } else {
4742-
4743- /*
4744- Enable exponential notation to be used with base 10 argument.
4745- Ensure return value is rounded to precision as with other bases.
4746- */
4747- if ( b == 10 ) {
4748-
4749- return rnd( new Decimal(n), Decimal['precision'], Decimal['rounding'] );
4750- }
4751-
4752- n = trim.call(n).replace( /^\+(?!-)/, '' );
4753-
4754- x['s'] = n.charAt(0) == '-' ? ( n = n.replace( /^-(?!-)/, '' ), -1 ) : 1;
4755-
4756- if ( b != e ) {
4757-
4758- if ( ( b == (b | 0) || !Decimal['errors'] ) &&
4759- !( outOfRange = !( b >= 2 && b < 65 ) ) ) {
4760- d = '[' + NUMERALS.slice( 0, b = b | 0 ) + ']+';
4761-
4762- // Remove the `.` from e.g. '1.', and replace e.g. '.1' with '0.1'.
4763- n = n.replace( /\.$/, '' ).replace( /^\./, '0.' );
4764-
4765- // Any number in exponential form will fail due to the e+/-.
4766- if ( valid = new RegExp(
4767- '^' + d + '(?:\\.' + d + ')?$', b < 37 ? 'i' : '' ).test(n)
4768- ) {
4769-
4770- if (isNum) {
4771-
4772- if ( n.replace( /^0\.0*|\./, '' ).length > 15 ) {
4773-
4774- // '{method} number type has more than 15 significant digits: {n}'
4775- ifExceptionsThrow( Decimal, 0, orig );
4776- }
4777-
4778- // Prevent later check for length on converted number.
4779- isNum = !isNum;
4780- }
4781- n = convertBase( Decimal, n, 10, b, x['s'] );
4782-
4783- } else if ( n != 'Infinity' && n != 'NaN' ) {
4784-
4785- // '{method} not a base {b} number: {n}'
4786- ifExceptionsThrow( Decimal, 'not a base ' + b + ' number', orig );
4787- n = 'NaN';
4788- }
4789- } else {
4790-
4791- // '{method} base not an integer: {b}'
4792- // '{method} base out of range: {b}'
4793- ifExceptionsThrow( Decimal, 'base', b, 0, 0 );
4794-
4795- // Ignore base.
4796- valid = isValid.test(n);
4797- }
4798- } else {
4799- valid = isValid.test(n);
4800- }
4801-
4802- if ( !valid ) {
4803-
4804- // Infinity/NaN
4805- x['c'] = x['e'] = null;
4806-
4807- // NaN
4808- if ( n != 'Infinity' ) {
4809-
4810- // No exception on NaN.
4811- if ( n != 'NaN' ) {
4812-
4813- // '{method} not a number: {n}'
4814- ifExceptionsThrow( Decimal, 'not a number', orig );
4815- }
4816- x['s'] = null;
4817- }
4818- id = 0;
4819-
4820- return x;
4821- }
4822- }
4823-
4824- // Decimal point?
4825- if ( ( e = n.indexOf('.') ) > -1 ) {
4826- n = n.replace( '.', '' );
4827- }
4828-
4829- // Exponential form?
4830- if ( ( i = n.search( /e/i ) ) > 0 ) {
4831-
4832- // Determine exponent.
4833- if ( e < 0 ) {
4834- e = i;
4835- }
4836- e += +n.slice( i + 1 );
4837- n = n.substring( 0, i );
4838-
4839- } else if ( e < 0 ) {
4840-
4841- // Integer.
4842- e = n.length;
4843- }
4844-
4845- // Determine leading zeros.
4846- for ( i = 0; n.charAt(i) == '0'; i++ );
4847-
4848- // Determine trailing zeros.
4849- for ( b = n.length; n.charAt(--b) == '0'; );
4850-
4851- n = n.slice( i, b + 1 );
4852-
4853- if (n) {
4854- b = n.length;
4855-
4856- // Disallow numbers with over 15 significant digits if number type.
4857- if ( isNum && b > 15 ) {
4858-
4859- // '{method} number type has more than 15 significant digits: {n}'
4860- ifExceptionsThrow( Decimal, 0, orig );
4861- }
4862-
4863- x['e'] = e = e - i - 1;
4864- x['c'] = [];
4865-
4866- // Transform base
4867-
4868- // e is the base 10 exponent.
4869- // i is where to slice n to get the first element of the coefficient array.
4870- i = ( e + 1 ) % LOGBASE;
4871-
4872- if ( e < 0 ) {
4873- i += LOGBASE;
4874- }
4875-
4876- // b is n.length.
4877- if ( i < b ) {
4878-
4879- if (i) {
4880- x['c'].push( +n.slice( 0, i ) );
4881- }
4882-
4883- for ( b -= LOGBASE; i < b; ) {
4884- x['c'].push( +n.slice( i, i += LOGBASE ) );
4885- }
4886-
4887- n = n.slice(i);
4888- i = LOGBASE - n.length;
4889- } else {
4890- i -= b;
4891- }
4892-
4893- for ( ; i--; n += '0' );
4894-
4895- x['c'].push( +n );
4896-
4897- if (external) {
4898-
4899- // Overflow?
4900- if ( x['e'] > Decimal['maxE'] ) {
4901-
4902- // Infinity.
4903- x['c'] = x['e'] = null;
4904-
4905- // Underflow?
4906- } else if ( x['e'] < Decimal['minE'] ) {
4907-
4908- // Zero.
4909- x['c'] = [ x['e'] = 0 ];
4910- }
4911- }
4912- } else {
4913-
4914- // Zero.
4915- x['c'] = [ x['e'] = 0 ];
4916- }
4917-
4918- id = 0;
4919- }
4920- })();
4921-
4922-
4923- /*
4924- * Return a new Decimal whose value is x raised to the power y.
4925- *
4926- * x {number|string|Decimal} The base.
4927- * y {number|string|Decimal} The exponent.
4928- *
4929- */
4930- function pow( x, y ) { return new this(x)['pow'](y) }
4931-
4932-
4933- /*
4934- * Returns a new Decimal with a random value equal to or greater than 0 and less than 1, and
4935- * with dp, or Decimal.precision if dp is omitted, decimal places (or less if trailing
4936- * zeros are produced).
4937- *
4938- * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
4939- *
4940- */
4941- function random(dp) {
4942- var a, n, v,
4943- i = 0,
4944- r = [],
4945- Decimal = this,
4946- rand = new Decimal( Decimal['ONE'] );
4947-
4948- if ( dp == null || !checkArg( rand, dp, 'random' ) ) {
4949- dp = Decimal['precision'];
4950- } else {
4951- dp |= 0;
4952- }
4953-
4954- n = Math.ceil( dp / LOGBASE );
4955-
4956- if ( Decimal['crypto'] ) {
4957-
4958- // Browsers supporting crypto.getRandomValues.
4959- if ( crypto && crypto['getRandomValues'] ) {
4960-
4961- a = crypto['getRandomValues']( new Uint32Array(n) );
4962-
4963- for ( ; i < n; ) {
4964- v = a[i];
4965-
4966- // 0 >= v < 4294967296
4967- // Probability that v >= 4.29e9, is 4967296 / 4294967296 = 0.00116 (1 in 865).
4968- if ( v >= 4.29e9 ) {
4969-
4970- a[i] = crypto['getRandomValues']( new Uint32Array(1) )[0];
4971- } else {
4972-
4973- // 0 <= v <= 4289999999
4974- // 0 <= ( v % 1e7 ) <= 9999999
4975- r[i++] = v % 1e7;
4976- }
4977- }
4978-
4979- // Node.js supporting crypto.randomBytes.
4980- } else if ( crypto && crypto['randomBytes'] ) {
4981-
4982- // buffer
4983- a = crypto['randomBytes']( n *= 4 );
4984-
4985- for ( ; i < n; ) {
4986-
4987- // 0 <= v < 2147483648
4988- v = a[i] + ( a[i + 1] << 8 ) + ( a[i + 2] << 16 ) +
4989- ( ( a[i + 3] & 0x7f ) << 24 );
4990-
4991- // Probability that v >= 2.14e9, is 7483648 / 2147483648 = 0.0035 (1 in 286).
4992- if ( v >= 2.14e9 ) {
4993- crypto['randomBytes'](4).copy( a, i );
4994- } else {
4995-
4996- // 0 <= v <= 4289999999
4997- // 0 <= ( v % 1e7 ) <= 9999999
4998- r.push( v % 1e7 );
4999- i += 4;
5000- }
The diff has been truncated for viewing.

Subscribers

People subscribed via source and target branches