Python十进制.十进制精度与Wolfram alpha不匹配 [英] Python decimal.Decimal precision doesn't match wolfram alpha's
问题描述
我有以下python代码:
I have the following python code:
In [1]: import decimal
In [2]: decimal.getcontext().prec = 80
In [3]: (1-decimal.Decimal('0.002'))**5
Out[3]: Decimal('0.990039920079968')
不应该匹配0.99003992007996799440405766290496103465557098388671875
根据此 http ://www.wolframalpha.com/input/?i = SetPrecision%5B%281 +-+ 0.002%29%5E5%2C + 80%5D 吗?
Shouldn't it match 0.99003992007996799440405766290496103465557098388671875
according to this http://www.wolframalpha.com/input/?i=SetPrecision%5B%281+-+0.002%29%5E5%2C+80%5D ?
推荐答案
Wolfram alpha在这里实际上是错误的.
Wolfram alpha is actually wrong here.
(1 - 0.002) ** 5
恰好是0.990039920079968
.
您可以通过简单地评估.
之后是否有15位数字与5 * 3
匹配来验证这一点,其中3是表达式(1 - 0.002)
中.
之后的位数.根据定义,第15位之后不能有任何数字.
You can verify that by simply assessing that there are 15 digits after the .
, which matches 5 * 3
, 3 being the number of digits after the .
in the expression (1 - 0.002)
. There couldn't be any digit after the 15th by definition.
多挖一点给我带来了一些有趣的东西:
A little more digging got me something interesting:
此符号Decimal('0.002')
使用此 exact 值创建实际的小数.使用Decimal(0.002)
十进制是由浮点数而不是字符串构成的,从而产生了不精确性.使用此表示法是原始公式:
This notation Decimal('0.002')
creates an actual decimal with this exact value. Using Decimal(0.002)
the decimal is made from a float rather than a string, creating an imprecision. Using this notation is the original formula :
(1-decimal.Decimal(0.002))**5
返回Decimal('0.99003992007996799979349352807411754897106595345737537649055432859002826694496107'
,它实际上是.
之后的80位数字,但与Wolfram alpha值不同.
Returns Decimal('0.99003992007996799979349352807411754897106595345737537649055432859002826694496107'
which is indeed 80 digits long after the .
, but different from the wolfram alpha value.
这可能是由于python和Wolfram alpha浮点表示形式之间的精度差异所致,这进一步表明Wolfram alpha在使用SetPrecision时正在使用浮点数.
This is probably caused by a difference of precision between python and wolfram alpha floating point representation, and is a further indication that wolfram alpha is using floats when SetPrecision is used.
Nota: directly asking for the result returns the correct value (see http://www.wolframalpha.com/input/?i=%281+-+0.002%29%5E5).
这篇关于Python十进制.十进制精度与Wolfram alpha不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!