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

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

我试图从一个值池中减去值,直到满足某个值为止,我应该如何做才能最小化舍入误差?这个代码的明显问题是+/-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
omvjsjqw

omvjsjqw1#

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


# 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

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

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

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

相关问题