0

I have b_x as an array and I'm operating on it as shown in code.

G = 5
b_x =numpy.array([[0] for i in range(G)])
print(b_x)

for x in range(5):
    for y in range(5):
        b_x[x] += y*0.25
        print("y*0.25:" + " " + str(y*0.25))
        print("b_x[x]:" + " " + str(b_x[x][0]))
    print("end")
print(b_x)

After addition my b_x should be like:

[[2.5]
 [2.5]
 [2.5]
 [2.5]
 [2.5]]

But the output is different.So, I added some print statements to check, and got the following output:

[[0]
 [0]
 [0]
 [0]
 [0]]
y*0.25: 0.0
b_x[x]: 0
y*0.25: 0.25
b_x[x]: 0
y*0.25: 0.5
b_x[x]: 0  
y*0.25: 0.75
b_x[x]: 0
y*0.25: 1.0
b_x[x]: 1
end
y*0.25: 0.0
b_x[x]: 0
y*0.25: 0.25
b_x[x]: 0
y*0.25: 0.5
b_x[x]: 0
y*0.25: 0.75
b_x[x]: 0
y*0.25: 1.0
b_x[x]: 1 
end
y*0.25: 0.0
b_x[x]: 0
y*0.25: 0.25
b_x[x]: 0
y*0.25: 0.5
b_x[x]: 0
y*0.25: 0.75
b_x[x]: 0
y*0.25: 1.0
b_x[x]: 1
end
y*0.25: 0.0
b_x[x]: 0 
y*0.25: 0.25
b_x[x]: 0
y*0.25: 0.5
b_x[x]: 0
y*0.25: 0.75
b_x[x]: 0
y*0.25: 1.0
b_x[x]: 1
end
y*0.25: 0.0
b_x[x]: 0
y*0.25: 0.25
b_x[x]: 0
y*0.25: 0.5
b_x[x]: 0
y*0.25: 0.75
b_x[x]: 0
y*0.25: 1.0
b_x[x]: 1  
end
[[1] 
 [1]
 [1]
 [1]
 [1]]

I n the end, every value is 1 which is wrong. And on checking the inner print statement it seems that the elements don't get added when the (y*0.25) value is a decimal. I have checked another code where if the value to be added is 12.5, only 12 gets added to the array element.Why does this happen with numpy array?

The problem doesn't occur with list(if I define b_x as a list), there the decimal values get added.

1 Answer 1

2

Change

b_x =numpy.array([[0] for i in range(G)])

to

b_x =numpy.array([[0.0] for i in range(G)])

or better

b_x =numpy.zeros((5,))

The trouble is that in your version b is stored as integers, so b[x] += (some smallish fraction) gets rounded down to 0.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.