By the following example, I can confirm that multiply would only work with at most 3 arguments:
import numpy as np
w = np.asarray([2, 4, 6])
x = np.asarray([1, 2, 3])
y = np.asarray([3, 1, 2])
z = np.asarray([10, 10, 10])
np.multiply(w, x, y) # works
np.multiply(w, x, y, z) #failed
Here is the error message:
ValueError Traceback (most recent call last)
<ipython-input-14-9538812eb3b4> in <module>()
----> 1 np.multiply(w, x, y, z)
ValueError: invalid number of arguments
Is there any way to achieve multiply with more than 3 arguments? I don't mind to use other Python library.
You can use np.prod
to calculate the product of array elements over a given axis , here it's (axis=0), ie multiply rows element-wise:
np.prod([w, x, y], axis=0)
# array([ 6, 8, 36])
np.prod([w, x, y, z], axis=0)
# array([ 60, 80, 360])
Actually multiply
takes two arrays. It's a binary operation. The third is an optional out
. But as a ufunc
it has a reduce
method which takes a list:
In [234]: x=np.arange(4)
In [235]: np.multiply.reduce([x,x,x,x])
Out[235]: array([ 0, 1, 16, 81])
In [236]: x*x*x*x
Out[236]: array([ 0, 1, 16, 81])
In [237]: np.prod([x,x,x,x],axis=0)
Out[237]: array([ 0, 1, 16, 81])
np.prod
can do the same, but be careful with the axis
parameter.
More fun with ufunc
- accumulate:
In [240]: np.multiply.accumulate([x,x,x,x])
Out[240]:
array([[ 0, 1, 2, 3],
[ 0, 1, 4, 9],
[ 0, 1, 8, 27],
[ 0, 1, 16, 81]], dtype=int32)
In [241]: np.cumprod([x,x,x,x],axis=0)
Out[241]:
array([[ 0, 1, 2, 3],
[ 0, 1, 4, 9],
[ 0, 1, 8, 27],
[ 0, 1, 16, 81]], dtype=int32)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.