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