任何想法为什么Python的decimal模块不喜欢数字1或更多,但0.9和更少可以吗?
>>> import decimal >>> max_digits = 5 >>> decimal_places = 5 >>> context = decimal.getcontext().copy() >>> context.prec = max_digits1本身有太多数字:
>>> value = decimal.Decimal('1') >>> '%s' % str(value.quantize(decimal.Decimal(".1") ** decimal_places, context=context)) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/decimal.py", line 2470, in quantize 'quantize result has too many digits for current context') File "/usr/lib/python2.7/decimal.py", line 3872, in _raise_error raise error(explanation) decimal.InvalidOperation: quantize result has too many digits for current context但是低于1的任何情况都可以:
>>> value = decimal.Decimal('0.9') >>> '%s' % str(value.quantize(decimal.Decimal(".1") ** decimal_places, context=context)) '0.90000'有人在乎解释吗?
Any idea why Python's decimal module doesn't like numbers 1 or more but 0.9 and less is okay?
>>> import decimal >>> max_digits = 5 >>> decimal_places = 5 >>> context = decimal.getcontext().copy() >>> context.prec = max_digits1 itself has too many digits:
>>> value = decimal.Decimal('1') >>> '%s' % str(value.quantize(decimal.Decimal(".1") ** decimal_places, context=context)) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/decimal.py", line 2470, in quantize 'quantize result has too many digits for current context') File "/usr/lib/python2.7/decimal.py", line 3872, in _raise_error raise error(explanation) decimal.InvalidOperation: quantize result has too many digits for current contextBut anything below 1 is fine:
>>> value = decimal.Decimal('0.9') >>> '%s' % str(value.quantize(decimal.Decimal(".1") ** decimal_places, context=context)) '0.90000'Anyone care to explain?
最满意答案
这是因为您将最大精度context.prec设置为5位数字,同时您还将decimal_places设置为小数点后的5个位置。 将值1和以上放置将给出6位精度(有效数字):
1.00000 ^ ^^^^^这是1加5个小数位。 这就是为什么它抱怨说“结果对于当前上下文有太多数字”。 注意:看,错误信息实际上解释了它! = d
对于低于1的数字,精确度只有5位数,因为小数点前的部分不重要。
0.90000 ^^^^^您不需要设置context.prec ,或者将其设置为更大的数字。 为什么你想首先设置环境?
将max_digits设置为6适用于我。
That's because you set the maximum precision context.prec to be 5 digits, while you also set the decimal_places into 5 places after the decimal point. Putting values 1 and above will give you 6 digits of precision (significant figures):
1.00000 ^ ^^^^^which is the 1 plus 5 decimal places. That's why it complains, saying "result has too many digits for current context". note: see, the error message actually explained it! =D
For numbers below 1, there are exactly 5 digits of precision, because the part before the decimal point is not significant.
0.90000 ^^^^^You don't need to set the context.prec, or, set it to larger number. Why did you want to set the context in the first place?
Setting the max_digits to 6 works for me.
更多推荐
发布评论