3

The numpy.multiply documentation says:

Equivalent to x1 * x2 in terms of array broadcasting.

Is np.multiply(x1, x2) different to x1 * x2 in any circumstance?

Where would I find the implementations of each?


Note: An analogous question exists for division but it doesn't mention multiplication, nor imply that the the answer would be the same in the multiplicative case.

This question also asks for implementation details specific to multiplication.

cs95
  • 379,657
  • 97
  • 704
  • 746
Tom Hale
  • 40,825
  • 36
  • 187
  • 242
  • Samething was asked 3 days ago: [Numpy np.multiply vs *-Operator](https://stackoverflow.com/questions/49493482/numpy-np-multiply-vs-operator) – hpaulj Mar 30 '18 at 03:55
  • Why are you asking? Do you have some odd-ball circumstance that you wondering about? What kinds of objects are you using? The `equivalent` statement applies to numeric `ndarray`, not `np.matrix` or `list`. – hpaulj Mar 30 '18 at 04:00
  • It's very weird that we suddenly get three (maybe more) near-identical questions in under a week, when I only ever remember seeing one of them before (and can't find it in a search). Is someone teaching a new course full of experienced programmers but who are new to numpy or something? – abarnert Mar 30 '18 at 04:32
  • @abarnet I'm doing a coursera course but it's certainly not new. I'm just doing a deep dive :) – Tom Hale Mar 31 '18 at 06:41

2 Answers2

6

Yes, np.multiply and the multiplication operator * work consistently for ndarray objects.

In [560]: x = np.array([1, 2, 3])

In [561]: y = np.array([4, 5, 6])

In [562]: x * y
Out[562]: array([ 4, 10, 18])

In [563]: np.multiply(x, y)
Out[563]: array([ 4, 10, 18])

The only major difference is in terms of matrix objects, for which, the * is setup to perform matrix multiplication (i.e., the dot product).

In [564]: x, y = map(np.matrix, (x, y))

In [565]: np.multiply(x, y)
Out[565]: matrix([[ 4, 10, 18]])

In [566]: x * y
ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)

Also, as @PaulPanzer mentioned in his answer, they behave differently when multiplying pure-python lists with scalars.

cs95
  • 379,657
  • 97
  • 704
  • 746
  • Where would I get access to the implementation of these? I was hoping for a link from the documentation page... – Tom Hale Mar 30 '18 at 03:09
  • @TomHale You can peruse the matrix code here: https://github.com/numpy/numpy/blob/9a4b692cb723b1eefea52ac6d5f1c6e2f6ed3187/numpy/matrixlib/defmatrix.py#L306 As for the array multiplication code, you may look at https://github.com/numpy/numpy/blob/master/numpy/core/src/multiarray/scalartypes.c.src#L247 but that's in C. – cs95 Mar 30 '18 at 03:12
6

Supplementing @COLDSPEED's answer I'd like to stress that for non array operands results can actually be quite different:

>>> import numpy as np
>>> 
>>> 2 * [1, 2]
[1, 2, 1, 2]
>>> np.multiply(2, [1, 2])
array([2, 4])
Paul Panzer
  • 51,835
  • 3
  • 54
  • 99