十进制。十进制(n) %1返回InvalidOperation,DivisionImpossible for all n>=100

2024-10-05 12:11:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我在django应用程序中使用Decimal对象,发现了一个奇怪的错误:

ipdb> decimal.Decimal(10) % 1
    Decimal('0')
ipdb> decimal.Decimal(100) % 1
    *** decimal.InvalidOperation: [<class 'decimal.DivisionImpossible'>]
ipdb> decimal.Decimal(150) % 1
    *** decimal.InvalidOperation: [<class 'decimal.DivisionImpossible'>]
ipdb> decimal.Decimal(79) % 1
    Decimal('0')
ipdb> decimal.Decimal(100.1) % 2
    Decimal('0.10')
ipdb> decimal.Decimal(1000) % 2
    *** decimal.InvalidOperation: [<class 'decimal.DivisionImpossible'>]

更神秘的是,在ipython中,直到数字变得非常大时才会发生这种情况:

^{pr2}$

请注意,这个错误不仅限于ipdb:我发现这个错误是因为Decimal(380)%1破坏了我的django应用程序。在

描述此错误的documentation表示:

Division impossible

This occurs and signals invalid-operation if the integer result of a divide-integer or remainder operation had too many digits (would be longer than precision). The result is [0,qNaN].

有什么想法吗?在


Tags: 对象django应用程序错误ipython数字integerresult
1条回答
网友
1楼 · 发布于 2024-10-05 12:11:19

我想我明白了。在

看着source code,我发现:

# catch most cases of large or small quotient
expdiff = self.adjusted() - other.adjusted()
if expdiff >= context.prec + 1:
    # expdiff >= prec+1 => abs(self/other) > 10**prec
    return context._raise_error(DivisionImpossible)
if expdiff <= -2:
    # expdiff <= -2 => abs(self/other) < 0.1
    ans = self._rescale(ideal_exponent, context.rounding)
    return ans._fix(context)

在我的django应用程序中,prec有一个调整:

^{pr2}$

这在我看来还是有点不对,因为:

In [39]: decimal.getcontext().prec + 1
Out[39]: 3

In [40]: decimal.Decimal(100).adjusted() - decimal.Decimal(0).adjusted()
Out[40]: 2

所以看起来100仍然在它检查的范围内(也就是说,2 < 3),但我很有信心这是问题的根源。如果有人能为我解释一下图书馆为什么这么做,我很想更好地理解它。在

相关问题 更多 >

    热门问题