algebraic operation that takes two equal-length sequences of numbers
In mathematics, the dot product is an algebraic operation that takes two equal-length sequences of numbers (usually coordinate vectors), and returns a single number. In Euclidean geometry, the scalar product of two … Wikipedia
🌐
Wikipedia
en.wikipedia.org › wiki › Dot_product
Dot product - Wikipedia
1 week ago - Algebraically, the dot product is the sum of the products of the corresponding entries of the two sequences of numbers. Geometrically, the scalar product of two vectors is the product of their lengths and the cosine of the angle between them. These definitions are equivalent when using Cartesian ...
🌐
Built In
builtin.com › data-science › dot-product-matrix
Dot Product of a Matrix: Explained | Built In
Two numpy array. | Image: Soner Yildirim · The dot product of these two vectors is the sum of the products of elements at each position.
Discussions

numpy - how to calculate the dot product of two arrays of vectors in python? - Stack Overflow
For a physicist there's a surprising amount of hand waving in this problem description. What have you tried, vectorized or not? Small sample arrays would be nice. The numpy dot tools are np.dot, np.tensordot, np.einsum, and the new @. ... In case someone comes here 7 years after the question was asked the einsum idea is a good one but I find the documentation a bit confusing. I had the exact same problem: the inner product ... More on stackoverflow.com
🌐 stackoverflow.com
Dot product of two arrays in Javascript - Stack Overflow
0 I want a mathematical formula to find the product of both array items but without going one by one separate multiplication More on stackoverflow.com
🌐 stackoverflow.com
Can someone explain what is happening here? I'm using numpy and I don't really understand the dot product
Dot product of two arrays. Specifically, If both a and b are 1-D arrays, it is inner product of vectors (without complex conjugation). If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred. https://numpy.org/doc/stable/reference/generated/numpy.dot.html For the first, the inner product [a, b, c] * [d, e, f] is [ad, be, cf]. The second, matrix multiplication, gives you a matrix AB = C st C[i, j] is the inner product ith row of A and jth column of B. More on reddit.com
🌐 r/learnpython
3
2
June 1, 2022
Dot product of two 3x3x3 arrays [University maths]
My best guess: The dot product is defined on vectors, not matrices, and not higher dimension arrays. What the program did was interpret the array as a 3x3 array of vectors, each of which is [1. 1. 1]. Then it took every vector in the first array and took the dot product with every vector in the second array. 3x3 choices in the first array, 3x3 choices in the second array, so 3x3x3x3 results in the resulting array. More on reddit.com
🌐 r/learnmath
3
4
March 27, 2017
🌐
Reddit
reddit.com › r/c_programming › how to compute the dot product of two arrays of varying types?
r/C_Programming on Reddit: How to compute the dot product of two arrays of varying types?
January 18, 2024 -

I would like to compute the dot product of two arrays of numbers, x and y. One way is as follows:

int dot_product (
    int *x, /* first array    */
    int *y, /* second array   */
    int  n  /* size of arrays */
) {
    int dot_product = 0 ;
    for(int i = 0 ; i < n ; i++) {
        dot_product += x[i] * y[i] ; 
    }
    return dot_product ;
}

This covers the case where x and y are arrays of ints, but I would like to also support the cases where one or more of x, y is an array of floats. The return type is not very important; it can be a double for all cases.

A solution is to cover all possibilities with 7 arguments:

double dot_product (
    int        *x_int_1,
    int        *y_int_1,
    int        *x_int_2,
    double  *y_double_2,
    double  *x_double_3,
    double  *y_double_3,
    int               n
) {
    int i ;
    double dot_product = 0 ;

    if (x_int_1 != NULL  y_int_1 != NULL) {
        for(i = 0 ; i < n ; i++) {
            dot_product += x_int_1[i] * y_int_1[i] ; 
        }
    }
    else if (x_int_2 != NULL  y_double_2 != NULL) {
        for(i = 0 ; i < n ; i++) {
            dot_product += x_int_2[i] * y_double_2[i] ; 
        }
    }
    else {
        for(i = 0 ; i < n ; i++) {
            dot_product += x_double_3[i] * y_double_3[i] ; 
        }
    }
    return dot_product ;
}

However, this is not a very good solution. What is a good way to do it?

Top answer
1 of 10
7
#include #define DOT_PRODUCT(x, y, n) \ _Generic((x), double * : dotProductDouble, int * : dotProductInt)(x, y, n) double dotProductDouble(double *x, double *y, int n) { double dp = 0; for (int i = 0; i < n; ++i) { dp += x[i] * y[i]; } return dp; } int dotProductInt(int *x, int *y, int n) { double dp = 0; for (int i = 0; i < n; ++i) { dp += x[i] * y[i]; } return dp; } int main() { double x[] = {1.0, 2.0, 3.0}; double y[] = {4.0, 5.0, 6.0}; int n = 3; double resultDouble = DOT_PRODUCT(x, y, n); printf("Dot Product Double: %lf\n", resultDouble); int a[] = {1, 2, 3}; int b[] = {4, 5, 6}; int resultInt = DOT_PRODUCT(a, b, n); printf("Dot Product Int: %d\n", resultInt); return 0; } I think the _Generic macro could be used for C11 or later. You are defining the dotProduct function twice (that's kinda bad), but this way, you don't have to perform a runtime type check for the correct functions. Edit: I didn't see that you have mixed types for x and y vectors, but still you can implement 4 separate functions like dotProductIntInt, dotProductDoubleInt... and so on and use _Generic #include #define DOT_PRODUCT(x, y, n) \ _Generic((x), double * : _Generic((y), double*: dotProductDoubleDouble, int* : dotProductDoubleInt), int * : _Generic((y), double*: dotProductIntDouble, int* : dotProductIntInt))(x, y, n) double dotProductDoubleDouble(double *x, double *y, int n) { double dp = 0; for (int i = 0; i < n; ++i) { dp += x[i] * y[i]; } return dp; } double dotProductDoubleInt(double *x, int *y, int n) { double dp = 0; for (int i = 0; i < n; ++i) { dp += x[i] * y[i]; } return dp; } double dotProductIntInt(int *x, int *y, int n) { double dp = 0; for (int i = 0; i < n; ++i) { dp += x[i] * y[i]; } return dp; } double dotProductIntDouble(int *x, double *y, int n) { double dp = 0; for (int i = 0; i < n; ++i) { dp += x[i] * y[i]; } return dp; } int main() { double x[] = {1.0, 2.0, 3.0}; double y[] = {4.0, 5.0, 6.0}; int n = 3; double result = DOT_PRODUCT(x, y, n); printf("Dot Product Double Double: %lf\n", result); int a[] = {1, 2, 3}; int b[] = {4, 5, 6}; result = DOT_PRODUCT(x, b, n); printf("Dot Product Double Int: %lf\n", result); return 0; }
2 of 10
4
Why not convert the inputs to a common type before the calculation? If the return will always be double, you can write the calculating function to take doubles and return them. Then write conversion functions for each of the types. You could wrap dot_product() with a conversion function for each permutation of inputs or.... Just convert each parameter in a conversion function before passing it to dot_product(). Something like: double x[n] = { … }; int y[n] = { … }; double *y_dbl = int2dbl(y, n); double *z = dot_product(x, y_dbl, n); free(y_dbl);
🌐
CodeSignal
codesignal.com › learn › courses › vector-and-matrix-operations-with-numpy › lessons › dot-product-and-cross-product-of-vectors-with-numpy
Dot Product and Cross Product of Vectors with NumPy
We start by defining two vectors, vector_a and vector_b, using NumPy arrays. The dot product is computed using both np.dot(vector_a, vector_b) and vector_a @ vector_b, demonstrating NumPy's flexibility in syntax. The result, a scalar, is printed out, indicating the degree of alignment between ...
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.dot.html
numpy.dot — NumPy v2.4 Manual
Returns the dot product of a and b. If a and b are both scalars or both 1-D arrays then a scalar is returned; otherwise an array is returned. If out is given, then it is returned. ... If the last dimension of a is not the same size as the second-to-last dimension of b. ... Complex-conjugating dot product. ... Vector dot product of two arrays.
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › find-maximum-dot-product-two-arrays-insertion-0s
Find Maximum dot product of two arrays with insertion of 0's - GeeksforGeeks
Input : A[] = {2, 3 , 1, 7, 8} , B[] = {3, 6, 7} Output : 107 Explanation : We get maximum dot product after inserting 0 at first and third positions in second array. Maximum Dot Product : = A[i] * B[j] 2*0 + 3*3 + 1*0 + 7*6 + 8*7 = 107 · Input : A[] = {1, 2, 3, 6, 1, 4}, B[] = {4, 5, 1} Output : 46 ... Another way to look at this problem is, for every pair of elements element A[i] and B[j] where j >= i , we have two choices:
Published   3 weeks ago
Find elsewhere
🌐
MathWorks
mathworks.com › matlab › mathematics › linear algebra
dot - Dot product - MATLAB
The function calculates the dot product of corresponding vectors along the first array dimension whose size does not equal 1. ... C = dot(A,B,dim) evaluates the dot product of A and B along dimension, dim. The dim input is a positive integer scalar. ... Create two simple, three-element vectors.
🌐
w3resource
w3resource.com › python-exercises › numpy › advanced-numpy-exercise-1.php
NumPy - Dot product of two arrays of different dimensions
nums2 = np.array([7, 8]): This code creates a 1D NumPy array with shape (2,) containing the values [7, 8] and assigns it to the variable nums2. result = np.dot(nums1, nums2): Here dot() function performs dot product between nums1 and nums2, and assigns the result to the variable result. Since nums1 has shape (3, 2) and nums2 has shape (2,), the dot product results in a 1D array with shape (3,) containing the values [23, 53, 83].
🌐
DataCamp
datacamp.com › doc › numpy › dot
NumPy dot()
The dot() function is used when you need to compute the dot product of two arrays, essential in operations like matrix multiplication or calculating vector projections. For 2-D arrays, np.dot() is equivalent to matrix multiplication.
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › program-dot-product-cross-product-two-vector
Program for dot product and cross product of two vectors - GeeksforGeeks
July 29, 2024 - static int dotProduct(int vect_A[], int vect_B[]) { int product = 0; // Loop for calculate dot product for (int i = 0; i < n; i++) product = product + vect_A[i] * vect_B[i]; return product; } // Function to find // cross product of two vector array.
Top answer
1 of 5
15

dot = (a, b) => a.map((x, i) => a[i] * b[i]).reduce((m, n) => m + n);
console.log(dot([1,2,3], [1,0,1]));

Here we use Array.prototype.map to create a new array with multiplied results of each index and Array.prototype.reduce to sum the values of resulting array.

2 of 5
4

Benchmark (the comments start with the median time of a thousand runs in ms):

let opt=[
  // (0.65) like kyun's answer but without extra variable
  'v.reduce((l,r,i)=>l+r*w[i],0)',

  // (0.66) like kyun's answer
  'v.reduce((l,r,i)=>{l+=(r*w[i]);return l},0)',

  // (0.71) variable for length declared outside block
  'let s2=0,l2=v.length;for(let i2=0;i2<l2;i2++)s2+=v[i2]*w[i2]',

  // (0.72) block-scoped variable for length
  'let s=0;for(let i=0,l=v.length;i<l;i++)s+=v[i]*w[i]',

  // (1.20) like the accepted answer
  'v.map((_,i)=>v[i]*w[i]).reduce((l,r)=>l+r)',

  // (1.93) hardcoded number for length
  'let s1=0;for(let i1=0;i1<1e4;i1++)s1+=v[i1]*w[i1]',

  // (2.05) check length during each iteration
  'let s3=0;for(let i3=0;i3<v.length;i3++)s3+=v[i3]*w[i3]',

  // (6.25) no `let` for sum variable
  's4=0;for(let i4=0,l4=v.length;i4<l4;i4++)s4+=v[i4]*w[i4]',

  // (12.17) no `let`
  's5=0;l5=v.length;for(i5=0;i5<l5;i5++)s5+=v[i5]*w[i5]',

  // (16.36) `var` instead of `let`
  'var s6=0,l6=v.length;for(var i6=0;i6<l6;i6++)s6+=v[i6]*w[i6]'
]

opt.sort(()=>Math.random()-.5)
let v=Array.from({length:1e4},()=>Math.random())
let w=Array.from({length:1e4},()=>Math.random())

for(let opti of opt){
  let t1=process.hrtime.bigint()
  eval(opti)
  let t2=process.hrtime.bigint()
  console.log(t2-t1+'\t'+opti)
}

In order to reduce the impact of optimizations for running the same code multiple times, I ran the benchmark like for i in {0..999};do node script.js;done instead of running each option 1000 times inside the script.

🌐
NumPy
numpy.org › devdocs › reference › generated › numpy.dot.html
numpy.dot — NumPy v2.6.dev0 Manual
Returns the dot product of a and b. If a and b are both scalars or both 1-D arrays then a scalar is returned; otherwise an array is returned. If out is given, then it is returned. ... If the last dimension of a is not the same size as the second-to-last dimension of b. ... Complex-conjugating dot product. ... Vector dot product of two arrays.
🌐
Medium
prajeetkalchuri18.medium.com › the-dot-product-between-arrays-d10f49e7a92e
The Dot Product Between Arrays - Prajeet Singh Kalchuri - Medium
January 5, 2022 - The dot product or scalar product or inner product between two vectors and of the same size is defined as: The dot product takes two vectors and returns a single number. Defining Arrays · nparray1 = np.array([0, 1, 2, 3]) # Define an array ...
🌐
Rosetta Code
rosettacode.org › wiki › Dot_product
Dot product - Rosetta Code
2 weeks ago - begin % computes the dot product of two equal length integer vectors % % (single dimension arrays ) the length of the vectors must be specified % % in length.
🌐
GeeksforGeeks
geeksforgeeks.org › numpy › python-program-to-get-dot-product-of-multidimensional-vectors-using-numpy
Python Program to Get dot product of multidimensional Vectors using NumPy - GeeksforGeeks
September 5, 2024 - Numpy module has a method dot which takes 2 vectors and returns the dot product of them ... # import numpy import numpy as np # initialize vectors a = np.array([2,5,3]) b = np.array([6,3,1]) # calculating Dot product form np.dot c = np.dot(a,b) print("Dot product of a and b is: ",c)
🌐
Reddit
reddit.com › r/learnmath › dot product of two 3x3x3 arrays [university maths]
r/learnmath on Reddit: Dot product of two 3x3x3 arrays [University maths]
March 27, 2017 -

Hello

I've been doing some work in Python for my research project and I've come over a solution to a problem which has my supervisor skeptical and myself confused.

Say I have two arrays: X = Y = [[[ 1. 1. 1.], [ 1. 1. 1.], [ 1. 1. 1.]],

[[ 1. 1. 1.], [ 1. 1. 1.], [ 1. 1. 1.]],

[[ 1. 1. 1.], [ 1. 1. 1.], [ 1. 1. 1.]]]

The shape of the array is 3x3x3.

Now, if I take the dot product ( R = np.dot(X,Y) ) I get a 3x3x3x3 array:

R = [[[[ 3. 3. 3.], [ 3. 3. 3.], [ 3. 3. 3.]],

[[ 3. 3. 3.], [ 3. 3. 3.], [ 3. 3. 3.]],

[[ 3. 3. 3.], [ 3. 3. 3.], [ 3. 3. 3.]]],

[[[ 3. 3. 3.], [ 3. 3. 3.], [ 3. 3. 3.]],

[[ 3. 3. 3.], [ 3. 3. 3.], [ 3. 3. 3.]],

[[ 3. 3. 3.], [ 3. 3. 3.], [ 3. 3. 3.]]],

[[[ 3. 3. 3.], [ 3. 3. 3.], [ 3. 3. 3.]],

[[ 3. 3. 3.], [ 3. 3. 3.], [ 3. 3. 3.]],

[[ 3. 3. 3.], [ 3. 3. 3.], [ 3. 3. 3.]]]]

How did I increase the dimensions of the array by one? Where can I read up on this sort of thing? Thanks!

Edit: From the scipy manual on numpy -

dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m]) For 2-D arrays it is equivalent to matrix multiplication, and for 1-D arrays to inner product of vectors (without complex conjugation). For N dimensions it is a sum product over the last axis of a and the second-to-last of b:

🌐
ScriptVerse
scriptverse.dev › tutorials › python-dot-product.html
Dot Product of 2 Arrays in Python/NumPy
Representing the vectors $u$ and $v$ as 1D arrays, we write the script below to compute their dot product. import numpy as np u = [2,-5] v = [1,3] dotproduct = np.dot(u,v) print(dotproduct) ... Now if the arrays are two-dimensional, numpy.dot() will result in matrix multiplication.