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