Coding some Quantum Mechanics routines, I have discovered a curious behavior of Python's NumPy. When I use NumPy's multiply with more than two arrays, I get faulty results. In the code below, i have to write:
f = np.multiply(rowH,colH)
A[row][col]=np.sum(np.multiply(f,w))
which produces the correct result. However, my initial formulation was this:
A[row][col]=np.sum(np.multiply(rowH, colH, w))
which does not produce an error message, but the wrong result. Where is my fault in thinking that I could give three arrays to numpy's multiply routine?
Here is the full 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 runs with NumPy 1.7.0 and higher!
Use the np. multiply() function or the * (asterisk) character in NumPy to execute element-wise matrix multiplication.
NumPy array can be multiplied by each other using matrix multiplication. These matrix multiplication methods include element-wise multiplication, the dot product, and the cross product.
C = A . * B multiplies arrays A and B by multiplying corresponding elements. The sizes of A and B must be the same or be compatible. If the sizes of A and B are compatible, then the two arrays implicitly expand to match each other.
Your fault is in not reading the documentation:
numpy.multiply(x1, x2[, out])
multiply
takes exactly two input arrays. The optional third argument is an output array which can be used to store the result. (If it isn't provided, a new array is created and returned.) When you passed three arrays, the third array was overwritten with the product of the first two.
For anyone stumbling upon this, the best way to apply an element-wise multiplication of n np.ndarray
of shape (d, )
is to first np.vstack
them and apply np.prod
on the first axis:
>>> import numpy as np
>>>
>>> arrays = [
... np.array([1, 2, 3]),
... np.array([5, 8, 2]),
... np.array([9, 2, 0]),
... ]
>>>
>>> print(np.prod(np.vstack(arrays), axis=0))
[45 32 0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With