Python十进制.InvalidOperation错误 [英] Python decimal.InvalidOperation error
问题描述
运行以下命令时,我总是会收到此错误:
i'm always getting this error when running something like this:
from decimal import *
getcontext().prec =30
b=("2/3")
Decimal(b)
错误:
Traceback (most recent call last):
File "Test.py", line 6, in <module>
Decimal(b)
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]
此外,为什么我要从控制台获得此结果?
Also, why do i get this result from the console?
>>> Decimal(2/3)
Decimal('0.66666666666666662965923251249478198587894439697265625')
谢谢
推荐答案
Decimal
的初始化程序不能接受带斜杠的字符串.非正式地,字符串必须看起来像单个数字. 此表显示了字符串参数的正确格式.如果要计算2/3,请执行
Decimal
's initializer can't accept strings with a slash in them. Informally, the string has to look like a single number. This table shows the proper format for string arguments. If you want to calculate 2/3, do
>>> Decimal(2)/Decimal(3)
Decimal('0.6666666666666666666666666667')
Decimal(2/3)
给出Decimal('0.66666666666666662965923251249478198587894439697265625')
的原因是2/3计算为浮点数,并且浮点数固有地具有有限的精度.这是计算机最接近使用浮点数表示2/3
的地方.
Decimal(2/3)
gives Decimal('0.66666666666666662965923251249478198587894439697265625')
because 2/3 evaluates to a floating point number, and floats have inherently limited precision. That's the closest the computer can get to representing 2/3
using a float.
这篇关于Python十进制.InvalidOperation错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!