python—在满足某个floatvalue之前,从浮点池中减去浮点的最佳方法是什么

baubqpgj  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(387)

我试图从一个值池中减去值,直到满足某个值为止,我应该如何做才能最小化舍入误差?这个代码的明显问题是+/-0.0001它永远不会是精确的。。。有没有一种方法可以在python中正确地做到这一点?

  1. for budgettodistributeto in budgetstodistributeto:
  2. amountneeded = (Decimal(budgettodistributeto.forcepercentageofbudget) -
  3. Decimal(campaignidpercentagedict[budgettodistributeto.campaignid])
  4. / totalpercentageforday)
  5. assert (amountneeded > 0.0)
  6. currentamount = 0
  7. while currentamount < amountneeded:
  8. for budgettoretrievefrom in budgetstoretrievefrom:
  9. if (Decimal(budgettoretrievefrom.forcepercentageofbudget) <=
  10. ((Decimal(campaignidpercentagedict[budgettoretrievefrom.campaignid])
  11. / totalpercentageforday) - Decimal(0.001))):
  12. daybudgetcampaigndictcopied[day][budgettoretrievefrom.campaignid] -= Decimal(0.001)
  13. currentamount += Decimal(0.001)
  14. daybudgetcampaigndictcopied[day][budgettodistributeto.campaignid] += amountneeded
  15. daybudgetcampaigndictcopied[day] = campaignidpercentagedict
omvjsjqw

omvjsjqw1#

我将按以下方式处理这个问题:

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

一种循环,通过某种方式减少池值,直到in0 range函数为真,如下所示:

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

当然,你将不得不应用你自己的逻辑部分,你正在寻找所需的价值。

展开查看全部

相关问题