【问题标题】:Which is the best way to subtract a float from a pool of floats until a certain floatvalue is met这是从浮点数池中减去浮点数直到满足某个浮点值的最佳方法
【发布时间】: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


【解决方案1】:

我会通过以下方式解决问题:

#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')))  

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

【讨论】:

    猜你喜欢
    • 2021-08-05
    • 1970-01-01
    • 2022-01-10
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多