sqrt.js 2.0 KB

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