UNPKG

18.8 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.isInteger = isInteger;
7exports.format = format;
8exports.splitNumber = splitNumber;
9exports.toEngineering = toEngineering;
10exports.toFixed = toFixed;
11exports.toExponential = toExponential;
12exports.toPrecision = toPrecision;
13exports.roundDigits = roundDigits;
14exports.digits = digits;
15exports.nearlyEqual = nearlyEqual;
16exports.tanh = exports.sinh = exports.cosh = exports.atanh = exports.asinh = exports.acosh = exports.DBL_EPSILON = exports.expm1 = exports.cbrt = exports.log1p = exports.log10 = exports.log2 = exports.sign = void 0;
17
18var _is = require("./is");
19
20/**
21 * @typedef {{sign: '+' | '-' | '', coefficients: number[], exponent: number}} SplitValue
22 */
23
24/**
25 * Check if a number is integer
26 * @param {number | boolean} value
27 * @return {boolean} isInteger
28 */
29function isInteger(value) {
30 if (typeof value === 'boolean') {
31 return true;
32 }
33
34 return isFinite(value) ? value === Math.round(value) : false; // Note: we use ==, not ===, as we can have Booleans as well
35}
36/**
37 * Calculate the sign of a number
38 * @param {number} x
39 * @returns {number}
40 */
41
42
43var sign = /* #__PURE__ */Math.sign || function (x) {
44 if (x > 0) {
45 return 1;
46 } else if (x < 0) {
47 return -1;
48 } else {
49 return 0;
50 }
51};
52/**
53 * Calculate the base-2 logarithm of a number
54 * @param {number} x
55 * @returns {number}
56 */
57
58
59exports.sign = sign;
60
61var log2 = /* #__PURE__ */Math.log2 || function log2(x) {
62 return Math.log(x) / Math.LN2;
63};
64/**
65 * Calculate the base-10 logarithm of a number
66 * @param {number} x
67 * @returns {number}
68 */
69
70
71exports.log2 = log2;
72
73var log10 = /* #__PURE__ */Math.log10 || function log10(x) {
74 return Math.log(x) / Math.LN10;
75};
76/**
77 * Calculate the natural logarithm of a number + 1
78 * @param {number} x
79 * @returns {number}
80 */
81
82
83exports.log10 = log10;
84
85var log1p = /* #__PURE__ */Math.log1p || function (x) {
86 return Math.log(x + 1);
87};
88/**
89 * Calculate cubic root for a number
90 *
91 * Code from es6-shim.js:
92 * https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js#L1564-L1577
93 *
94 * @param {number} x
95 * @returns {number} Returns the cubic root of x
96 */
97
98
99exports.log1p = log1p;
100
101var cbrt = /* #__PURE__ */Math.cbrt || function cbrt(x) {
102 if (x === 0) {
103 return x;
104 }
105
106 var negate = x < 0;
107 var result;
108
109 if (negate) {
110 x = -x;
111 }
112
113 if (isFinite(x)) {
114 result = Math.exp(Math.log(x) / 3); // from https://en.wikipedia.org/wiki/Cube_root#Numerical_methods
115
116 result = (x / (result * result) + 2 * result) / 3;
117 } else {
118 result = x;
119 }
120
121 return negate ? -result : result;
122};
123/**
124 * Calculates exponentiation minus 1
125 * @param {number} x
126 * @return {number} res
127 */
128
129
130exports.cbrt = cbrt;
131
132var expm1 = /* #__PURE__ */Math.expm1 || function expm1(x) {
133 return x >= 2e-4 || x <= -2e-4 ? Math.exp(x) - 1 : x + x * x / 2 + x * x * x / 6;
134};
135/**
136 * Convert a number to a formatted string representation.
137 *
138 * Syntax:
139 *
140 * format(value)
141 * format(value, options)
142 * format(value, precision)
143 * format(value, fn)
144 *
145 * Where:
146 *
147 * {number} value The value to be formatted
148 * {Object} options An object with formatting options. Available options:
149 * {string} notation
150 * Number notation. Choose from:
151 * 'fixed' Always use regular number notation.
152 * For example '123.40' and '14000000'
153 * 'exponential' Always use exponential notation.
154 * For example '1.234e+2' and '1.4e+7'
155 * 'engineering' Always use engineering notation.
156 * For example '123.4e+0' and '14.0e+6'
157 * 'auto' (default) Regular number notation for numbers
158 * having an absolute value between
159 * `lowerExp` and `upperExp` bounds, and
160 * uses exponential notation elsewhere.
161 * Lower bound is included, upper bound
162 * is excluded.
163 * For example '123.4' and '1.4e7'.
164 * {number} precision A number between 0 and 16 to round
165 * the digits of the number.
166 * In case of notations 'exponential',
167 * 'engineering', and 'auto',
168 * `precision` defines the total
169 * number of significant digits returned.
170 * In case of notation 'fixed',
171 * `precision` defines the number of
172 * significant digits after the decimal
173 * point.
174 * `precision` is undefined by default,
175 * not rounding any digits.
176 * {number} lowerExp Exponent determining the lower boundary
177 * for formatting a value with an exponent
178 * when `notation='auto`.
179 * Default value is `-3`.
180 * {number} upperExp Exponent determining the upper boundary
181 * for formatting a value with an exponent
182 * when `notation='auto`.
183 * Default value is `5`.
184 * {Function} fn A custom formatting function. Can be used to override the
185 * built-in notations. Function `fn` is called with `value` as
186 * parameter and must return a string. Is useful for example to
187 * format all values inside a matrix in a particular way.
188 *
189 * Examples:
190 *
191 * format(6.4) // '6.4'
192 * format(1240000) // '1.24e6'
193 * format(1/3) // '0.3333333333333333'
194 * format(1/3, 3) // '0.333'
195 * format(21385, 2) // '21000'
196 * format(12.071, {notation: 'fixed'}) // '12'
197 * format(2.3, {notation: 'fixed', precision: 2}) // '2.30'
198 * format(52.8, {notation: 'exponential'}) // '5.28e+1'
199 * format(12345678, {notation: 'engineering'}) // '12.345678e+6'
200 *
201 * @param {number} value
202 * @param {Object | Function | number} [options]
203 * @return {string} str The formatted value
204 */
205
206
207exports.expm1 = expm1;
208
209function format(value, options) {
210 if (typeof options === 'function') {
211 // handle format(value, fn)
212 return options(value);
213 } // handle special cases
214
215
216 if (value === Infinity) {
217 return 'Infinity';
218 } else if (value === -Infinity) {
219 return '-Infinity';
220 } else if (isNaN(value)) {
221 return 'NaN';
222 } // default values for options
223
224
225 var notation = 'auto';
226 var precision;
227
228 if (options) {
229 // determine notation from options
230 if (options.notation) {
231 notation = options.notation;
232 } // determine precision from options
233
234
235 if ((0, _is.isNumber)(options)) {
236 precision = options;
237 } else if ((0, _is.isNumber)(options.precision)) {
238 precision = options.precision;
239 }
240 } // handle the various notations
241
242
243 switch (notation) {
244 case 'fixed':
245 return toFixed(value, precision);
246
247 case 'exponential':
248 return toExponential(value, precision);
249
250 case 'engineering':
251 return toEngineering(value, precision);
252
253 case 'auto':
254 // remove trailing zeros after the decimal point
255 return toPrecision(value, precision, options && options).replace(/((\.\d*?)(0+))($|e)/, function () {
256 var digits = arguments[2];
257 var e = arguments[4];
258 return digits !== '.' ? digits + e : e;
259 });
260
261 default:
262 throw new Error('Unknown notation "' + notation + '". ' + 'Choose "auto", "exponential", or "fixed".');
263 }
264}
265/**
266 * Split a number into sign, coefficients, and exponent
267 * @param {number | string} value
268 * @return {SplitValue}
269 * Returns an object containing sign, coefficients, and exponent
270 */
271
272
273function splitNumber(value) {
274 // parse the input value
275 var match = String(value).toLowerCase().match(/^0*?(-?)(\d+\.?\d*)(e([+-]?\d+))?$/);
276
277 if (!match) {
278 throw new SyntaxError('Invalid number ' + value);
279 }
280
281 var sign = match[1];
282 var digits = match[2];
283 var exponent = parseFloat(match[4] || '0');
284 var dot = digits.indexOf('.');
285 exponent += dot !== -1 ? dot - 1 : digits.length - 1;
286 var coefficients = digits.replace('.', '') // remove the dot (must be removed before removing leading zeros)
287 .replace(/^0*/, function (zeros) {
288 // remove leading zeros, add their count to the exponent
289 exponent -= zeros.length;
290 return '';
291 }).replace(/0*$/, '') // remove trailing zeros
292 .split('').map(function (d) {
293 return parseInt(d);
294 });
295
296 if (coefficients.length === 0) {
297 coefficients.push(0);
298 exponent++;
299 }
300
301 return {
302 sign: sign,
303 coefficients: coefficients,
304 exponent: exponent
305 };
306}
307/**
308 * Format a number in engineering notation. Like '1.23e+6', '2.3e+0', '3.500e-3'
309 * @param {number | string} value
310 * @param {number} [precision] Optional number of significant figures to return.
311 */
312
313
314function toEngineering(value, precision) {
315 if (isNaN(value) || !isFinite(value)) {
316 return String(value);
317 }
318
319 var split = splitNumber(value);
320 var rounded = roundDigits(split, precision);
321 var e = rounded.exponent;
322 var c = rounded.coefficients; // find nearest lower multiple of 3 for exponent
323
324 var newExp = e % 3 === 0 ? e : e < 0 ? e - 3 - e % 3 : e - e % 3;
325
326 if ((0, _is.isNumber)(precision)) {
327 // add zeroes to give correct sig figs
328 while (precision > c.length || e - newExp + 1 > c.length) {
329 c.push(0);
330 }
331 } else {
332 // concatenate coefficients with necessary zeros
333 // add zeros if necessary (for example: 1e+8 -> 100e+6)
334 var missingZeros = Math.abs(e - newExp) - (c.length - 1);
335
336 for (var i = 0; i < missingZeros; i++) {
337 c.push(0);
338 }
339 } // find difference in exponents
340
341
342 var expDiff = Math.abs(e - newExp);
343 var decimalIdx = 1; // push decimal index over by expDiff times
344
345 while (expDiff > 0) {
346 decimalIdx++;
347 expDiff--;
348 } // if all coefficient values are zero after the decimal point and precision is unset, don't add a decimal value.
349 // otherwise concat with the rest of the coefficients
350
351
352 var decimals = c.slice(decimalIdx).join('');
353 var decimalVal = (0, _is.isNumber)(precision) && decimals.length || decimals.match(/[1-9]/) ? '.' + decimals : '';
354 var str = c.slice(0, decimalIdx).join('') + decimalVal + 'e' + (e >= 0 ? '+' : '') + newExp.toString();
355 return rounded.sign + str;
356}
357/**
358 * Format a number with fixed notation.
359 * @param {number | string} value
360 * @param {number} [precision=undefined] Optional number of decimals after the
361 * decimal point. null by default.
362 */
363
364
365function toFixed(value, precision) {
366 if (isNaN(value) || !isFinite(value)) {
367 return String(value);
368 }
369
370 var splitValue = splitNumber(value);
371 var rounded = typeof precision === 'number' ? roundDigits(splitValue, splitValue.exponent + 1 + precision) : splitValue;
372 var c = rounded.coefficients;
373 var p = rounded.exponent + 1; // exponent may have changed
374 // append zeros if needed
375
376 var pp = p + (precision || 0);
377
378 if (c.length < pp) {
379 c = c.concat(zeros(pp - c.length));
380 } // prepend zeros if needed
381
382
383 if (p < 0) {
384 c = zeros(-p + 1).concat(c);
385 p = 1;
386 } // insert a dot if needed
387
388
389 if (p < c.length) {
390 c.splice(p, 0, p === 0 ? '0.' : '.');
391 }
392
393 return rounded.sign + c.join('');
394}
395/**
396 * Format a number in exponential notation. Like '1.23e+5', '2.3e+0', '3.500e-3'
397 * @param {number | string} value
398 * @param {number} [precision] Number of digits in formatted output.
399 * If not provided, the maximum available digits
400 * is used.
401 */
402
403
404function toExponential(value, precision) {
405 if (isNaN(value) || !isFinite(value)) {
406 return String(value);
407 } // round if needed, else create a clone
408
409
410 var split = splitNumber(value);
411 var rounded = precision ? roundDigits(split, precision) : split;
412 var c = rounded.coefficients;
413 var e = rounded.exponent; // append zeros if needed
414
415 if (c.length < precision) {
416 c = c.concat(zeros(precision - c.length));
417 } // format as `C.CCCe+EEE` or `C.CCCe-EEE`
418
419
420 var first = c.shift();
421 return rounded.sign + first + (c.length > 0 ? '.' + c.join('') : '') + 'e' + (e >= 0 ? '+' : '') + e;
422}
423/**
424 * Format a number with a certain precision
425 * @param {number | string} value
426 * @param {number} [precision=undefined] Optional number of digits.
427 * @param {{lowerExp: number | undefined, upperExp: number | undefined}} [options]
428 * By default:
429 * lowerExp = -3 (incl)
430 * upper = +5 (excl)
431 * @return {string}
432 */
433
434
435function toPrecision(value, precision, options) {
436 if (isNaN(value) || !isFinite(value)) {
437 return String(value);
438 } // determine lower and upper bound for exponential notation.
439
440
441 var lowerExp = options && options.lowerExp !== undefined ? options.lowerExp : -3;
442 var upperExp = options && options.upperExp !== undefined ? options.upperExp : 5;
443 var split = splitNumber(value);
444 var rounded = precision ? roundDigits(split, precision) : split;
445
446 if (rounded.exponent < lowerExp || rounded.exponent >= upperExp) {
447 // exponential notation
448 return toExponential(value, precision);
449 } else {
450 var c = rounded.coefficients;
451 var e = rounded.exponent; // append trailing zeros
452
453 if (c.length < precision) {
454 c = c.concat(zeros(precision - c.length));
455 } // append trailing zeros
456 // TODO: simplify the next statement
457
458
459 c = c.concat(zeros(e - c.length + 1 + (c.length < precision ? precision - c.length : 0))); // prepend zeros
460
461 c = zeros(-e).concat(c);
462 var dot = e > 0 ? e : 0;
463
464 if (dot < c.length - 1) {
465 c.splice(dot + 1, 0, '.');
466 }
467
468 return rounded.sign + c.join('');
469 }
470}
471/**
472 * Round the number of digits of a number *
473 * @param {SplitValue} split A value split with .splitNumber(value)
474 * @param {number} precision A positive integer
475 * @return {SplitValue}
476 * Returns an object containing sign, coefficients, and exponent
477 * with rounded digits
478 */
479
480
481function roundDigits(split, precision) {
482 // create a clone
483 var rounded = {
484 sign: split.sign,
485 coefficients: split.coefficients,
486 exponent: split.exponent
487 };
488 var c = rounded.coefficients; // prepend zeros if needed
489
490 while (precision <= 0) {
491 c.unshift(0);
492 rounded.exponent++;
493 precision++;
494 }
495
496 if (c.length > precision) {
497 var removed = c.splice(precision, c.length - precision);
498
499 if (removed[0] >= 5) {
500 var i = precision - 1;
501 c[i]++;
502
503 while (c[i] === 10) {
504 c.pop();
505
506 if (i === 0) {
507 c.unshift(0);
508 rounded.exponent++;
509 i++;
510 }
511
512 i--;
513 c[i]++;
514 }
515 }
516 }
517
518 return rounded;
519}
520/**
521 * Create an array filled with zeros.
522 * @param {number} length
523 * @return {Array}
524 */
525
526
527function zeros(length) {
528 var arr = [];
529
530 for (var i = 0; i < length; i++) {
531 arr.push(0);
532 }
533
534 return arr;
535}
536/**
537 * Count the number of significant digits of a number.
538 *
539 * For example:
540 * 2.34 returns 3
541 * 0.0034 returns 2
542 * 120.5e+30 returns 4
543 *
544 * @param {number} value
545 * @return {number} digits Number of significant digits
546 */
547
548
549function digits(value) {
550 return value.toExponential().replace(/e.*$/, '') // remove exponential notation
551 .replace(/^0\.?0*|\./, '') // remove decimal point and leading zeros
552 .length;
553}
554/**
555 * Minimum number added to one that makes the result different than one
556 */
557
558
559var DBL_EPSILON = Number.EPSILON || 2.2204460492503130808472633361816E-16;
560/**
561 * Compares two floating point numbers.
562 * @param {number} x First value to compare
563 * @param {number} y Second value to compare
564 * @param {number} [epsilon] The maximum relative difference between x and y
565 * If epsilon is undefined or null, the function will
566 * test whether x and y are exactly equal.
567 * @return {boolean} whether the two numbers are nearly equal
568*/
569
570exports.DBL_EPSILON = DBL_EPSILON;
571
572function nearlyEqual(x, y, epsilon) {
573 // if epsilon is null or undefined, test whether x and y are exactly equal
574 if (epsilon === null || epsilon === undefined) {
575 return x === y;
576 }
577
578 if (x === y) {
579 return true;
580 } // NaN
581
582
583 if (isNaN(x) || isNaN(y)) {
584 return false;
585 } // at this point x and y should be finite
586
587
588 if (isFinite(x) && isFinite(y)) {
589 // check numbers are very close, needed when comparing numbers near zero
590 var diff = Math.abs(x - y);
591
592 if (diff < DBL_EPSILON) {
593 return true;
594 } else {
595 // use relative error
596 return diff <= Math.max(Math.abs(x), Math.abs(y)) * epsilon;
597 }
598 } // Infinite and Number or negative Infinite and positive Infinite cases
599
600
601 return false;
602}
603/**
604 * Calculate the hyperbolic arccos of a number
605 * @param {number} x
606 * @return {number}
607 */
608
609
610var acosh = Math.acosh || function (x) {
611 return Math.log(Math.sqrt(x * x - 1) + x);
612};
613
614exports.acosh = acosh;
615
616var asinh = Math.asinh || function (x) {
617 return Math.log(Math.sqrt(x * x + 1) + x);
618};
619/**
620 * Calculate the hyperbolic arctangent of a number
621 * @param {number} x
622 * @return {number}
623 */
624
625
626exports.asinh = asinh;
627
628var atanh = Math.atanh || function (x) {
629 return Math.log((1 + x) / (1 - x)) / 2;
630};
631/**
632 * Calculate the hyperbolic cosine of a number
633 * @param {number} x
634 * @returns {number}
635 */
636
637
638exports.atanh = atanh;
639
640var cosh = Math.cosh || function (x) {
641 return (Math.exp(x) + Math.exp(-x)) / 2;
642};
643/**
644 * Calculate the hyperbolic sine of a number
645 * @param {number} x
646 * @returns {number}
647 */
648
649
650exports.cosh = cosh;
651
652var sinh = Math.sinh || function (x) {
653 return (Math.exp(x) - Math.exp(-x)) / 2;
654};
655/**
656 * Calculate the hyperbolic tangent of a number
657 * @param {number} x
658 * @returns {number}
659 */
660
661
662exports.sinh = sinh;
663
664var tanh = Math.tanh || function (x) {
665 var e = Math.exp(2 * x);
666 return (e - 1) / (e + 1);
667};
668
669exports.tanh = tanh;
\No newline at end of file