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