# [Numpy-tickets] [NumPy] #741: Extend numpy.dot() to accept more than 2 arrays.

NumPy numpy-tickets@scipy....
Thu Apr 17 16:17:48 CDT 2008

```#741: Extend numpy.dot() to accept more than 2 arrays.
-------------------------+--------------------------------------------------
Reporter:  joris        |        Owner:  somebody
Type:  enhancement  |       Status:  new
Priority:  normal       |    Milestone:  1.2
Component:  numpy.core   |      Version:  none
Severity:  normal       |   Resolution:
Keywords:               |
-------------------------+--------------------------------------------------
Comment (by joris):

The conversation Robert mentioned can be found in the numpy archives on
gmane, with the keywords:[[BR]]
- extended dot()  (Tim Hochberg) [[BR]]
- simple multi-arg wrapper for dot (Bil Baxter, Anne Archibald, Colin J.
Williams)

The associativity argument of Tim boils down to:

1) to be efficient, an extended dot should be able to choose the order of
operations. E.g. if A is 100x3, B is 3x100, and C is 100x1, then
dot(dot(A,B), B) is less efficient than dot(A, dot(B,C)) since the former
requires an intermediate 100x100 array.

2) the optimum order of operations is difficult to choose because dot() is
intrinsically not-associative because it can do both matrix and dot
multiplications: e.g.  {{{dot([1,2], dot([3,2], [1,1])) !=
dot(dot([1,2],[3,2]), [1,1])}}}

Bill provides an interesting suggestion: no optimization provided, but
giving the user a way to specify the order of multiplication:

{{{
mdot(a,(b,c),d)
mdot(a,(b,c,d))
mdot(a,b,c,d)
}}}
etc.

with

{{{
def mdot(*args):
if len(args) == 1:
return args[0]
elif len(args) == 2:
return _mdot(args[0], args[1])
else:
return _mdot(args[:-1], args[-1])

def _mdot(a,b):
if isinstance(a,tuple):
if len(a) > 1:
a = mdot(*a)
else:
a = a[0]
if isinstance(b, tuple):
if len(b) > 1:
b = mdot(*b)
else:
b = b[0]

return N.dot(a,b)
}}}

However, in its current form {{{mdot(a,b,c,d)}}} is about twice as slow as
{{{dot(a,dot(b,dot(c,d)))}}}, which is kind of show-stopper.

--
Ticket URL: <http://scipy.org/scipy/numpy/ticket/741#comment:2>
NumPy <http://projects.scipy.org/scipy/numpy>
The fundamental package needed for scientific computing with Python.
```