这是从浮点数池中减去浮点数直到达到某个浮点数值的最佳方法



我正试图从一个值池中减去值,直到达到某个值,我应该如何做到这一点,以最大限度地减少舍入误差?这个代码的明显问题是+/-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

我会用以下方式来处理这个问题:

#Function to detect if current value is within the desired accuracy  
def in_range(cur_val: float, tgt_val: float, tol:float) -> bool:
if cur_val >= tgt_val - tol and cur_val <= tgt_val + tol:
return True
return False

以某种方式递减池值的循环,直到in_range函数为True大致如下:

while not in_range(pool, budget, accuracy) and pool > budget + accuracy:
pool -= (pool - budget)*dec_amt
print(pool)
print(Decimal(pool).quantize(Decimal('.01')))  

当然,您必须将自己的逻辑应用于您正在寻找所需价值的部分。

最新更新