UNPKG

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