Home > Blockchain >  Numpy matrix multiplication with scalar results in negative zeros
Numpy matrix multiplication with scalar results in negative zeros

Time:10-26

I have a random nxn matrix A with floating points, then I call

X = np.eye(A.shape[0])

matrix nxn which has diagonal values (0 elsewhere)

1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

now I want to multiply every even row with -2 so I do

X[0::2] *= -2

however it returns

 2  0  0  0
-0 -2 -0 -0
 0  0  2  0
-0 -0 -0 -2 

Why do the zeroes have negative sign? Does this matter at all and if so is it possible to avoid having that? Thank you

SOLUTION

As someone pointed out, the np.eye function returns float matrix by default, fixed by adding np.eye(A.shape[0],dtype=int)

CodePudding user response:

The issue is that the numbers are float types so the '0' is not actually 0 but a very small number so when you multiply the number by -1, you actually multiplying the small number which can be negative. You can read about how floas are stored in memory in this post.

CodePudding user response:

SOLUTION

As someone pointed out, the np.eye function returns float matrix by default, fixed by adding np.eye(A.shape[0],dtype=int)

  • Related