Python 在满足某个浮点值之前,从浮点池中减去浮点的最佳方法是什么
我试图从一组值中减去值,直到满足某个值为止,我应该如何做才能最大限度地减少舍入误差? 此代码的明显问题是+/-0.0001,它永远不会精确。。。有没有一种方法可以在python中正确地实现这一点Python 在满足某个浮点值之前,从浮点池中减去浮点的最佳方法是什么,python,python-3.x,floating-point,decimal,precision,Python,Python 3.x,Floating Point,Decimal,Precision,我试图从一组值中减去值,直到满足某个值为止,我应该如何做才能最大限度地减少舍入误差? 此代码的明显问题是+/-0.0001,它永远不会精确。。。有没有一种方法可以在python中正确地实现这一点 for budgettodistributeto in budgetstodistributeto: amountneeded = (Decimal(budgettodistributeto.forcepercentageofbudget) -
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
对于budgettodistributeto中的budgettodistributeto:
所需金额=(十进制(budgettodistributeto.forcepercentageofbudget)-
十进制(活动IDPercentageDict[budgettodistributeto.campaignid])
/总百分比(天)
断言(所需数量>0.0)
当前金额=0
当currentamount 如果(Decimal(budgettoretrievefrom.forcepercentageofbudget),我将按以下方式处理该问题:
#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
当然,您必须对查找所需值的部分应用您自己的逻辑。“我应该如何做到这一点以最大限度地减少舍入误差?”-->按候选值的大小排序,并首先尝试最接近运行总和的值。
while not in_range(pool, budget, accuracy) and pool > budget + accuracy:
pool -= (pool - budget)*dec_amt
print(pool)
print(Decimal(pool).quantize(Decimal('.01')))