sqrt.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { factory } from '../../utils/factory.js';
  2. var name = 'sqrt';
  3. var dependencies = ['config', 'typed', 'Complex'];
  4. export var createSqrt = /* #__PURE__ */factory(name, dependencies, _ref => {
  5. var {
  6. config,
  7. typed,
  8. Complex
  9. } = _ref;
  10. /**
  11. * Calculate the square root of a value.
  12. *
  13. * For matrices, if you want the matrix square root of a square matrix,
  14. * use the `sqrtm` function. If you wish to apply `sqrt` elementwise to
  15. * a matrix M, use `math.map(M, math.sqrt)`.
  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 | Unit} x
  32. * Value for which to calculate the square root.
  33. * @return {number | BigNumber | Complex | 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. Unit: function Unit(x) {
  50. // Someday will work for complex units when they are implemented
  51. return x.pow(0.5);
  52. }
  53. });
  54. /**
  55. * Calculate sqrt for a number
  56. * @param {number} x
  57. * @returns {number | Complex} Returns the square root of x
  58. * @private
  59. */
  60. function _sqrtNumber(x) {
  61. if (isNaN(x)) {
  62. return NaN;
  63. } else if (x >= 0 || config.predictable) {
  64. return Math.sqrt(x);
  65. } else {
  66. return new Complex(x, 0).sqrt();
  67. }
  68. }
  69. });