Elemental Multiplication of Multiple Arrays in Python Numpy

While coding some of the procedures of quantum mechanics, I discovered the curious behavior of Python NumPy. When I multiply NumPy with more than two arrays, I get erroneous results. In the code below, I should write:

f = np.multiply(rowH,colH) A[row][col]=np.sum(np.multiply(f,w)) 

which gives the correct result. However, my initial wording is this:

 A[row][col]=np.sum(np.multiply(rowH, colH, w)) 

which does not display an error message but an incorrect result. Where is my mistake that I can give three arrays for multiple chores?

Here is the complete code:

 from numpy.polynomial.hermite import Hermite, hermgauss import numpy as np import matplotlib.pyplot as plt dim = 3 x,w = hermgauss(dim) A = np.zeros((dim, dim)) #build matrix for row in range(0, dim): rowH = Hermite.basis(row)(x) for col in range(0, dim): colH = Hermite.basis(col)(x) #gaussian quadrature in vectorized form f = np.multiply(rowH,colH) A[row][col]=np.sum(np.multiply(f,w)) print(A) 

:: NOTE :: this code only works with NumPy 1.7.0 and higher!

+6
source share
2 answers

Your mistake is that you are not reading the documentation :

numpy.multiply(x1, x2[, out])

multiply accepts exactly two input arrays. An additional third argument is the output array, which can be used to store the result. (If it is not specified, a new array is created and returned.) When you passed three arrays, the third array was overwritten by the product of the first two.

+14
source

Yes! Just like * np.arrays

 import numpy as np a=np.array([2,9,4]) b=np.array([3,4,5]) c=np.array([10,5,8]) d=a*b*c print(d) 

Produce:

 [ 60 180 160] 
0
source

All Articles