UNPKG

2.8 kBJavaScriptView Raw
1'use strict'
2
3const array = require('../../utils/array')
4
5function factory (type, config, load, typed) {
6 const matrix = load(require('../../type/matrix/function/matrix'))
7 const subtract = load(require('../arithmetic/subtract'))
8 const multiply = load(require('../arithmetic/multiply'))
9
10 /**
11 * Calculate the cross product for two vectors in three dimensional space.
12 * The cross product of `A = [a1, a2, a3]` and `B = [b1, b2, b3]` is defined
13 * as:
14 *
15 * cross(A, B) = [
16 * a2 * b3 - a3 * b2,
17 * a3 * b1 - a1 * b3,
18 * a1 * b2 - a2 * b1
19 * ]
20 *
21 * If one of the input vectors has a dimension greater than 1, the output
22 * vector will be a 1x3 (2-dimensional) matrix.
23 *
24 * Syntax:
25 *
26 * math.cross(x, y)
27 *
28 * Examples:
29 *
30 * math.cross([1, 1, 0], [0, 1, 1]) // Returns [1, -1, 1]
31 * math.cross([3, -3, 1], [4, 9, 2]) // Returns [-15, -2, 39]
32 * math.cross([2, 3, 4], [5, 6, 7]) // Returns [-3, 6, -3]
33 * math.cross([[1, 2, 3]], [[4], [5], [6]]) // Returns [[-3, 6, -3]]
34 *
35 * See also:
36 *
37 * dot, multiply
38 *
39 * @param {Array | Matrix} x First vector
40 * @param {Array | Matrix} y Second vector
41 * @return {Array | Matrix} Returns the cross product of `x` and `y`
42 */
43 const cross = typed('cross', {
44 'Matrix, Matrix': function (x, y) {
45 return matrix(_cross(x.toArray(), y.toArray()))
46 },
47
48 'Matrix, Array': function (x, y) {
49 return matrix(_cross(x.toArray(), y))
50 },
51
52 'Array, Matrix': function (x, y) {
53 return matrix(_cross(x, y.toArray()))
54 },
55
56 'Array, Array': _cross
57 })
58
59 cross.toTex = {
60 2: `\\left(\${args[0]}\\right)\\times\\left(\${args[1]}\\right)`
61 }
62
63 return cross
64
65 /**
66 * Calculate the cross product for two arrays
67 * @param {Array} x First vector
68 * @param {Array} y Second vector
69 * @returns {Array} Returns the cross product of x and y
70 * @private
71 */
72 function _cross (x, y) {
73 const highestDimension = Math.max(array.size(x).length, array.size(y).length)
74
75 x = array.squeeze(x)
76 y = array.squeeze(y)
77
78 const xSize = array.size(x)
79 const ySize = array.size(y)
80
81 if (xSize.length !== 1 || ySize.length !== 1 || xSize[0] !== 3 || ySize[0] !== 3) {
82 throw new RangeError('Vectors with length 3 expected ' +
83 '(Size A = [' + xSize.join(', ') + '], B = [' + ySize.join(', ') + '])')
84 }
85
86 const product = [
87 subtract(multiply(x[1], y[2]), multiply(x[2], y[1])),
88 subtract(multiply(x[2], y[0]), multiply(x[0], y[2])),
89 subtract(multiply(x[0], y[1]), multiply(x[1], y[0]))
90 ]
91
92 if (highestDimension > 1) {
93 return [product]
94 } else {
95 return product
96 }
97 }
98}
99
100exports.name = 'cross'
101exports.factory = factory