UNPKG

1.95 kBJavaScriptView Raw
1import { factory } from '../../utils/factory'
2import { deepMap } from '../../utils/collection'
3
4const name = 'sqrt'
5const dependencies = ['config', 'typed', 'Complex']
6
7export const createSqrt = /* #__PURE__ */ factory(name, dependencies, ({ config, typed, Complex }) => {
8 /**
9 * Calculate the square root of a value.
10 *
11 * For matrices, the function is evaluated element wise.
12 *
13 * Syntax:
14 *
15 * math.sqrt(x)
16 *
17 * Examples:
18 *
19 * math.sqrt(25) // returns 5
20 * math.square(5) // returns 25
21 * math.sqrt(-4) // returns Complex 2i
22 *
23 * See also:
24 *
25 * square, multiply, cube, cbrt, sqrtm
26 *
27 * @param {number | BigNumber | Complex | Array | Matrix | Unit} x
28 * Value for which to calculate the square root.
29 * @return {number | BigNumber | Complex | Array | Matrix | Unit}
30 * Returns the square root of `x`
31 */
32 const sqrt = typed('sqrt', {
33 number: _sqrtNumber,
34
35 Complex: function (x) {
36 return x.sqrt()
37 },
38
39 BigNumber: function (x) {
40 if (!x.isNegative() || config.predictable) {
41 return x.sqrt()
42 } else {
43 // negative value -> downgrade to number to do complex value computation
44 return _sqrtNumber(x.toNumber())
45 }
46 },
47
48 'Array | Matrix': function (x) {
49 // deep map collection, skip zeros since sqrt(0) = 0
50 return deepMap(x, sqrt, true)
51 },
52
53 Unit: function (x) {
54 // Someday will work for complex units when they are implemented
55 return x.pow(0.5)
56 }
57
58 })
59
60 /**
61 * Calculate sqrt for a number
62 * @param {number} x
63 * @returns {number | Complex} Returns the square root of x
64 * @private
65 */
66 function _sqrtNumber (x) {
67 if (isNaN(x)) {
68 return NaN
69 } else if (x >= 0 || config.predictable) {
70 return Math.sqrt(x)
71 } else {
72 return new Complex(x, 0).sqrt()
73 }
74 }
75
76 return sqrt
77})