Elementwise multiplication of several arrays in Python Numpy

seb picture seb · Apr 19, 2013 · Viewed 10.4k times · Source

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!

Answer

BrenBarn picture BrenBarn · Apr 19, 2013

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.