sign.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { factory } from '../../utils/factory.js';
  2. import { deepMap } from '../../utils/collection.js';
  3. import { signNumber } from '../../plain/number/index.js';
  4. var name = 'sign';
  5. var dependencies = ['typed', 'BigNumber', 'Fraction', 'complex'];
  6. export var createSign = /* #__PURE__ */factory(name, dependencies, _ref => {
  7. var {
  8. typed,
  9. BigNumber: _BigNumber,
  10. complex,
  11. Fraction: _Fraction
  12. } = _ref;
  13. /**
  14. * Compute the sign of a value. The sign of a value x is:
  15. *
  16. * - 1 when x > 0
  17. * - -1 when x < 0
  18. * - 0 when x == 0
  19. *
  20. * For matrices, the function is evaluated element wise.
  21. *
  22. * Syntax:
  23. *
  24. * math.sign(x)
  25. *
  26. * Examples:
  27. *
  28. * math.sign(3.5) // returns 1
  29. * math.sign(-4.2) // returns -1
  30. * math.sign(0) // returns 0
  31. *
  32. * math.sign([3, 5, -2, 0, 2]) // returns [1, 1, -1, 0, 1]
  33. *
  34. * See also:
  35. *
  36. * abs
  37. *
  38. * @param {number | BigNumber | Fraction | Complex | Array | Matrix | Unit} x
  39. * The number for which to determine the sign
  40. * @return {number | BigNumber | Fraction | Complex | Array | Matrix | Unit}e
  41. * The sign of `x`
  42. */
  43. return typed(name, {
  44. number: signNumber,
  45. Complex: function Complex(x) {
  46. return x.im === 0 ? complex(signNumber(x.re)) : x.sign();
  47. },
  48. BigNumber: function BigNumber(x) {
  49. return new _BigNumber(x.cmp(0));
  50. },
  51. Fraction: function Fraction(x) {
  52. return new _Fraction(x.s, 1);
  53. },
  54. // deep map collection, skip zeros since sign(0) = 0
  55. 'Array | Matrix': typed.referToSelf(self => x => deepMap(x, self, true)),
  56. Unit: typed.referToSelf(self => x => {
  57. if (!x._isDerived() && x.units[0].unit.offset !== 0) {
  58. throw new TypeError('sign is ambiguous for units with offset');
  59. }
  60. return typed.find(self, x.valueType())(x.value);
  61. })
  62. });
  63. });