Python decimal.InvalidOperation 错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33827179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python decimal.InvalidOperation error
提问by Matteo
i'm always getting this error when running something like this:
运行这样的东西时,我总是收到这个错误:
from decimal import *
getcontext().prec =30
b=("2/3")
Decimal(b)
Error:
错误:
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')
Thanks
谢谢
采纳答案by Kevin
Decimal
's initializer can't accept strings with a slash in them. Informally, the string has to look like a single number. This tableshows the proper format for string arguments. If you want to calculate 2/3, do
Decimal
的初始值设定项不能接受带有斜线的字符串。非正式地,字符串必须看起来像一个数字。下表显示了字符串参数的正确格式。如果要计算 2/3,请执行
>>> Decimal(2)/Decimal(3)
Decimal('0.6666666666666666666666666667')
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.
Decimal(2/3)
给出Decimal('0.66666666666666662965923251249478198587894439697265625')
是因为 2/3 计算为浮点数,而浮点数本身具有有限的精度。这是计算机可以2/3
使用浮点数表示的最接近的值。
回答by user11614811
I solved the problem like this
我解决了这样的问题
from decimal import *
b = (Decimal(2) / Decimal(3)).quantize(Decimal(1)/(10**Decimal(30)))
Decimal(b)
quantize allows you to get the necessary accuracy
quantize 允许您获得必要的准确性