Python decimal.invalido操作

2024-04-25 12:04:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我在运行这样的程序时总是会遇到这个错误:

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'>]

另外,为什么我要从控制台得到这个结果?

>>> Decimal(2/3)
Decimal('0.66666666666666662965923251249478198587894439697265625')

谢谢


Tags: fromtestimport程序most错误callfile
2条回答

我这样解决了这个问题

from decimal import *

b = (Decimal(2) / Decimal(3)).quantize(Decimal(1)/(10**Decimal(30)))

Decimal(b)

量子化允许你获得必要的精度

Decimal的初始值设定项不能接受包含斜线的字符串。非正式地说,字符串必须看起来像一个数字。This table显示字符串参数的正确格式。如果你想计算2/3

>>> Decimal(2)/Decimal(3)
Decimal('0.6666666666666666666666666667')

Decimal(2/3)给出了Decimal('0.66666666666666662965923251249478198587894439697265625'),因为2/3的计算结果是一个浮点数,而浮点数本身具有有限的精度。这是计算机能够用浮点表示2/3的最接近的值。

相关问题 更多 >