[Tutor] strange behavior of matrix**matrix

Steven D'Aprano steve at pearwood.info
Sun Jul 17 11:23:01 EDT 2016


On Sun, Jul 17, 2016 at 02:41:33PM +0200, A.Brozi wrote:
> Hello
> 
> I'm puzzling over some strange behavior of raising a matrix to a matrix 
> power:
> 
> If I create two matrices (containing integers):
> a = np.array([2])
> and
> b = np.array([-1])
> the operation a**b produces:
> array([0], dtype=int32)

What result did you expect? 2**-1 as an int32 cannot be 0.5, as that's a 
float.

I'm not really sure about the rules that numpy uses for coercing from 
one type to another, but I'm not surprised by this result. I don't know 
if it is documented anywhere, but it seems like the sort of thing numpy 
would do. Here's another similar example:

py> np.array([0])**-1
__main__:1: RuntimeWarning: divide by zero encountered in power
__main__:1: RuntimeWarning: invalid value encountered in power
array([-2147483648])



> The result of division b/a is correct:
> array([-0.5])

You only get that result in Python 3, or Python 2 with "from __future__ 
import division". Without it, / behaves the same as // (integer 
division), for example:

py> b//a
array([-1])
py> b/a
array([-1])

But once I run the future import, the behaviour changes:

py> from __future__ import division
py> b/a
array([-0.5])



> I wonder if it's a bug or a feature.
> And if it's a feature, then what is it useful for?

My guess is that the only reason for it is that it keeps the code 
simple, which allows numpy to be fast.

-- 
Steve


More information about the Tutor mailing list