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