UNPKG

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