hypot.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { factory } from '../../utils/factory.js';
  2. import { flatten } from '../../utils/array.js';
  3. import { isComplex } from '../../utils/is.js';
  4. var name = 'hypot';
  5. var dependencies = ['typed', 'abs', 'addScalar', 'divideScalar', 'multiplyScalar', 'sqrt', 'smaller', 'isPositive'];
  6. export var createHypot = /* #__PURE__ */factory(name, dependencies, _ref => {
  7. var {
  8. typed,
  9. abs,
  10. addScalar,
  11. divideScalar,
  12. multiplyScalar,
  13. sqrt,
  14. smaller,
  15. isPositive
  16. } = _ref;
  17. /**
  18. * Calculate the hypotenusa of a list with values. The hypotenusa is defined as:
  19. *
  20. * hypot(a, b, c, ...) = sqrt(a^2 + b^2 + c^2 + ...)
  21. *
  22. * For matrix input, the hypotenusa is calculated for all values in the matrix.
  23. *
  24. * Syntax:
  25. *
  26. * math.hypot(a, b, ...)
  27. * math.hypot([a, b, c, ...])
  28. *
  29. * Examples:
  30. *
  31. * math.hypot(3, 4) // 5
  32. * math.hypot(3, 4, 5) // 7.0710678118654755
  33. * math.hypot([3, 4, 5]) // 7.0710678118654755
  34. * math.hypot(-2) // 2
  35. *
  36. * See also:
  37. *
  38. * abs, norm
  39. *
  40. * @param {... number | BigNumber | Array | Matrix} args A list with numeric values or an Array or Matrix.
  41. * Matrix and Array input is flattened and returns a
  42. * single number for the whole matrix.
  43. * @return {number | BigNumber} Returns the hypothenusa of the input values.
  44. */
  45. return typed(name, {
  46. '... number | BigNumber': _hypot,
  47. Array: _hypot,
  48. Matrix: M => _hypot(flatten(M.toArray()))
  49. });
  50. /**
  51. * Calculate the hypotenusa for an Array with values
  52. * @param {Array.<number | BigNumber>} args
  53. * @return {number | BigNumber} Returns the result
  54. * @private
  55. */
  56. function _hypot(args) {
  57. // code based on `hypot` from es6-shim:
  58. // https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js#L1619-L1633
  59. var result = 0;
  60. var largest = 0;
  61. for (var i = 0; i < args.length; i++) {
  62. if (isComplex(args[i])) {
  63. throw new TypeError('Unexpected type of argument to hypot');
  64. }
  65. var value = abs(args[i]);
  66. if (smaller(largest, value)) {
  67. result = multiplyScalar(result, multiplyScalar(divideScalar(largest, value), divideScalar(largest, value)));
  68. result = addScalar(result, 1);
  69. largest = value;
  70. } else {
  71. result = addScalar(result, isPositive(value) ? multiplyScalar(divideScalar(value, largest), divideScalar(value, largest)) : value);
  72. }
  73. }
  74. return multiplyScalar(largest, sqrt(result));
  75. }
  76. });