Chef1075 - 1 year ago 54

Python Question

I have a division error with the matrix below. I want to divide the 10 x 10

`matrix`

`[[5731, 3, 20, 8, 12, 54, 46, 8, 39, 2],`

[ 2, 6472, 47, 24, 7, 44, 7, 11, 116, 12],

[ 55, 36, 5296, 104, 84, 27, 106, 53, 183, 14],

[ 50, 49, 132, 5312, 2, 253, 36, 58, 142, 97],

[ 16, 28, 36, 9, 5381, 11, 55, 24, 85, 197],

[ 62, 45, 30, 181, 77, 4631, 117, 28, 161, 89],

[ 33, 23, 37, 1, 43, 92, 5642, 4, 42, 1],

[ 20, 20, 74, 23, 55, 14, 4, 5788, 18, 249],

[ 52, 155, 74, 143, 14, 170, 50, 30, 5036, 127],

[ 43, 32, 32, 85, 174, 40, 2, 197, 79, 5265]]

The

`sum_vector`

`[[5923],`

[6742],

[5958],

[6131],

[5842],

[5421],

[5918],

[6265],

[5851],

[5949]]

However, I keep getting this matrix below when the division occurs

`matrix / sum_vector`

`[[0 0 0 0 0 0 0 0 0 0]`

[0 0 0 0 0 0 0 0 0 0]

[0 0 0 0 0 0 0 0 0 0]

[0 0 0 0 0 0 0 0 0 0]

[0 0 0 0 0 0 0 0 0 0]

[0 0 0 0 0 0 0 0 0 0]

[0 0 0 0 0 0 0 0 0 0]

[0 0 0 0 0 0 0 0 0 0]

[0 0 0 0 0 0 0 0 0 0]

[0 0 0 0 0 0 0 0 0 0]]

I've tried this post and this post, but still getting all zeros.

I can divide the matrix by a scalar and it will return correctly. However it is something with my division that is returning all zeros.

I've also tried

`np.divide(matrix, sum_vector.reshape((10,1)))`

`matrix / matrix.sum(axis=1)[:,None]`

I feel like I'm missing something with the dimensions of the matrices, but I can't figure it out.

Suggestions?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

In Python2, dividing an integer by another integer yields an integer result, which will be rounded down to the nearest integer value. Numpy follows the same convention. Since all the values in your `sum_vector`

are larger than all the values in `matrix`

then the result will be an array of zeros.

To perform float division instead, you need to cast one or both of your input arrays to a floating point `dtype`

, e.g. `result = matrix.astype(np.double) / sum_vector`

.

The situation is different in Python3, where `/`

performs float division by default, and `//`

(the floor division operator) is used if you want an integral result. You can also get the new-style division behaviour in Python2 by importing `division`

from `__future__`

:

```
In [1]: 5 / 2
Out[1]: 2
In [2]: from __future__ import division
In [3]: 5 / 2
Out[3]: 2.5
In [4]: 5 // 2 # floor division operator
Out[4]: 2
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**