prod.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { deepForEach } from '../../utils/collection.js';
  2. import { factory } from '../../utils/factory.js';
  3. import { improveErrorMessage } from './utils/improveErrorMessage.js';
  4. var name = 'prod';
  5. var dependencies = ['typed', 'config', 'multiplyScalar', 'numeric'];
  6. export var createProd = /* #__PURE__ */factory(name, dependencies, _ref => {
  7. var {
  8. typed,
  9. config,
  10. multiplyScalar,
  11. numeric
  12. } = _ref;
  13. /**
  14. * Compute the product of a matrix or a list with values.
  15. * In case of a multidimensional array or matrix, the sum of all
  16. * elements will be calculated.
  17. *
  18. * Syntax:
  19. *
  20. * math.prod(a, b, c, ...)
  21. * math.prod(A)
  22. *
  23. * Examples:
  24. *
  25. * math.multiply(2, 3) // returns 6
  26. * math.prod(2, 3) // returns 6
  27. * math.prod(2, 3, 4) // returns 24
  28. * math.prod([2, 3, 4]) // returns 24
  29. * math.prod([[2, 5], [4, 3]]) // returns 120
  30. *
  31. * See also:
  32. *
  33. * mean, median, min, max, sum, std, variance
  34. *
  35. * @param {... *} args A single matrix or or multiple scalar values
  36. * @return {*} The product of all values
  37. */
  38. return typed(name, {
  39. // prod([a, b, c, d, ...])
  40. 'Array | Matrix': _prod,
  41. // prod([a, b, c, d, ...], dim)
  42. 'Array | Matrix, number | BigNumber': function ArrayMatrixNumberBigNumber(array, dim) {
  43. // TODO: implement prod(A, dim)
  44. throw new Error('prod(A, dim) is not yet supported');
  45. // return reduce(arguments[0], arguments[1], math.prod)
  46. },
  47. // prod(a, b, c, d, ...)
  48. '...': function _(args) {
  49. return _prod(args);
  50. }
  51. });
  52. /**
  53. * Recursively calculate the product of an n-dimensional array
  54. * @param {Array} array
  55. * @return {number} prod
  56. * @private
  57. */
  58. function _prod(array) {
  59. var prod;
  60. deepForEach(array, function (value) {
  61. try {
  62. prod = prod === undefined ? value : multiplyScalar(prod, value);
  63. } catch (err) {
  64. throw improveErrorMessage(err, 'prod', value);
  65. }
  66. });
  67. // make sure returning numeric value: parse a string into a numeric value
  68. if (typeof prod === 'string') {
  69. prod = numeric(prod, config.number);
  70. }
  71. if (prod === undefined) {
  72. throw new Error('Cannot calculate prod of an empty array');
  73. }
  74. return prod;
  75. }
  76. });