number.js 20 KB

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