UNPKG

2.9 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.createHypot = void 0;
7
8var _factory = require("../../utils/factory");
9
10var _array = require("../../utils/array");
11
12var name = 'hypot';
13var dependencies = ['typed', 'abs', 'addScalar', 'divideScalar', 'multiplyScalar', 'sqrt', 'smaller', 'isPositive'];
14var createHypot = /* #__PURE__ */(0, _factory.factory)(name, dependencies, function (_ref) {
15 var typed = _ref.typed,
16 abs = _ref.abs,
17 addScalar = _ref.addScalar,
18 divideScalar = _ref.divideScalar,
19 multiplyScalar = _ref.multiplyScalar,
20 sqrt = _ref.sqrt,
21 smaller = _ref.smaller,
22 isPositive = _ref.isPositive;
23
24 /**
25 * Calculate the hypotenusa of a list with values. The hypotenusa is defined as:
26 *
27 * hypot(a, b, c, ...) = sqrt(a^2 + b^2 + c^2 + ...)
28 *
29 * For matrix input, the hypotenusa is calculated for all values in the matrix.
30 *
31 * Syntax:
32 *
33 * math.hypot(a, b, ...)
34 * math.hypot([a, b, c, ...])
35 *
36 * Examples:
37 *
38 * math.hypot(3, 4) // 5
39 * math.hypot(3, 4, 5) // 7.0710678118654755
40 * math.hypot([3, 4, 5]) // 7.0710678118654755
41 * math.hypot(-2) // 2
42 *
43 * See also:
44 *
45 * abs, norm
46 *
47 * @param {... number | BigNumber | Array | Matrix} args A list with numeric values or an Array or Matrix.
48 * Matrix and Array input is flattened and returns a
49 * single number for the whole matrix.
50 * @return {number | BigNumber} Returns the hypothenusa of the input values.
51 */
52 var hypot = typed(name, {
53 '... number | BigNumber': _hypot,
54 Array: function Array(x) {
55 return hypot.apply(hypot, (0, _array.flatten)(x));
56 },
57 Matrix: function Matrix(x) {
58 return hypot.apply(hypot, (0, _array.flatten)(x.toArray()));
59 }
60 });
61 /**
62 * Calculate the hypotenusa for an Array with values
63 * @param {Array.<number | BigNumber>} args
64 * @return {number | BigNumber} Returns the result
65 * @private
66 */
67
68 function _hypot(args) {
69 // code based on `hypot` from es6-shim:
70 // https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js#L1619-L1633
71 var result = 0;
72 var largest = 0;
73
74 for (var i = 0; i < args.length; i++) {
75 var value = abs(args[i]);
76
77 if (smaller(largest, value)) {
78 result = multiplyScalar(result, multiplyScalar(divideScalar(largest, value), divideScalar(largest, value)));
79 result = addScalar(result, 1);
80 largest = value;
81 } else {
82 result = addScalar(result, isPositive(value) ? multiplyScalar(divideScalar(value, largest), divideScalar(value, largest)) : value);
83 }
84 }
85
86 return multiplyScalar(largest, sqrt(result));
87 }
88
89 return hypot;
90});
91exports.createHypot = createHypot;
\No newline at end of file