【发布时间】:2021-04-27 13:00:52
【问题描述】:
我正在尝试从值池中减去值,直到满足某个值,我应该如何做到这一点以最小化舍入误差? 这段代码的明显问题是 +/- 0.0001 它永远不会是精确的......有没有办法在 python 中正确地做到这一点?
for budgettodistributeto in budgetstodistributeto:
amountneeded = (Decimal(budgettodistributeto.forcepercentageofbudget) -
Decimal(campaignidpercentagedict[budgettodistributeto.campaignid])
/ totalpercentageforday)
assert (amountneeded > 0.0)
currentamount = 0
while currentamount < amountneeded:
for budgettoretrievefrom in budgetstoretrievefrom:
if (Decimal(budgettoretrievefrom.forcepercentageofbudget) <=
((Decimal(campaignidpercentagedict[budgettoretrievefrom.campaignid])
/ totalpercentageforday) - Decimal(0.001))):
daybudgetcampaigndictcopied[day][budgettoretrievefrom.campaignid] -= Decimal(0.001)
currentamount += Decimal(0.001)
daybudgetcampaigndictcopied[day][budgettodistributeto.campaignid] += amountneeded
daybudgetcampaigndictcopied[day] = campaignidpercentagedict
【问题讨论】:
-
“我应该怎么做才能最小化舍入误差?” --> 按候选者的大小对候选者进行排序,并首先尝试最接近运行总和的值。
标签: python python-3.x floating-point decimal precision