问题描述
我是python的新手,在我的新旅程中,我使用 decimal
模块遇到了这一点:
I am new to python, and in my new trip I have encountered this using the decimal
module:
>>> getcontext().prec = 4; print(Decimal(7)/Decimal(9));
0.7778 # everything ok
>>>
>>> getcontext().prec = 4; print(Decimal(2).sqrt());
1.414 # why 3 and not 4?
>>>
>>> getcontext().prec = 10;
>>> print(Decimal(10).log10()/Decimal(2).log10());
3.321928094 # why 9 if precision is set to 10?
从 https://docs.python.org/2/library/decimal看.html 我没有找到提及的地方.
Looking from the https://docs.python.org/2/library/decimal.html I didn't find a mention on that.
为什么会发生?
感谢您的关注!
推荐答案
猜测:这是有效位数:第二个和第三个示例的小数点前还有一个数字(第一个例子并不重要).
At a guess: it's the number of significant digits: there is also a digit in front of the decimal point for the second and third example (the 0 in the first example is not significant).
请注意,文档中的第四个项目符号为:
Note that the fourth bullet in the documentation says:
比较(使用第一个示例,但数量更多):
Compare (using your first example, but with a larger number):
>>> getcontext().prec = 8
>>> print Decimal(7000)/Decimal(9)
777.77778
>>> getcontext().prec = 4
>>> print Decimal(7000)/Decimal(9)
777.8
>>> getcontext().prec = 2
>>> print Decimal(7000)/Decimal(9)
7.8E+2
不幸的是,文档中的大多数示例都限于1级数字,因此并不能清楚地显示出来.
Unfortunately, most examples in the documentation are restricted to numbers of order 1, so this doesn't show clearly.
这篇关于为什么Python getcontext().prec = 4有时会给出3个小数而不是4个小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!