Home » Python » Not getting full float division for values above 1. in python 3.6.2-Exceptionshub

Not getting full float division for values above 1. in python 3.6.2-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I am trying to fill a np.zeros 2d array with some values and then normalize those values with the max value in each row.

I am dividing each value of that row with the max value using the max() function. Although I am getting proper float division for values in the array up to the max value, Python only returns 1. for values after the max value in the array.

How can can I have proper values in this case?

I am using Python 3.6.2 with jupyter notebook.

 import numpy as np
 from matplotlib import pyplot as plt
 np.set_printoptions(threshold=np.inf) #for printing full array

 l1 = np.zeros((5,10))
 l2 = np.arange(500)

 for j in range(len(l1[:,0])):
  for i in range(len(l1[0,:])):
    if i<(j+(len(l1[0,:])/2)):
        l1[j,i] = l1[j,i-1]+1
    if i>(j+(len(l1[0,:])/2)-1):
        l1[j,i] = l1[j,i-1]-1


for j in range(len(l1[:,0])):
 for i in range(len(l1[0,:])):
    l1[j,i] = l1[j,i]/(max(l1[j,:]))

fig,ax = plt.subplots(figsize = (5,25))
ax.imshow(l1)
ax.set_aspect('5')

print(l1[0,:])

The result I get is:

[0.2 0.4 0.6 0.8 1.  1.  1.  1.  1.  0. ]

The array without normalizing:

[1. 2. 3. 4. 5. 4. 3. 2. 1. 0.]
How to&Answers:

Thanks to user2357112supportsMonica and mkrieger1 I found my mistake in the code. The max value was changing as the for loops edit the array. The solution to this was achieved by changing the code as follows:

import numpy as np
from matplotlib import pyplot as plt
np.set_printoptions(threshold=np.inf) #for printing full array

l1 = np.zeros((10,20))
l2 = np.arange(500)

for j in range(len(l1[:,0])):
    for i in range(len(l1[0,:])):
        if i<(j+(len(l1[0,:])/2)):
            l1[j,i] = l1[j,i-1]+1
        if i>(j+(len(l1[0,:])/2)-1):
            l1[j,i] = l1[j,i-1]-1

for j in range(len(l1[:,0])):
    l1[j,:] = l1[j,:]/(max(l1[j,:]))

fig,ax = plt.subplots(figsize = (5,25))
ax.imshow(l1)
ax.set_aspect('1')