30

Is there any difference in using

import numpy as np

a, b = np.random([1024, 1024]), np.random([1024, 1024])
c = np.multiply(a, b)

over

c = a * b

or is the *-Operator on numpy-arrays simply overridden with np.multiply?


Edit: This question is marked as duplicate because a question asks the same thing about the division operator (np.divide() vs /) and similar answers followed, but unless it is changed to "numpy arithmetic vs. python arithmetic" or something of the kind, it won't help people wondering the same thing as I did (about multiplication) and not being "clever" enough to assume a question about a related arithmetic operation (division) generalizes to all the basic arithmetic operations. To make it easier finding answers, I'd advocate for keeping this question as is.

Honeybear
  • 2,928
  • 2
  • 28
  • 47
  • 1
    Did you even try to search for the answer in the docs? It literally took me less than 5 seconds to find the answer. – DeepSpace Mar 26 '18 at 14:11
  • 5
    I did look at the docs and looked around on SO. If you are referring to the docs, I found `Equivalent to x1 * x2 in terms of array broadcasting.` not to be an answer to this question, as it explicitly says it is equivalent "... in terms of broadcasting", leaving me wondering whether there are other differences, e.g. in terms of speed. – Honeybear Mar 26 '18 at 14:34
  • 2
    Snarky comment, and this question being closed as dupe, is why SO is broken and subject of ridicule at r/ProgrammerHumor. That this question came up first when I googled `numpy multiply vs *` shows the system is still working despite itself – eric Oct 07 '22 at 11:22

2 Answers2

26

There is no difference. However, the np.multiply function can take in additional, optional arguments, making it more versatile. See the docs.

Saying that * is overwritten with np.multiply would not be very precise. Generally, * maps to calls to the __mul__ and __rmul__ methods on the objects on which it acts. Thus, * is rather "overwritten" with np.ndarray.__mul__.

jmd_dk
  • 12,125
  • 9
  • 63
  • 94
  • 3
    One interesting to note too, is that np.multiply can be used for non numpy arrays: `[ x1, ..., xn ] * [y1, ..., yn]` wouldn't work, but `np.multiply([ x1, ..., xn ] * [y1, ..., yn])` does. – Atralb Feb 05 '21 at 02:08
11

speed differences - none:

In [65]: timeit c = np.multiply(a,b)
4.95 ms ± 10.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [66]: timeit c = a*b
5.06 ms ± 180 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

For smaller arrays we might see differences due to a different calling stack, but with these, the actual computation dominates the time.

But as you can see from the docs, np.multiply is a ufunc with access to all the machinery that that implies.

For np.matrix objects, * is matrix product, np.multiply is element multiplication.

jmd_dk
  • 12,125
  • 9
  • 63
  • 94
hpaulj
  • 221,503
  • 14
  • 230
  • 353