为什么Python getcontext().prec = 4有时会给出3位小数而不是4位小数?

ton*_*nix 0 python precision decimal

我是python的新手,在我的新旅行中,我使用decimal模块遇到了这个:

>>> 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?
Run Code Online (Sandbox Code Playgroud)

https://docs.python.org/2/library/decimal.html看,我没有找到提及.

为什么会这样?

感谢您的关注!

小智 5

猜测:它是有效数字的位数:第二个和第三个例子的小数点前面还有一个数字(第一个例子中的0不重要).

请注意,文档中的第四个子弹说:

十进制模块包含重要位置的概念,因此1.30 + 1.20为2.50.

比较(使用您的第一个示例,但使用更大的数字):

>>> 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
Run Code Online (Sandbox Code Playgroud)

遗憾的是,文档中的大多数示例仅限于1阶的数字,因此这并未明确显示.