UNPKG

2.13 kBJavaScriptView Raw
1'use strict'
2
3const size = require('../../utils/array').size
4
5function factory (type, config, load, typed) {
6 const add = load(require('../arithmetic/add'))
7 const multiply = load(require('../arithmetic/multiply'))
8
9 /**
10 * Calculate the dot product of two vectors. The dot product of
11 * `A = [a1, a2, a3, ..., an]` and `B = [b1, b2, b3, ..., bn]` is defined as:
12 *
13 * dot(A, B) = a1 * b1 + a2 * b2 + a3 * b3 + ... + an * bn
14 *
15 * Syntax:
16 *
17 * math.dot(x, y)
18 *
19 * Examples:
20 *
21 * math.dot([2, 4, 1], [2, 2, 3]) // returns number 15
22 * math.multiply([2, 4, 1], [2, 2, 3]) // returns number 15
23 *
24 * See also:
25 *
26 * multiply, cross
27 *
28 * @param {Array | Matrix} x First vector
29 * @param {Array | Matrix} y Second vector
30 * @return {number} Returns the dot product of `x` and `y`
31 */
32 const dot = typed('dot', {
33 'Matrix, Matrix': function (x, y) {
34 return _dot(x.toArray(), y.toArray())
35 },
36
37 'Matrix, Array': function (x, y) {
38 return _dot(x.toArray(), y)
39 },
40
41 'Array, Matrix': function (x, y) {
42 return _dot(x, y.toArray())
43 },
44
45 'Array, Array': _dot
46 })
47
48 dot.toTex = { 2: `\\left(\${args[0]}\\cdot\${args[1]}\\right)` }
49
50 return dot
51
52 /**
53 * Calculate the dot product for two arrays
54 * @param {Array} x First vector
55 * @param {Array} y Second vector
56 * @returns {number} Returns the dot product of x and y
57 * @private
58 */
59 // TODO: double code with math.multiply
60 function _dot (x, y) {
61 const xSize = size(x)
62 const ySize = size(y)
63 const len = xSize[0]
64
65 if (xSize.length !== 1 || ySize.length !== 1) throw new RangeError('Vector expected') // TODO: better error message
66 if (xSize[0] !== ySize[0]) throw new RangeError('Vectors must have equal length (' + xSize[0] + ' != ' + ySize[0] + ')')
67 if (len === 0) throw new RangeError('Cannot calculate the dot product of empty vectors')
68
69 let prod = 0
70 for (let i = 0; i < len; i++) {
71 prod = add(prod, multiply(x[i], y[i]))
72 }
73
74 return prod
75 }
76}
77
78exports.name = 'dot'
79exports.factory = factory