我有b_x作为一个数组,我正在操作它,如代码所示。
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)
添加后,我的b_x应该是:
[[2.5]
[2.5]
[2.5]
[2.5]
[2.5]]
但输出是不同的。所以,我添加了一些打印语句来检查,并得到以下输出:
[[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]]
最后,每个值都是1,这是错误的。在检查内部打印语句时,似乎在(y * 0.25)值为小数时不会添加元素。 我已经检查了另一个代码,如果要添加的值是12.5,只有12个被添加到数组元素。为什么这会发生在numpy数组?
列表不会出现问题(如果我将b_x定义为列表),则会添加小数值。
答案 0 :(得分:2)
更改
b_x =numpy.array([[0] for i in range(G)])
到
b_x =numpy.array([[0.0] for i in range(G)])
或更好
b_x =numpy.zeros((5,))
问题在于,您的版本b
存储为整数,因此b[x] += (some smallish fraction)
向下舍入为0.