variance.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.createVariance = void 0;
  6. var _collection = require("../../utils/collection.js");
  7. var _is = require("../../utils/is.js");
  8. var _factory = require("../../utils/factory.js");
  9. var _improveErrorMessage = require("./utils/improveErrorMessage.js");
  10. var DEFAULT_NORMALIZATION = 'unbiased';
  11. var name = 'variance';
  12. var dependencies = ['typed', 'add', 'subtract', 'multiply', 'divide', 'apply', 'isNaN'];
  13. var createVariance = /* #__PURE__ */(0, _factory.factory)(name, dependencies, function (_ref) {
  14. var typed = _ref.typed,
  15. add = _ref.add,
  16. subtract = _ref.subtract,
  17. multiply = _ref.multiply,
  18. divide = _ref.divide,
  19. apply = _ref.apply,
  20. isNaN = _ref.isNaN;
  21. /**
  22. * Compute the variance of a matrix or a list with values.
  23. * In case of a multidimensional array or matrix, the variance over all
  24. * elements will be calculated.
  25. *
  26. * Additionally, it is possible to compute the variance along the rows
  27. * or columns of a matrix by specifying the dimension as the second argument.
  28. *
  29. * Optionally, the type of normalization can be specified as the final
  30. * parameter. The parameter `normalization` can be one of the following values:
  31. *
  32. * - 'unbiased' (default) The sum of squared errors is divided by (n - 1)
  33. * - 'uncorrected' The sum of squared errors is divided by n
  34. * - 'biased' The sum of squared errors is divided by (n + 1)
  35. *
  36. *
  37. * Note that older browser may not like the variable name `var`. In that
  38. * case, the function can be called as `math['var'](...)` instead of
  39. * `math.var(...)`.
  40. *
  41. * Syntax:
  42. *
  43. * math.variance(a, b, c, ...)
  44. * math.variance(A)
  45. * math.variance(A, normalization)
  46. * math.variance(A, dimension)
  47. * math.variance(A, dimension, normalization)
  48. *
  49. * Examples:
  50. *
  51. * math.variance(2, 4, 6) // returns 4
  52. * math.variance([2, 4, 6, 8]) // returns 6.666666666666667
  53. * math.variance([2, 4, 6, 8], 'uncorrected') // returns 5
  54. * math.variance([2, 4, 6, 8], 'biased') // returns 4
  55. *
  56. * math.variance([[1, 2, 3], [4, 5, 6]]) // returns 3.5
  57. * math.variance([[1, 2, 3], [4, 6, 8]], 0) // returns [4.5, 8, 12.5]
  58. * math.variance([[1, 2, 3], [4, 6, 8]], 1) // returns [1, 4]
  59. * math.variance([[1, 2, 3], [4, 6, 8]], 1, 'biased') // returns [0.5, 2]
  60. *
  61. * See also:
  62. *
  63. * mean, median, max, min, prod, std, sum
  64. *
  65. * @param {Array | Matrix} array
  66. * A single matrix or or multiple scalar values
  67. * @param {string} [normalization='unbiased']
  68. * Determines how to normalize the variance.
  69. * Choose 'unbiased' (default), 'uncorrected', or 'biased'.
  70. * @param dimension {number | BigNumber}
  71. * Determines the axis to compute the variance for a matrix
  72. * @return {*} The variance
  73. */
  74. return typed(name, {
  75. // variance([a, b, c, d, ...])
  76. 'Array | Matrix': function ArrayMatrix(array) {
  77. return _var(array, DEFAULT_NORMALIZATION);
  78. },
  79. // variance([a, b, c, d, ...], normalization)
  80. 'Array | Matrix, string': _var,
  81. // variance([a, b, c, c, ...], dim)
  82. 'Array | Matrix, number | BigNumber': function ArrayMatrixNumberBigNumber(array, dim) {
  83. return _varDim(array, dim, DEFAULT_NORMALIZATION);
  84. },
  85. // variance([a, b, c, c, ...], dim, normalization)
  86. 'Array | Matrix, number | BigNumber, string': _varDim,
  87. // variance(a, b, c, d, ...)
  88. '...': function _(args) {
  89. return _var(args, DEFAULT_NORMALIZATION);
  90. }
  91. });
  92. /**
  93. * Recursively calculate the variance of an n-dimensional array
  94. * @param {Array} array
  95. * @param {string} normalization
  96. * Determines how to normalize the variance:
  97. * - 'unbiased' The sum of squared errors is divided by (n - 1)
  98. * - 'uncorrected' The sum of squared errors is divided by n
  99. * - 'biased' The sum of squared errors is divided by (n + 1)
  100. * @return {number | BigNumber} variance
  101. * @private
  102. */
  103. function _var(array, normalization) {
  104. var sum;
  105. var num = 0;
  106. if (array.length === 0) {
  107. throw new SyntaxError('Function variance requires one or more parameters (0 provided)');
  108. }
  109. // calculate the mean and number of elements
  110. (0, _collection.deepForEach)(array, function (value) {
  111. try {
  112. sum = sum === undefined ? value : add(sum, value);
  113. num++;
  114. } catch (err) {
  115. throw (0, _improveErrorMessage.improveErrorMessage)(err, 'variance', value);
  116. }
  117. });
  118. if (num === 0) throw new Error('Cannot calculate variance of an empty array');
  119. var mean = divide(sum, num);
  120. // calculate the variance
  121. sum = undefined;
  122. (0, _collection.deepForEach)(array, function (value) {
  123. var diff = subtract(value, mean);
  124. sum = sum === undefined ? multiply(diff, diff) : add(sum, multiply(diff, diff));
  125. });
  126. if (isNaN(sum)) {
  127. return sum;
  128. }
  129. switch (normalization) {
  130. case 'uncorrected':
  131. return divide(sum, num);
  132. case 'biased':
  133. return divide(sum, num + 1);
  134. case 'unbiased':
  135. {
  136. var zero = (0, _is.isBigNumber)(sum) ? sum.mul(0) : 0;
  137. return num === 1 ? zero : divide(sum, num - 1);
  138. }
  139. default:
  140. throw new Error('Unknown normalization "' + normalization + '". ' + 'Choose "unbiased" (default), "uncorrected", or "biased".');
  141. }
  142. }
  143. function _varDim(array, dim, normalization) {
  144. try {
  145. if (array.length === 0) {
  146. throw new SyntaxError('Function variance requires one or more parameters (0 provided)');
  147. }
  148. return apply(array, dim, function (x) {
  149. return _var(x, normalization);
  150. });
  151. } catch (err) {
  152. throw (0, _improveErrorMessage.improveErrorMessage)(err, 'variance');
  153. }
  154. }
  155. });
  156. exports.createVariance = createVariance;