UNPKG

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