UNPKG

2.72 kBJavaScriptView Raw
1import { factory } from '../../utils/factory';
2import { flatten } from '../../utils/array';
3var name = 'hypot';
4var dependencies = ['typed', 'abs', 'addScalar', 'divideScalar', 'multiplyScalar', 'sqrt', 'smaller', 'isPositive'];
5export var createHypot =
6/* #__PURE__ */
7factory(name, dependencies, function (_ref) {
8 var typed = _ref.typed,
9 abs = _ref.abs,
10 addScalar = _ref.addScalar,
11 divideScalar = _ref.divideScalar,
12 multiplyScalar = _ref.multiplyScalar,
13 sqrt = _ref.sqrt,
14 smaller = _ref.smaller,
15 isPositive = _ref.isPositive;
16
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 var hypot = typed(name, {
46 '... number | BigNumber': _hypot,
47 Array: function Array(x) {
48 return hypot.apply(hypot, flatten(x));
49 },
50 Matrix: function Matrix(x) {
51 return hypot.apply(hypot, flatten(x.toArray()));
52 }
53 });
54 /**
55 * Calculate the hypotenusa for an Array with values
56 * @param {Array.<number | BigNumber>} args
57 * @return {number | BigNumber} Returns the result
58 * @private
59 */
60
61 function _hypot(args) {
62 // code based on `hypot` from es6-shim:
63 // https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js#L1619-L1633
64 var result = 0;
65 var largest = 0;
66
67 for (var i = 0; i < args.length; i++) {
68 var value = abs(args[i]);
69
70 if (smaller(largest, value)) {
71 result = multiplyScalar(result, multiplyScalar(divideScalar(largest, value), divideScalar(largest, value)));
72 result = addScalar(result, 1);
73 largest = value;
74 } else {
75 result = addScalar(result, isPositive(value) ? multiplyScalar(divideScalar(value, largest), divideScalar(value, largest)) : value);
76 }
77 }
78
79 return multiplyScalar(largest, sqrt(result));
80 }
81
82 return hypot;
83});
\No newline at end of file