因此,我开始构建一个函数,旨在纠正超出一定限制的前3个“分配”。计算float和存储到列表给出了奇怪的值?
下面的函数现在返回一个列表,其中传递列表中每个值超出的值。
def correct_wrong_allocations_zw(weight_vect):
temp_weight_vect = list(weight_vect[:3])
limits = [1.00, 0.30, 0.25]
too_much_list = []
too_much = 0.00
for i in range(0, len(temp_weight_vect)):
if temp_weight_vect[i] > limits[i]:
too_much_list.append(temp_weight_vect[i]-limits[i])
return too_much_list
allocations = [0.10, 0.40, 0.50, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00]
allocations = correct_wrong_allocations_zw(allocations)
print allocations
分配[1]和限制之间的差异[1]为0.10,但这个方案的结果是:
[0.10000000000000003, 0.25]
这是怎么回事?
使用格式化的printf四舍五入值。所使用的内部二进制表示不能与理性1/10完全匹配,多于一个打印的十进制可以完全匹配理性1/3。 – mpez0
如果要控制浮点精度超出格式化输出,请查看[decimal](https://docs.python.org/2.7/library/decimal.html)模块。 – schwobaseggl
我希望人们会停止链接到该通用问题,并找到更多Python特定的东西,因为它们的工作方式或每种语言的固定方式都有细微差别。 –