[Numpy-discussion] BUG: ndarray subclass calls __mul__ when ** (pow) is involved

Robert Kern robert.kern at gmail.com
Sat Mar 19 18:01:22 EDT 2011

2011/3/19 Dmitrey <tmp50 at ukr.net>:
> I have ndarray subclass, its instance x and use
> r = x**2
> I expected it will call for each array element
> elem.__pow__(2)
> but it calls
> elem.__mul__(elem)
> instead.
> It essentially (tens or even more times) decreases my calculations speed for
> lots of cases.

x.__pow__(2) is indeed strength-reduced down to multiplication by
default. This occurs in the C implementation of ndarray.__pow__().
Feel free to override __pow__() in your class to directly call
np.power() which will just do the power calculation directly.

Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco

More information about the NumPy-Discussion mailing list