1

I am not able to figure what out what is wrong with this piece of code. Could you please help me understand what is going wrong and how to fix it?

import numpy as np
T = np.random.randint(0,5,(3,2,3))
print(T)
print(T[0,0])
print(T[0,0].sum())
T[0,0] = T[0,0]/T[0,0].sum()
print(T)

Output i get:

[[[4 1 3]
  [1 4 4]]

 [[0 0 4]
  [2 2 2]]

 [[2 4 2]
  [2 1 4]]]
[4 1 3]
8
[0.5   0.125 0.375]
[[[0 0 0]
  [1 4 4]]

 [[0 0 4]
  [2 2 2]]

 [[2 4 2]
  [2 1 4]]]

Output i expect:

[[[4 1 3]
  [1 4 4]]

 [[0 0 4]
  [2 2 2]]

 [[2 4 2]
  [2 1 4]]]
[4 1 3]
8
[0.5   0.125 0.375]
[[[0.5   0.125 0.375]
  [1 4 4]]

 [[0 0 4]
  [2 2 2]]

 [[2 4 2]
  [2 1 4]]]

Any help would be appreciated. Thanks!

xabhi
  • 798
  • 1
  • 13
  • 30
  • 1
    How do you justify that row of floats, `[0.5 0.125 0.375]` in an integer array? – hpaulj Jun 21 '20 at 23:42
  • Feel like an idiot now, guess that is the result of coding in wee hours of night. Thanks for bringing sanity to my life again. – xabhi Jun 22 '20 at 05:06

1 Answers1

0

Your array is of type int (calling randint) and you try to assign float to it which will round numbers to int in it. If you want to keep the values as float, convert your array to float as well.

T = T.astype(np.float)
T[0,0] = T[0,0]/T[0,0].sum()
print(T)

The example is different, because it is created randomly, but gives you the ides:

[[[0.   0.75 0.25]
  [1.   4.   0.  ]]

 [[1.   4.   0.  ]
  [1.   3.   1.  ]]

 [[3.   2.   1.  ]
  [4.   0.   2.  ]]]
Ehsan
  • 12,072
  • 2
  • 20
  • 33