UNPKG

2.57 kBJavaScriptView Raw
1import { factory } from '../../utils/factory.js';
2import { flatten } from '../../utils/array.js';
3var name = 'hypot';
4var dependencies = ['typed', 'abs', 'addScalar', 'divideScalar', 'multiplyScalar', 'sqrt', 'smaller', 'isPositive'];
5export var createHypot = /* #__PURE__ */factory(name, dependencies, (_ref) => {
6 var {
7 typed,
8 abs,
9 addScalar,
10 divideScalar,
11 multiplyScalar,
12 sqrt,
13 smaller,
14 isPositive
15 } = _ref;
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 return typed(name, {
46 '... number | BigNumber': _hypot,
47 Array: function Array(x) {
48 return this.apply(this, flatten(x));
49 },
50 Matrix: function Matrix(x) {
51 return this.apply(this, 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});
\No newline at end of file