在保存到DB之前对python列表值进行四舍五入



我使用python将每月预测值保存在postgesDB中,与实际结果相匹配例如每月预测值[10.5,20.6,30.8,5.4,0,1,1.4,2.2],总计71.9和实际结果65

我的解决方案是通过将实际值除以预测值65/71.9=0.904来获得一个重新缩放因子,并将其乘以预测值中的所有值,现在新列表将为[9.492,18.622,27.843,4.881,0,0.904,1.265,1.988],其总和为64.995,四舍五入为实际值65,但现在我被要求预测值只能是整数,重构列表以使预测值仅为"0"的最佳方式是什么;正整数";与实际结果接近+-1。我尝试在重构后对列表值进行四舍五入,但对于列表较大的记录,与实际值的差异超过100

results = []
forecast = [10.5, 20.6, 30.8, 5.4, 0, 1, 1.4, 2.2]
actual_result = 65
rounded_list = [round(number) for number in forecast if number >= 0]
percentage = actual_result / sum(rounded_list)
for number in rounded_list:
results.append(number * percentage)

打印列表:

[9.154929577464788, 19.225352112676056, 28.380281690140844, 4.577464788732394, 0.0, 0.9154929577464789, 0.9154929577464789, 1.8309859154929577]

打印总额列表:

65.0

如果你想非常精确,并且预测列表应该只有整数:

results = []
forecast = [10.5, 20.6, 30.8, 5.4, 0, 1, 1.4, 2.2]
actual_result = 65
rounded_list = [number * 10 for number in forecast if number >= 0]
percentage = 65 * 10 / sum(rounded_list)
for number in rounded_list:
results.append(number * percentage / 10)

打印列表:

[9.492350486787204, 18.6230876216968, 27.8442280945758, 4.881780250347704, 0.0, 0.9040333796940194, 1.265646731571627, 1.9888734353268425]

打印列表总和:

65.0

最新更新