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